Search is not available for this dataset
query
stringlengths
7
355k
document
stringlengths
9
341k
metadata
dict
negatives
sequencelengths
0
101
negative_scores
sequencelengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
2. Create a constructor function called `Dog` that sets a property on itself within the constructor. The property should be called `says` and the value should be `life is ruff` DONE
function Dog(){ this.says = 'life is ruff' }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function Dog () {\n this.legs = 4;\n this.bark = function() {\n return 'arf arf;;\n }\n }", "function Dog (breed) {\n this.breed = breed;\n}", "function Dog (breed) {\n this.breed = breed;\n}", "function Dog (breed) {\n this.breed = breed;\n}", "function Dog (breed) {\n this.breed = breed;\n}", "function Dog (breed) {\n this.breed = breed;\n}", "function Dog(){//Constructors are functions that create new objects.\n this.name = 'Charlie';//They define properties and behaviors that will belong to the new object.\n this.color = 'Red-brown';//'this.attribute' etc.\n this.numLegs = 4;\n}", "function Dog() {\n this.name = \"Albert\";\n this.color = \"Brown\";\n this.numLegs = 4;\n}", "function Dog(){\n this.name = \"Bob\";\n this.color = \"red\";\n this.numLegs = 4;\n}", "function Dog() {\n this.name = \"Rex\";\n this.color = \"Black\";\n this.numLegs = 4;\n}", "function Dog(name, age, color) {\n this.name = name;\n this.age = age;\n this.color = color;\n this.bark = function () {\n console.log(\n this.name +\n \" the \" +\n this.age +\n \" year old \" +\n this.color +\n \" dog\" +\n \" just barked!\"\n );\n };\n}", "function Dog() {\n this.name = \"Rupert\";\n this.color = \"brown\";\n this.numLegs = 4;\n}", "function Dog() {\n this.name = \"Rupert\";\n this.color = \"brown\";\n this.numLegs = 4;\n}", "function Dog() {\n this.name = \"Rusty\";\n this.color = \"Golden\";\n this.numLegs = 4;\n}", "function Dog(age, legs, name) {\n this.age = age;\n this.legs = legs;\n this.name = name;\n\n var dogCounter = 0;\n\n this.bark = function() {\n ++dogCounter;\n console.log(`${this.name} barked! Count: ${dogCounter}`);\n }\n}", "function Animal() {\n this.kind = \"Dog\"\n}", "function Dog(age, name){\n this.age = age;\n this.name = name;\n}", "function Dog(age, name, breed){\n this.age = age;\n this.name = name;\n this.breed = breed;\n}", "function Dog() {\n this.name = \"Fluffers\";\n this.color = \"yellow\";\n this.numLegs = 4;\n}", "function Dog() {\nthis.name = \"Rupert\";\nthis.color = \"brown\";\nthis.numLegs = 4;\n}", "function Dog() {\n this.name = \"Tarzan\";\n this.color = \"brown\";\n this.numLegs = 4;\n}", "function Dog(name, age, breed = 'Australian Shepard') {\n Mammal.call(this, name, age);\n this.breed = breed;\n}", "function Dog (name, breed) {\n this.name = name,\n this.breed = breed,\n this.sayName = function (sound) {\n console.log(`My name is ${this.name}. I am a ${this.breed}. I say ${sound}`);\n }\n}", "function Dog(name, age) {\n this.name = name;\n this.age = age;\n}", "function Dog(name,breed,mood,hungry){\n this.name = name\n this.breed = breed\n this.mood = mood\n this.hungry = hungry\n}", "function makeDog() {\n return {\n name: \"Jet\",\n // here we have to use an anonymous function to ensure the context\n // is set correctly when this method is invoked\n speak: function (word) {\n return this.name + \" says \" + word;\n },\n changeName: function (newName) {\n this.name = newName;\n return this.name;\n },\n };\n}", "function Dog () {\n \t//this.bark = function() {\n \t//\treturn 'woof';\n \t//};\n }", "function Dog(hungry) {\n\n this.status = \"normal\";\n this.color = \"black\";\n this.hungry = \"hungry\";\n}", "function Dog(name) {\n this.name = name; \n}", "function Dog(name, breed) {\n this.name = name;\n this.breed = breed;\n}", "function Dog(name, breed, mood, hungry){\n this.name = name;\n this.breed = breed;\n this.mood = mood;\n this.hungry = hungry;\n}", "function Dog(age, breed, color) {\n this.age = age;\n this.breed = breed;\n this.color = color;\n}", "function Dog(name, breed) {\n this.name = name;\n this.breed = breed;\n}", "function Dog() {\n this.name = \"Rupert\";\n this.color = \"brown\";\n this.numLegs = 4;\n }", "function Dog() {\n this.name = \"Rupert\";\n this.color = \"brown\";\n this.numLegs = 4;\n }", "function Dog(name, breed, mood, hungry) {\n this.name = name;\n this.breed = breed;\n this.mood = mood;\n this.hungry = hungry;\n}", "function Dog(name, breed, mood, hungry) {\n this.name = name;\n this.breed = breed;\n this.mood = mood;\n this.hungry = hungry;\n}", "function Dog(Breed, Age, Colour) {\r\n this.Dog_Breed = Breed;\r\n this.Dog_Age = Age;\r\n this.Dog_Colour = Colour;\r\n}", "function Dog (name, breed, mood, hungry) {\n this.name = name;\n this.breed = breed;\n this.mood = mood;\n this.hungry = hungry;\n}", "function Dog() {\n this.name = \"Albert\";\n this.color = \"blue\";\n this.numLegs = 4;\n }", "function dogClass() {\n // properties of the class goes here\n this.name = 'default';\n}", "function Dog (name, breed) {\n this.name = name;\n this.breed = breed;\n\n this.greet = function greet () {\n console.log(`Woof, I am ${this.name} and I'm a ${this.breed}`)\n }\n}", "function Dog() {\n this.name = \"Albert\";\n this.color = \"brown\";\n this.numLegs = 4;\n }", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog () {\n this.legs = 4;\n }", "function Dog(color) {\r\n this.name = \"Woof\";\r\n this.color = color;\r\n this.legs = 4;\r\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog(name) {\n this.name = name;\n}", "function Dog (name, color) {\n this.name = name\n this.status = 'normal'\n this.hungry = true\n this.pet = function (name) {\n this.status = 'happy'\n }\n}", "function Dog(name, breed, mood, hungry){\n\tthis.name = name;\n\tthis.breed = breed;\n\tthis.mood = mood;\n\tthis.hungry = hungry;\n}", "function Dog () {\n this.status = \"\",\n this.color = \"\",\n this.hungry =\"\"\n}", "function Dog(Name, Breed, Age, Color) {\r\n this.Dog_Name = Name;\r\n this.Dog_Breed = Breed;\r\n this.Dog_Age = Age;\r\n this.Dog_Color = Color;\r\n}", "function Dog(){}", "function Dog(){}", "function Dog(name){\r\n Pet.call(this, name);\r\n \r\n this.whatAmI = function() {\r\n return \"I am a Dog.\"\r\n } \r\n}", "function Dog(isGoodBoy, name) {\n this.isGoodBoy = isGoodBoy;\n this.name = name;\n }", "function Dog(petName, petType, canBark){\n //Inherit instance properties\n Pets.call(this, petName, petType);\n this.canBark = canBark;\n this.petImage=\"dog.jpg\";\n}", "function Dog(name) {\n\tthis.name = name;\n}", "function Animal(obj) {\n this.species = obj.species,\n this.weight = obj.weight,\n this.sound = obj.sound,\n this.speak = function() {\n return `The ${this.species} weighs ${this.weight}lbs and ${this.sound}s`\n }\n}", "function Dog(name, color) {\n this.name = name; \n this.color = color; \n}", "function doggy(name){\n this.name = name;\n }", "function Dog(name, colors, age) {\n this.name = name;\n this.color = colors;\n this.age = age;\n}", "function Animals(food) {\n this.food = food,\n this.eat = function () {\n return (`This animal like to eat ${this.food}`);\n }\n}", "function Dog(name) {\n this.name = name; \n }", "function Animal(voice){\n this.voice = voice || 'grunt';\n}", "constructor() {\n this.age = 0;\n this.color = 'pink';\n this.food = 'jelly';\n }", "function Dog(name, breed, color) {\n this.name = name;\n this.breed = breed;\n this.color = color;\n}", "function Dog(name) {\n this.name = name; \n }", "function Dog(name) {\n this.name = name;\n }", "function Dog(name) {\n this.name = name;\n }", "function Dog(name) {\n this.name = name;\n }", "function Dog(name) {\n this.name = name;\n }", "function Dog(name, color) {\n this.name = name;\n this.color = color;\n this.numLegs = 4;\n}", "function Dog(numEars, numNose){\n var ears = numEars;\n var nose = numNose;\n\n Object.defineProperties(\n this,\n {\n ears : {\n get: function(){\n return ears;\n },\n set: function(numEars){\n ears = numEars;\n }\n }\n }\n );\n}", "function Animal(sound) {\n this.speak = sound;\n}", "function Dog(name, color) {\n this.name = name;\n this.color = color;\n this.numLegs = 4;\n}", "function Dog(name, breed) {\n\t\tthis.name = name;\n\t\tthis.breed = breed;\n}", "function animal(species) {\n this.confirmaton = `I'm a `;\n this.species = species;\n this.speak = function() {\n console.log(this.confirmaton + this.species);\n }\n}" ]
[ "0.74398655", "0.7401345", "0.73636514", "0.73636514", "0.73636514", "0.73636514", "0.72722626", "0.7203767", "0.7194559", "0.7180483", "0.7175434", "0.7175424", "0.7175424", "0.717116", "0.71687704", "0.7153247", "0.714996", "0.7149823", "0.7143825", "0.71397036", "0.71206236", "0.71161366", "0.71067894", "0.70979017", "0.70836204", "0.70628834", "0.7062586", "0.7052118", "0.7002511", "0.6992198", "0.69858116", "0.69720054", "0.6961983", "0.6961982", "0.6961982", "0.69571984", "0.69571984", "0.69488", "0.69452757", "0.6935209", "0.6927973", "0.69158524", "0.6900965", "0.6893919", "0.6893919", "0.6893919", "0.6893919", "0.6893919", "0.6893919", "0.6893919", "0.6893919", "0.6893919", "0.6893919", "0.6893919", "0.6893919", "0.6893919", "0.6893919", "0.6893919", "0.6893919", "0.6893919", "0.6893919", "0.6893919", "0.68875664", "0.6885604", "0.68780774", "0.68780774", "0.68780774", "0.68780774", "0.68780774", "0.68780774", "0.6874796", "0.6853096", "0.6793643", "0.6788", "0.67388356", "0.67388356", "0.6736525", "0.67282385", "0.6704333", "0.66716295", "0.6656301", "0.66278756", "0.66232544", "0.6619488", "0.66053426", "0.6589448", "0.6580112", "0.65654606", "0.656148", "0.65539706", "0.6537572", "0.6537572", "0.6537572", "0.6537572", "0.64984053", "0.64940596", "0.6474499", "0.6473483", "0.6472979", "0.64715654" ]
0.8282548
0
3. Create a constructor function called `Cat` that has a method on it's prototype called `growl` that returns the string `meow`; create an instance of this called `cat` DONE
function Cat(){ }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function newCat(name) {\n\tconsole.log(this); // this refers to the global-object i.e. Window\n\treturn {\n\t\tname : name,\n\t\ttalk : function() {\n\t\t\tconsole.log(this); // this refers to the object containing the \"talk\" method\n\t\t\tconsole.log(this.name + \" says Meoow\");\n\t\t},\n\t};\n}", "function Cat(){ this.name = 'MrPurr'; }", "function Cat(){ this.name = 'MrPurr'; }", "function Cat(){ }", "function Cat(){}", "function Cat (name) {\n Animal(name);\n}", "function Cat (name) {\n var instance = new Animal(name);\n return instance;\n}", "function Cat(){ this.name = 'tom'; }", "function Cat(name, breed) {\n this.name = name;\n this.breed = breed;\n}", "function Cat(name, breed) {\n this.name = name;\n this.breed = breed;\n}", "function makeCat() {\n VCAT = new Catgirl();\n return VCAT;\n}", "function Cat(name){\n this.name = name;\n this.sound = 'Meow'\n}", "function kittyCreator (catInfo) {\n console.info('kittyCreator functional, human.');\n var kNew = this;\n \n this.name = catInfo.name || 'Purrcival';\n this.color = catInfo.color;\n this.breed = catInfo.breed;\n this.dead = false;\n this.lives = 9;\n this.inventory = [canOfTuna, prettyKittyCollar];\n this.class = 'Catventurer';\n this.desc = \"You examine yourself. You're looking purrty good! You are \" + this.name + \", the \" + this.breed + \" \" + this.class + \"! Your fur is \" + this.color + \" and \" + this.furLength + \" in length. You could really go for a can of tuna.\"; //ou have \" + this.lives + \" lives left, and y\n this.atkBoost = 0;\n this.type = 'kitty';\n \n if (kNew.breed == 'siamese'){\n kNew.attack = dieTypes[4];\n kNew.hp = 50;\n kNew.maxHp = 50;\n kNew.furLength = 'short';\n kNew.meowType = 'with barely restrained rage';\n }\n if (kNew.breed == 'maineCoon'){\n kNew.attack = dieTypes[0];\n kNew.hp = 75;\n kNew.maxHp = 75;\n kNew.furLength = 'long';\n kNew.meowType = 'lazily';\n }\n if (kNew.breed == 'tabby'){\n kNew.attack = dieTypes[1];\n kNew.hp = 60;\n kNew.maxHp = 60;\n kNew.furLength = 'average';\n kNew.meowType = 'adorably';\n }\n party.push(this);\n }", "function Cat(name){\r\n Pet.call(this, name);\r\n \r\n this.whatAmI = function() {\r\n return \"I am a Cat.\"\r\n } \r\n}", "introduceCat() {\n console.log(`This is ${this._name}. It's a ${this._breed}.`);\n }", "function Cat(name) {\n this.name = name;\n}", "function Cat(name) {\n this.name = name;\n}", "function Cat(name) {\n this.name = name;\n}", "function Cat( cat_name ) {\n var name = cat_name;\n this.getName = function() {\n return name;\n };\n }", "function Cat() {\n this.name = \"Ola\";\n this.age = 20;\n}", "function Cat(name) {\n this.name = name; \n }", "function Animal() {\n // arguments\n this.spaces = \"Animal\";\n this.growup = function () {\n console.log(\"Stronger\");\n }\n}", "function cat() {\r\n return cat.meow\r\n}", "function Cat(name) { \n this.age = 1;\n this.name = name;\n}", "function UncordialCat(greeter) {\n this.greeting = 'angered emotional';\n this.greeter = greeter;\n this.speak = function() {\n console.log(this.greeting + this.greeter);\n console.log(this);\n };\n }", "function Coffee(type, strength, sugar, milk) {\n //var this = {};\n\n this.typeOfCoffee = type;\n this.coffeeStrength = strength;\n this.sugar = sugar;\n this.withMilek = milk;\n\n this.addSugar = function() {\n this.sgar++;\n };\n this.printInfo = function() {\n console.log(\"Our coffee is:\" + this.typeOfCoffee);\n\n //1 or 2 --> weak\n //3 or 4-->regular\n //5 or 6 --> strong\n\n switch (this.coffeeStrength) {\n case 1:\n case 2:\n console.log(\"Weak coffee\");\n break;\n case 3:\n case 4:\n console.log(\"Regular coffee.\");\n break;\n case 5:\n case 6:\n console.log(\"Strong coffee.\");\n break;\n }\n //>2 sweet coffee\n\n if (this.sugar > 2) {\n console.log(\"Super sweet coffee\");\n } else {\n console.log(\"Not so sweet coffee.\");\n }\n var milkMessage;\n milkMessage = this.withMilk == true ? \"with milk\" : \"without milk\";\n console.log(milkMessage);\n };\n}", "function Cat(name, likes, goodWithDogs, goodWithOtherCats, goodWithKids, breed) {\n console.log(this);\n this.name = name;\n this.age = 0;\n this.likes = likes;\n this.goodWithDogs = goodWithDogs;\n this.goodWithOtherCats = goodWithOtherCats;\n this.goodWithKids = goodWithKids;\n this.breed = breed;\n this.imagePath = `./images/${this.name}.jpeg`;\n}", "function Cat(firstName, lastName, favoriteFood) {\n if(firstName === undefined || lastName === undefined || favoriteFood === undefined) {\n return undefined;\n }\n this.firstName = firstName;\n this.lastName = lastName;\n this.favoriteFood = favoriteFood;\n\n this.introduction = function() { // will not be saved\n return 'Hi, my name is ' + this.firstName + ' ' + this.lastName +\n '. I am a cat, and I like to eat ' + this.favoriteFood;\n };\n}", "function Cat(name, color){\n this.name = name;\n this.color = color;\n}", "function NinjaConstructor(name, prevOccupation) {\n this.name = name;\n this.prevOccupation = prevOccupation\n this.introduce = function() {\n console.log(\"Hi my name is \" + this.name + \". I used to be a \" + this.prevOccupation + \" and now I'm a Ninja!\");\n }\n}", "function Cat(name, color){\r\n this.name = name\r\n this.color = color\r\n}", "function Animals(food) {\n this.food = food,\n this.eat = function () {\n return (`This animal like to eat ${this.food}`);\n }\n}", "function Monkey(name, species) {\n this.name = name;\n this.species = species;\n this.foodsEaten = [];\n\n this.eatSomething = function(food) {\n this.foodsEaten.push(food);\n return food;\n };\n\n this.introduce = function() {\n return \"Hi, I'm \" + this.name + \" and I'm a \" + this.species + \" who has eaten\n \" + this.foodsEaten;\n };\n}", "function Cons() {\n\tthis.age = 21;\n\tthis.sex = 'male';\n\treturn 'spider';\n}", "function Cat(name, color) {\n this.name = name;\n this.color = color;\n}", "function Cat(name) {\n\tthis.name = name;\n\tconsole.log(this); // 'this' refers to the Cat object that is being created\n}", "function Catberry() {\n\tCatberryBase.call(this);\n}", "function createCats(cats) {\n\n}", "function Cat(name, color) {\n this.name = name;\n this.color = color;\n}", "function Kitten(name, age) {\n this.name = name;\n this.age = age;\n\n //we can eliminate this redundancy by using the constructor's prototype\n // this.meow = function () {\n // console.log(this.name + ' says \"MEOW!\"');\n // };\n}", "function Cat(name, age, color){\n var cat = {\n name: name,\n age: age,\n color: color\n };\n return cat;\n}", "function NinjaConstructor(name, prevOccupation) {\n var this = {}; // <-- PAY ATTENTION TO THIS LINE!\n this.name = name;\n this.prevOccupation = prevOccupation\n this.introduce = function() {\n console.log(\"Hi my name is \" + this.name + \". I used to be a \" + this.prevOccupation + \" and now I'm a Ninja!\");\n }\n return this; // <-- AND THIS LINE!\n}", "function Animal() {}", "function Animal() {}", "function Animal() {}", "function Animal() {}", "function Animal() {}", "function Animal() {}", "function Animal() {}", "function animal(species) {\n this.confirmaton = `I'm a `;\n this.species = species;\n this.speak = function() {\n console.log(this.confirmaton + this.species);\n }\n}", "function Animal(){ }", "function Animal(){ }", "static meow() {\n console.log(\"Meow Meow Meow Cat Lovers\");\n }", "function makeAnimal(){\n //create an animal\n var animal = {};\n animal.name = \"name\";\n animal.age = \"age\";\n animal.speak = function(){\n console.log(\"Hello, my name is \"+ this.name);\n }\n //return the animal object\n return animal;\n}", "function cat(obj) {\n this.name = obj.name;\n this.nickname = obj.nickname;\n this.speak = function() {\n console.log(\"This new binding: \", this);\n console.log(\n `Meow! My name is ${this.name} and my nickname is ${this.nickname}!`\n );\n };\n}", "function Cat(name) {\n this.name = name;\n\n if (! Cat.inst) {\n Cat.inst = this;\n }\n\n return Cat.inst;\n}", "function Animal() { }", "function Animal() { }", "function Animal() { }", "function Animal() { }", "function Animal() { }", "function Animal() { }", "function Animal() { }", "function Animal() { }", "function Animal() { }", "function Animal() { }", "function Animal() { }", "function Animal() { }", "function Animal() { }", "function Animal() { }", "function Animal() { }", "function Ninja(name, health=100) {\n // create a private variable that stores a reference to the new object we create\n var self = this;\n var strength =3;\n var speed =3;\n this.nameT = name;\n this.healthT =health;\n\n this.sayName = function(){\n console.log(`My ninja name is ${this.nameT}`)\n } \n this.showStats = function() {\n console.log(`Name: ${this.nameT} , Health is ${this.healthT} , Speed: ${speed} , Strength${strength}` )\n }\n \n this.drinkSake = function() {\n this.healthT +=10;\n }\n\n\n // this.method = function() {\n // console.log( \"I am a method\");\n\n // var privateMethod = function() {\n // console.log(\"this is a private method for \" + self.name);\n // console.log(self);\n // }\n // this.age = age;\n // this.greet = function() {\n // console.log(\"Hello my name is \" + this.name + \" and I am \" + this.age + \" years old!\");\n // // we can access our attributes within the constructor!\n // console.log(\"Also my privateVariable says: \" + privateVariable)\n // // we can access our methods within the constructor!\n // privateMethod();\n // }\n}", "function Animal (name, color, weight, personality){\n this.name = name;\n this.color = color;\n this.weight = weight;\n this.personality = personality;\n this.bio = `${this.name} is ${this.color} and weighs ${this.weight} pounds`;\n}", "function Animal() {\n this.kind = \"Dog\"\n}", "function Animal(species, call) {\n this.species = species;\n this.call = call;\n this.speak = function () {\n \tconsole.log(\"The \" + this.species + \" says \" + this.call)\n }\n}", "function Animal(species, call) {\n this.species = species;\n this.call = call;\n this.speak = function () {\n \tconsole.log(\"The \" + this.species + \" says \" + this.call)\n }\n}", "function Dog(){//Constructors are functions that create new objects.\n this.name = 'Charlie';//They define properties and behaviors that will belong to the new object.\n this.color = 'Red-brown';//'this.attribute' etc.\n this.numLegs = 4;\n}", "function AnimalMaker(name) {\n return {\n speak: function () {\n console.log(\"my name is \", name);\n },\n name: name,\n owner: 'Bianca'\n }\n}", "function Ninja(name, health=100, speed=3, strength=3){\n this.name=name;\n this.health=health;\n this.speed=speed;\n this.strength = strength;\n this.sayName = function(){\n console.log(\"My ninja name is \"+name);\n };\n}", "function Ninja(name){\n\n\tlet speed = 3;\n\tlet strength = 3;\n\tthis.name = name;\n\tthis.health = 100;\n\n\tthis.sayName = function(){\n\t\tconsole.log(this.name);\n\t}\n\n\tthis.showStats = function(){\n\t\tconsole.log(`Name: ${this.name}, Health: ${this.health}, Strength: ${strength}, Speed: ${speed}`);\n\t}\n\n\tthis.drinkSake = function(){\n\t\tthis.health += 10;\n\t\treturn this;\n\t}\n\n\tthis.punch = function(target){\n\t\tif(target instanceof Ninja){\n\t\t\ttarget.health -= 5;\n\t\t\tconsole.log(`${target.name} was punched by ${this.name} and health is down to ${target.health}`);\n\t\t}\n\t\telse{\n\t\t\tconsole.log(`You can't punch a ${target.constructor.name}`);\n\t\t}\n\t}\n\n\tthis.kick = function(target){\n\t\tif(target instanceof Ninja){\n\t\t\ttarget.health -= 15;\n\t\t\tconsole.log(`${target.name} was kicked by ${this.name} and health is down to ${target.health}`);\n\t\t}\n\t\telse{\n\t\t\tconsole.log(`You can't kick a ${target.constructor.name}`);\n\t\t}\n\t}\n\n}", "function Lion(name) { // Constructor Function\n this.name = name;\n}", "function Fruit() {\r\n\tthis.type = \"apple\"\r\n}", "function Dog () {\n this.legs = 4;\n this.bark = function() {\n return 'arf arf;;\n }\n }", "function makeDog() {\n return {\n name: \"Jet\",\n // here we have to use an anonymous function to ensure the context\n // is set correctly when this method is invoked\n speak: function (word) {\n return this.name + \" says \" + word;\n },\n changeName: function (newName) {\n this.name = newName;\n return this.name;\n },\n };\n}", "function Moto() {\n this.name = \"Honda\"\n this.sayName = \"my favorite bike is \" + this.name\n}", "function Ninja(){\n this.name = \"Ninja\";\n }", "function Human () {\nthis.pet = function (dogName) {\n return sadie.status = \"happy\"\n}\nthis.feed = function (feedDog) {\n return moonshine.hungry = false\n}\nthis.cool = function () {\n}\n}", "function FunHuman() { // is will be called with NEW use capital letter\n this.name = 'Pesho';\n this.address = 'Mladost';\n this.walk = function() {};\n}", "function Animal(obj) {\n this.species = obj.species,\n this.weight = obj.weight,\n this.sound = obj.sound,\n this.speak = function() {\n return `The ${this.species} weighs ${this.weight}lbs and ${this.sound}s`\n }\n}", "function Cat(color, weight) {\n this.color = color;\n this.weight = weight;\n}", "function Human (name, cool) {\n this.name = name;\n this.cool = cool;\n this.feed = function(dog) {\n dog.hungry = false;\n }\n this.pet = function(dog) {\n dog.status = \"happy\";\n }\n}", "function Animal(){}", "function Animal(){}", "function Furniture() {\n this.make = \"Chair\";\n}", "function CreateCat() {\n //Validate the pet name which must be present\n var sPetName=document.getElementById(\"inputPetName\").value;\n if (sPetName=='')\n {\n alert (\"Error, name missing\"); return;\n }\n\n //Determine if this cat has a scratching problem\n var scratches=document.getElementById(\"scratches\").checked;\n\n //Instantiate the Cat, which inherits from pet\n var Cat1= new Cat(sPetName, \"Cat\", scratches); //We are saying that \"Tiger\" is not the scratching kind of cat by passing false.\n\n console.log(Cat1.getInfo() + \" Can Scratch: \" + Cat1.getCanScratch());\n var warning=\"\";\n if (Cat1.getCanScratch()) warning=\"Warning - This cat can scratch!\";\n\n // Create a new list item to hold the pet\n var node = document.createElement(\"LI\");\n\n //Add an image to the pet\n var petImage = document.createElement(\"img\");\n petImage.setAttribute(\"src\", \"../img/cat.jpg\");\n petImage.setAttribute(\"height\", \"100\");\n petImage.setAttribute(\"width\", \"100\");\n node.appendChild(petImage);\n\n // Append the text to <li>\n var textnode = document.createTextNode(Cat1.getInfo() + \" \" + warning); // Create a text node\n node.appendChild(textnode);\n\n //Create a button to remove the pet\n var nodeButton = document.createElement(\"button\");\n nodeButton.innerHTML=\"remove\";\n nodeButton.className = \"button\";\n node.appendChild(nodeButton);\n\n //This will make our remove button work when it is clicked\n nodeButton.addEventListener('click', function(e) {\n e.currentTarget.parentNode.remove();\n }, false);\n\n // Append the text to the pet list\n document.getElementById(\"petObjects\").appendChild(node); // Append <li> to <ul> with id=\"myList\"\n\n //document.getElementById(\"output\").innerHTML=\"Added a new cat named \" + Cat1.getInfo() + \" \" + warning;\n}", "function ninjaConstructor(name, cohort){\n\tvar ninja = {};\n\tvar beltLevels = ['white', 'yellow', 'blue', 'red', 'black'];\n\tif ( typeof(name) === 'string' && typeof(cohort) === 'string'){\n\t\tninja.name = name;\n\t\tninja.cohort = cohort;\n\t\tninja.beltLevel = beltLevels[0];\n\t} else {\n\t\tconsole.log('Your ninja\\'s name and cohort must be a string!');\n\t\treturn null;\n\t};\n\tninja.levelUp = function(){\n\t\tbeltUpgrade();\n\t\treturn ninja;\n\t};\n\n\tfunction beltUpgrade(){\n\t\t// iterate through our belt levels array\n\t\tfor (var i = 0; i<beltLevels.length-1; i++) {\n\t\t\tif (ninja.beltLevel === beltLevels[i]){\n\t\t\t\tvar index = i;\n\t\t\t};\n\t\t};\n\t\t\n\t\t// update our ninja.beltLevel to the next slot in the array,\n\t\t// but only if the next index slot exists in the length of the array:\n\t\tif (index <= beltLevels.length-1){\n\t\t\tninja.beltLevel = beltLevels[index + 1];\n\t\t\tconsole.log(`${name}'s belt level is now: ${ninja.beltLevel}`);\n\t\t} else {\n\t\t\tconsole.log(`You've reached the highest belt ${ninja.name}!`);\n\t\t};\n\t\t\n\t}; \n\treturn ninja;\n}", "function Human (name) {\n this.name = name\n this.cool = false\n this.pet = function (dogName) {\n dogName.status = 'happy'\n }\n this.feed = function (dogName) {\n dogName.hungry = false\n }\n}", "function Apple (type) {\n this.type = type;\n this.color = \"red\";\n this.getInfo = function() {\n return this.color + ' ' + this.type + ' apple';\n };\n}", "function Animal(name,age,latinName,legsNo){\n this.name=name;\n this.age=age;\n this.latinName=latinName;\n this.legsNo=legsNo;\n this.printAnimal=function(){\n console.log(`${this.name} or also known as ${this.latinName}, in latin, is ${this.age} years old and has ${this.legsNo} legs!`)\n }\n}" ]
[ "0.7306775", "0.72485834", "0.72485834", "0.7077942", "0.7065386", "0.7018846", "0.6913897", "0.69030786", "0.6879301", "0.6879301", "0.6851107", "0.6769632", "0.6761657", "0.674306", "0.6735571", "0.66676795", "0.66676795", "0.66676795", "0.66666317", "0.6658805", "0.66370404", "0.6597965", "0.65973365", "0.6595827", "0.6547149", "0.65129167", "0.6461797", "0.64096993", "0.6393803", "0.63841224", "0.63765377", "0.63552904", "0.63545126", "0.6316339", "0.6294528", "0.62450886", "0.6244588", "0.62426037", "0.623182", "0.62144977", "0.6213822", "0.62118196", "0.6207452", "0.6207452", "0.6207452", "0.6207452", "0.6207452", "0.6207452", "0.6207452", "0.61969936", "0.61920494", "0.61920494", "0.61852664", "0.61819404", "0.6181371", "0.6156762", "0.61422443", "0.61422443", "0.61422443", "0.61422443", "0.61422443", "0.61422443", "0.61422443", "0.61422443", "0.61422443", "0.61422443", "0.61422443", "0.61422443", "0.61422443", "0.61422443", "0.61422443", "0.6071787", "0.60655093", "0.6062839", "0.6060541", "0.6060541", "0.6055625", "0.6045943", "0.60302067", "0.6025833", "0.6023564", "0.6003784", "0.59881014", "0.598585", "0.598072", "0.598068", "0.59760594", "0.59754974", "0.5962034", "0.5941851", "0.59250855", "0.5918438", "0.5918438", "0.5918007", "0.59149235", "0.59131974", "0.591086", "0.59101033", "0.5907915" ]
0.6656884
21
4. Create a constructor called `KeepSecret`. The constructor function itself should accept a parameter called `secret` it should store this in a private variable (use a closure). Add a method to the prototype that is called `squeal` that returns the secret string. DONE
function KeepSecret(secret) { this.secret = secret; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function makesecret() {\n secret = makerandword(); }", "function createSecretHolder(secret) {\n let secr = secret;\n let obj = {\n getSecret: function() {\n return secr;\n },\n setSecret: function(s) {\n secr = s;\n }\n }\n\n return obj;\n}", "function createSecretHolder(secret) {\n var secretObject = {\n secretValue: secret,\n getSecret: function() {\n return this.secretValue;\n },\n setSecret: function(newSecretValue) {\n this.secretValue = newSecretValue;\n }\n };\n return secretObject;\n}", "function privateFunction() {\r\n let secret = \"This is a secret.\";// Changes the scope of that variable to be within the constructor function versus available globally, private property\r\n this.revealSecret = function () {\r\n console.log(secret);\r\n };\r\n}", "function createSecretHolder(secret) {\n let _data = secret;\n\n return {\n getSecret: () => _data,\n setSecret: (arg) => (_data = arg),\n };\n}", "accessSecret(){\n this.#secret(); // method in class be a property\n }", "function secretPassword() {\n var password = 'xh38sk';\n return {\n \t//Code here\n }\n }", "function secretVariable() {\n var private = \"super secret code\";\n return function() {\n return private\n }\n}", "getSecret () {\n const secret = crypto.randomBytes(32);\n const hash = crypto.createHash('sha256').update(secret).digest('hex');\n\n return {\n secret: secret,\n hash: hash\n };\n }", "function secret() {\n\t\tvar unused1;\n\t}", "constructor() { \n \n SecretInfo.initialize(this);\n }", "function setSecretVariable() {\n var private = 'super secret code';\n return function() {\n return private\n }\n}", "function myPowerConstructor(x) {\n var that = otherMaker(x);\n var secret = f(x);\n that.priv = function () {\n ... secret x that ...\n };\n return that;\n}", "function random_secret(len) {\n\tlet s = \"\";\n\tfor(let i = 0; i < len; ++i) {\n\t\ts += Object.fromCharCode(Math.random()*0xffff);\n\t}\n\treturn s;\n}", "function generateSecret(length) {\n var tab = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n var secret = '';\n for (var i=0; i<length; i++) {\n secret += tab.charAt(Math.floor(Math.random() * 64));\n }\n return secret;\n }", "saySecret() {\n console.log('secret');\n }", "function setSecret() {\n var newSecret = {secret: uuid.v4(),\n date: null};\n return createSecret(newSecret).then(function(){return findSecrets()})\n .then(function(secrets){\n if (secrets.length > 12){\n for (var i=0;i<secrets.length-12;i++){\n secrets[i].remove();\n }\n secrets = secrets.slice(secrets.length-13);\n }\n return secrets;\n })\n .fail(function(err) {\n });\n}", "secret() {\n let self = this;\n\n // User-input.\n let client = document.createElement('textarea');\n client.setAttribute('id', 'client');\n client.setAttribute('rows', '1');\n client.setAttribute('tabindex', '1');\n\n\n let caption = document.createElement('p');\n caption.innerHTML = 'Type \"help\" for help.';\n\n self.virtualProtect.appendChild(client);\n self.virtualProtect.appendChild(caption);\n\n client.addEventListener('keypress', function(e) {\n // 'Enter' key.\n if ((e.keyCode || e.which) === 13) {\n self.handleCommand(this.value);\n e.preventDefault();\n\n this.value = \"\";\n }\n }, false);\n }", "static fromSecretName(scope, id, secretName) {\n return new class extends SecretBase {\n constructor() {\n super(...arguments);\n this.encryptionKey = undefined;\n this.secretArn = secretName;\n this.secretName = secretName;\n this.autoCreatePolicy = false;\n }\n get secretFullArn() { return undefined; }\n // Overrides the secretArn for grant* methods, where the secretArn must be in ARN format.\n // Also adds a wildcard to the resource name to support the SecretsManager-provided suffix.\n get arnForPolicies() {\n return core_1.Stack.of(this).formatArn({\n service: 'secretsmanager',\n resource: 'secret',\n resourceName: this.secretName + '*',\n arnFormat: core_1.ArnFormat.COLON_RESOURCE_NAME,\n });\n }\n }(scope, id);\n }", "function generateSecret() {\n let secret = crypto.createHash('sha256')\n .update(uuid.v4())\n .update(crypto.randomBytes(128))\n .digest('hex');\n return secret.substring(0, 40)\n}", "function powerConstructor(x) {\n let that = {}; // object creates\n let privateVar = \"\"; // private members\n let privateFunc = function () {}; // private members\n that.privilegedPublicMethod = function () {\n // use private secret function variable here ..\n };\n}", "function encryption(){\n this.saltrounds = 10;\n this.rawtext = '';\n this.encryptedword = '';\n}", "function SecureRandom() {}", "function Person(name, age, password) {\n this.name = name;// public\n let _age = age; // _hidden\n let _password = password;\n let _brain = \"Powerful\";\n this.setPassword = function (newPassword) {\n _password = newPassword\n }\n this.getBio = function () {\n return `\n Hello, I am ${name}!\n I am ${age} years old\n i have a ${_brain}\n `\n }\n}", "formatSecret() {\n return \"0x\" + this.secret.toString('hex')\n }", "function generateSecret() {\n var i, secret = '';\n\n for (i = 0; i < 14; i++) {\n secret += Math.floor(Math.random() * 36).toString(36)\n }\n return secret;\n}", "function secretValidator(control) {\n var secret = \"turtleneck\";\n var typedSecret = control.value;\n if (secret == typedSecret) {\n return null;\n }\n else {\n return control.value;\n }\n}", "function setSecret(newSecret) {\n bot.secret = newSecret;\n rl.close();\n bot.buildBot();\n}", "function secret() { \t\t//4. This one, because after definitions are hoisted, the functions execute in order and this second \"secret\" fn overwrites the first one.\n\t\tvar unused2;\n\t}", "function generateRandomSecret() {\n\t\tvar ss = Math.floor(Math.random() * (secretSizeMax + 1 - secretSizeMin) + secretSizeMin);\n\t\t\n\t\tvar sec = new Array(); //secret\n\t\tfor (let i = 0; i < ss; i++)\n\t\t\tsec.push(Math.floor(Math.random()*keySize*valSize));\n\t\treturn sec;\n\t}", "function encryptWithPassword(something){\n return sjcl.encrypt(userPassword, something);\n}", "function randomSecret() {\n var result = '';\n var characters = 'ABCDEFGHIJKLMNOPQRSTUVXZabcdefghijklmnopqrstuvxz0123456789';\n var charactersLength = characters.length;\n for ( var i = 0; i < 32; i++ ) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength));\n }\n //console.log( result );\n return result;\n}", "function myPassword(password, confirm) {\n this.mypassword = password;\n this.confirmpassword = confirm;\n}", "function SecretGenerator(manifest, secrets) {\n ApiModule.call(this);\n\n var self = this;\n\n self._manifest = manifest;\n self._secrets = secrets;\n}", "constructor(secret, maxTokenAge) {\n\t\tif (!secret) {\n\t\t\tthrow new Error(\"You must provide a secret!\");\n\t\t}\n\n\t\tthis.secret = new Buffer(secret);\n\t\tthis.maxTokenAge = maxTokenAge || 900000; // 15 minutes\n\t\tthis.iterations = 1000;\n\n\t\t// Use a zero vector as the default IV. It isn't necessary to enforce distinct ciphertexts.\n\t\tthis.iv = new Buffer(8);\n\t\tthis.iv.fill(0);\n\t}", "function SecretKey() {\n var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date();\n\n _public_key2.default.call(this, date);\n /**\n * Packet type\n * @type {module:enums.packet}\n */\n this.tag = _enums2.default.packet.secretKey;\n /**\n * Encrypted secret-key data\n */\n this.encrypted = null;\n /**\n * Indicator if secret-key data is available in decrypted form\n */\n this.isDecrypted = false;\n}", "#secret(){\n console.log(\"this is a secret\")\n }", "static fromUnsafePlaintext(secretValue) { try {\n jsiiDeprecationWarnings.print(\"aws-cdk-lib.aws_secretsmanager.SecretStringValueBeta1#fromUnsafePlaintext\", \"Use `cdk.SecretValue` instead.\");\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, this.fromUnsafePlaintext);\n }\n throw error;\n } return new SecretStringValueBeta1(secretValue); }", "static fromSecretNameV2(scope, id, secretName) {\n return new class extends SecretBase {\n constructor() {\n super(...arguments);\n this.encryptionKey = undefined;\n this.secretName = secretName;\n this.secretArn = this.partialArn;\n this.autoCreatePolicy = false;\n }\n get secretFullArn() { return undefined; }\n // Creates a \"partial\" ARN from the secret name. The \"full\" ARN would include the SecretsManager-provided suffix.\n get partialArn() {\n return core_1.Stack.of(this).formatArn({\n service: 'secretsmanager',\n resource: 'secret',\n resourceName: secretName,\n arnFormat: core_1.ArnFormat.COLON_RESOURCE_NAME,\n });\n }\n }(scope, id);\n }", "function secret() {\n\t\tconsole.log(randomNumber);\n\t}", "function decryptWithYourPrivate() {\n decryptMyPrivate();\n}", "cleanSecrets () {\n this.shared = {}\n\n this.ephemeralKey = { local: null, remote: null }\n this.proposal = { in: null, out: null }\n this.proposalEncoded = { in: null, out: null }\n this.protocols = { local: null, remote: null }\n this.exchange = { in: null, out: null }\n }", "cleanSecrets () {\n this.shared = {}\n\n this.ephemeralKey = { local: null, remote: null }\n this.proposal = { in: null, out: null }\n this.proposalEncoded = { in: null, out: null }\n this.protocols = { local: null, remote: null }\n this.exchange = { in: null, out: null }\n }", "_getSharedSecret() {\n // Once every ~256 attempts, we will get a key that starts with a `00` byte, which\n // can lead to problems initializing AES if we don't force a 32 byte BE buffer.\n return Buffer.from(this.key.derive(this.ephemeralPub.getPublic()).toArray('be', 32));\n }", "function generateSecret(callback) {\n crypto.randomBytes(32, function (err, buf) {\n callback(err, buf && buf.toString('hex'))\n })\n}", "get generateSecretInput() {\n return this._generateSecret;\n }", "function Protect() {\r\n}", "function secretkey(password,secret) {\n\n const hash = crypto.createHmac('sha256', secret)\n .update(password)\n .digest('hex');\n return hash;\n}", "function exportSecret(name, val) {\r\n exportVariable(name, val);\r\n // the runner will error with not implemented\r\n // leaving the function but raising the error earlier\r\n command_1.issueCommand('set-secret', {}, val);\r\n throw new Error('Not implemented.');\r\n}", "function exportSecret(name, val) {\r\n exportVariable(name, val);\r\n // the runner will error with not implemented\r\n // leaving the function but raising the error earlier\r\n command_1.issueCommand('set-secret', {}, val);\r\n throw new Error('Not implemented.');\r\n}", "function SafeString(string) {\n this.string = string;\n}", "function SafeString(string) {\n this.string = string;\n}", "function SafeString(string) {\n this.string = string;\n}", "function SafeString(string) {\n this.string = string;\n}", "function SafeString(string) {\n this.string = string;\n}", "function SafeString(string) {\n this.string = string;\n}", "function SpoofConstructor(name){\n this.name=\"I am \" + name;\n return {name:\"I am Deadpool\"};\n}", "function exportSecret(name, val) {\n exportVariable(name, val);\n // the runner will error with not implemented\n // leaving the function but raising the error earlier\n command_1.issueCommand('set-secret', {}, val);\n throw new Error('Not implemented.');\n}", "function getSecret(lines) {\n\t return lines[secretKey];\n\t}", "function getSecret(lines) {\n\t return lines[secretKey];\n\t}", "function SpeedTestSecrets (SpeedTestVersion) \n\t\t\t{\n\t\t\t\tif (SpeedTestVersion == \"old\")\n\t\t\t\t{\n\t\t\t\t\tglobal_secret = \"fours4me\";\n\t\t\t\t\turl_secret = \"bling^bling\";\n\t\t\t\t\tdate_secret = \"n0v4super\";\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tif (SpeedTestVersion == \"new\")\n\t\t\t\t{\n\t\t\t\t\tglobal_secret = \"aXPB2\";\n\t\t\t\t\turl_secret = \"QV67R\";\n\t\t\t\t\tdate_secret = \"4tE)C4kS\";\n\t\t\t\t}\n\t\t\t\treturn {global_secret: global_secret, url_secret: url_secret, date_secret: date_secret}; //return an object here as its easier to read and understand then array is\n\t\t\t}", "function mystery(input) {\n var secret = 5;\n function mystery2(multiplier) {\n multiplier *= input;\n return secret * multiplier;\n }\n return mystery2;\n}", "function caesarCipher(myString) {\nvar\n}", "function Sandwich(bread, ingredients, cut) {\n this.bread = bread;\n this.ingredients = ingredients;\n this.cut = cut;\n this.serve = function() {\n console.log(\"here's your\" + this.name + \", enjoy!\")\n }\n}", "function encryptWithFriendsPublic() {\n encryptFriendsPublic();\n}", "function getStateSecret(ttl, stateRegistrySize) {\n //1. the secret is a hexString of a random number\n const secret = randomString(12);\n\n //2. states is an LRU cache\n states.length > stateRegistrySize && states.shift();\n states.push(secret);\n\n //3. The state secrets on live in the memory of cf worker until the timeout is reached.\n // When the timeout is reached, the state is deleted from the memory.\n setTimeout(() => hasStateSecretOnce(secret), ttl);\n return secret;\n}", "_clearCachedSecret(secret) {\n if (!!secret && secret === this._cachedSecret) return;\n\n this._cachedSecret = null;\n clearTimeout(this._clearCachedSecretRef);\n this._clearCachedSecretRef = null;\n }", "async function createAndAccessSecret() {\n // Create the secret with automation replication.\n const [secret] = await client.createSecret({\n parent: parent,\n secret: {\n name: secretId,\n replication: {\n automatic: {},\n },\n },\n secretId,\n });\n\n console.info(`Created secret ${secret.name}`);\n\n // Add a version with a payload onto the secret.\n const [version] = await client.addSecretVersion({\n parent: secret.name,\n payload: {\n data: Buffer.from(payload, 'utf8'),\n },\n });\n\n console.info(`Added secret version ${version.name}`);\n\n // Access the secret.\n const [accessResponse] = await client.accessSecretVersion({\n name: version.name,\n });\n\n const responsePayload = accessResponse.payload.data.toString('utf8');\n console.info(`Payload: ${responsePayload}`);\n }", "cleanSecrets() {\n this.shared = {};\n this.ephemeralKey = {\n local: null,\n remote: null\n };\n this.proposal = {\n in: null,\n out: null\n };\n this.proposalEncoded = {\n in: null,\n out: null\n };\n this.protocols = {\n local: null,\n remote: null\n };\n this.exchange = {\n in: null,\n out: null\n };\n }", "function genSecret(nModulus) {\n return bignum(Math.floor(Math.random() * nModulus)).mod(nModulus);\n}", "function getSignature() {\r\n var encode = \"\"\r\n for(var i = 0; i < arguments.length; i++) {\r\n encode += arguments[i]\r\n }\r\n encode += secret\r\n return Qt.md5(encode)\r\n}", "function generateCode() {\n for (i = 0; i < 4; i++) {\n secret[i] = Math.floor(Math.random() * 6);\n }\n return secret;\n}", "function secretNumberGenerator() {\n secretNumber = (Math.floor(Math.random()*100));\n console.log(\"Secret number = \" + secretNumber);\n }", "function Bot(){\n this.name;\n this.userName;\n this.password;\n this.secret;\n}", "async sharedSecret(epub) {\n // todo [REFACTOR]: the keypair from the user will not be accessible in future; must be moved to a secure section, better to a SE (secure element)\n return everblack().secret(epub, this.root._.sea);\n }", "function decryptFromPassword(something){\n return sjcl.decrypt(userPassword, something);\n}", "function Blowfish() {}", "function Blowfish() {}", "function Blowfish() {}", "function requestSecret(secret_id) {\n base.emit(\"request-secret\", {\n url: document.location.toString(),\n secret_id: secret_id,\n });\n }", "function func() {\n var priv = \"secret code\";\n}", "function genKey(string){\n //multiple random prime with secretKey\n var key = secretKey*prime;\n\n //intergify string add string to product\n for(var i = 0; i < string.length; i++){\n key+= string.charCodeAt(i);\n }\n\n return key;\n}", "function safe_object_example() {\r\n\r\n\t// This generates unique strings\r\n\tvar serial_maker = function() {\r\n\t\t// private variables only accessible inside this function \r\n\t\tvar prefix = '';\r\n\t\tvar seq = 0;\r\n\t\treturn {\r\n\t\t\tsetPrefix: function(str) {\r\n\t\t\t\tprefix = String(str);\r\n\t\t\t},\r\n\t\t\tsetSequence: function(num) {\r\n\t\t\t\tseq += num;\r\n\t\t\t},\r\n\t\t\tgensym: function() {\r\n\t\t\t\tseq += 1;\r\n\t\t\t\tvar unique = prefix + seq.toString();\r\n\t\t\t\treturn unique;\r\n\t\t\t}\r\n\t\t};\r\n\t};\r\n\r\n\tvar sequer = serial_maker();\r\n\tsequer.setPrefix(\"M\");\r\n\tsequer.setSequence(9034);\r\n\tvar unique = sequer.gensym();\r\n\tconsole.log(unique);\r\n\tconsole.log(sequer.prefix);\t//undefined\r\n\tconsole.log(sequer.seq);\t//undefined\r\n\tvar unique2 = sequer.gensym();\r\n\tconsole.log(unique);\r\n}", "function SecretComponent() {\n return (\n <h1>Secret information for authorized users only.</h1>\n )\n}", "function getSignature() {\n var encode = \"\"\n for(var i = 0; i < arguments.length; i++) {\n encode += arguments[i]\n }\n encode += secret\n return Qt.md5(encode)\n}", "function Songkick(apiKey) {\n Songkick.prototype.apiKey = apiKey;\n}", "function generateSecret(appname, seed) {\n var secretbody = appname + seed;\n var secret = crypto.createHash('sha256').update(secretbody.substring(0, 64)).digest(\"hex\");\n\n console.log(\"----------- Secret ---------------\");\n console.log(secret);\n return secret;\n}", "function SimplePrivate() {\n var foo = 4;\n\n this.getFoo = function (){\n return foo;\n };\n\n\n}", "static fromSecretPartialArn(scope, id, secretPartialArn) {\n return Secret.fromSecretAttributes(scope, id, { secretPartialArn });\n }", "function makeClass(phrase){\r\n // declare a class and return it\r\n return class {\r\n sayHi(){\r\n alert(phrase);\r\n };\r\n };\r\n}", "function CreateSecretWord() {\n \n if (Selection === \"Countries\") {\n var Words = new WordBank(\"Countries\", CountriesWordArray);\n } else if (Selection === \"States\") {\n var Words = new WordBank(\"States\", StatesWordArray);\n } else if (Selection === \"Food\") {\n var Words = new WordBank(\"Food\", FoodWordArray);\n }\n // now this is us creating the secret word, we'll create thew constructor over in the secretwordletters.js and then ship it back over to the main program\n var string = Words.Words[Math.floor((Math.random() * Words.Words.length) + 1)]\n var CurrentSWord = new SecretWordLetters()\n for (var i = 0; i < string.length; i++) {\n var result = string.slice(i, i + 1)\n\n\n CurrentSWord.addLetters(result, false)\n //var PlaceholderArray = [result, false];\n\n //SecretWord.push(PlaceholderArray)\n\n }\n \n \n var Output = \"\"\n for (var i = 0; i < CurrentSWord.Letter.length; i++) {\n Output = Output + \" _\"\n\n }\n console.log(Output)\n \n LetsPlayAGame()\n\n \n function LetsPlayAGame() {\n var GuessInput;\n StopPlaying = false;\n \n GuessLetters()\n\n }\n\n function GuessLetters() {\n if (LifeCounter > 0) {\n inquirer.prompt([{\n type: \"input\",\n name: \"guess\",\n message: \"Pick a letter!\"\n }, ]).then(function(user) {\n \n if (user.guess==\"\"){\n console.log(\"Please input a valid letter\")\n GuessLetters()\n \n } else {\n FixedInput = user.guess.toLowerCase()\n\n // can add a split here if I have time\n for (var i = 0; i < RemainingLetters.length; i++) {\n if (FixedInput == RemainingLetters[i]) {\n console.log(\"guessing the letter: \" + RemainingLetters[i])\n console.log(\"\")\n RemainingLetters[i] = \" \"\n // Variable to pass this value to be checked against secret word\n\n GuessInput = FixedInput\n \n break;\n }\n if (i === 25) {\n console.log(\"You've already used the letter \" + user.guess)\n // need to add a condition for gett ing the letter wrong\n }\n }\n \n CheckSecretWord()\n if (StopPlaying === false) {\n GuessLetters()\n } else {\n console.log(\"Yay you did it!!\")\n console.log(\"Current Winstreak:\" + WinStreak)\n PlayAgain()\n }\n }\n })\n } else {\n WinStreak=0;\n console.log(\"\")\n PlayAgain()\n }\n\n }\n function CheckSecretWord() {\n var UnderScoreCounter = 0;\n var Match = false;\n for (var i = 0; i < CurrentSWord.Letter.length; i++) {\n\n if (GuessInput == CurrentSWord.Letter[i] && CurrentSWord.isRevealed[i] == false) {\n CurrentSWord.isRevealed[i] = true;\n Match = true;\n console.log(\"matched with the letter: \" + CurrentSWord.Letter[i])\n console.log(\"\")\n\n }\n\n }\n if (Match === false) {\n LifeCounter--\n console.log(\"Nope, no '\"+GuessInput+\"'s\")\n console.log(\"Lives Remaining: \"+ LifeCounter )\n }\n // making thing to output _ or a letter\n var Output = \"\";\n for (var i = 0; i < CurrentSWord.Letter.length; i++) {\n\n if (CurrentSWord.isRevealed[i] == true) {\n Output = Output + \" \" + CurrentSWord.Letter[i]\n UnderScoreCounter++;\n if (UnderScoreCounter === CurrentSWord.Letter.length) {\n StopPlaying = true;\n WinStreak++\n \n\n }\n } else {\n Output = Output + \" _\"\n }\n\n }\n console.log(Output)\n }\n\n}", "function makeClass(phrase) {\n // declare a class and return it\n return class {\n sayHi() {\n alert(phrase);\n };\n };\n}", "function privateFunction() {\n\n}", "function getNukeCodes() {\n return \"someSuperSecretPassword\";\n}", "static fromPassword(password) {\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_SecretValue(password);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, this.fromPassword);\n }\n throw error;\n }\n return { generatePassword: false, password };\n }", "function SafeString(string) {\n\t this.string = string;\n\t}", "function SafeString(string) {\n\t this.string = string;\n\t}", "function SafeString(string) {\n\t this.string = string;\n\t}", "justProtect() {\n return this.keyCloak.protect();\n }", "function generateToken (password) {\n return hat();\n}" ]
[ "0.77774686", "0.7397415", "0.7242398", "0.7206933", "0.7100086", "0.6714597", "0.6598306", "0.64396524", "0.62731177", "0.6253335", "0.6126397", "0.6120165", "0.605057", "0.5921582", "0.5865497", "0.58446383", "0.5805677", "0.57992554", "0.5787509", "0.577822", "0.57578784", "0.56668574", "0.5659372", "0.5656803", "0.5655358", "0.5647889", "0.56113297", "0.55704314", "0.5532956", "0.55067855", "0.54958", "0.54626465", "0.5456653", "0.5443511", "0.5437414", "0.543165", "0.5402147", "0.5401073", "0.53785247", "0.53726625", "0.53508663", "0.5322788", "0.5322788", "0.5302844", "0.52634245", "0.5250565", "0.5248885", "0.5214768", "0.52025974", "0.52025974", "0.519199", "0.519199", "0.519199", "0.519199", "0.519199", "0.519199", "0.5180094", "0.51723814", "0.5162009", "0.5162009", "0.51475114", "0.51441324", "0.51380265", "0.51228803", "0.51176006", "0.5116033", "0.51143086", "0.51141036", "0.5109146", "0.5107313", "0.51043516", "0.51027554", "0.51010776", "0.50970507", "0.5079742", "0.5073468", "0.5070882", "0.5070882", "0.5070882", "0.50696456", "0.5066962", "0.5062514", "0.50583977", "0.5043926", "0.50367147", "0.5026159", "0.5025903", "0.5006877", "0.5005746", "0.50043166", "0.5002102", "0.5001742", "0.49924734", "0.4992095", "0.49904612", "0.49758962", "0.49758962", "0.49758962", "0.4971174", "0.49633068" ]
0.81052107
0
5. Create a constructor called `Key`. Create another constructor called `Safe`. Make the Safe constructor take 2 arguments. The first argument can be any piece if data to keep safe. This must be stored using a private variable like you did with KeepSecret. The 2nd param to the `Safe` constructor needs to be an instance of `Key` you need to store it privately as well. Add a function to the Safe prototype called `unlock` that accepts a key. If the key matches the key that was used to create the Safe; then return the secret data. DONE
function Key(){ }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function KeepSecret(secret) {\n this.secret = secret;\n }", "function createSecretHolder(secret) {\n var secretObject = {\n secretValue: secret,\n getSecret: function() {\n return this.secretValue;\n },\n setSecret: function(newSecretValue) {\n this.secretValue = newSecretValue;\n }\n };\n return secretObject;\n}", "function createSecretHolder(secret) {\n let _data = secret;\n\n return {\n getSecret: () => _data,\n setSecret: (arg) => (_data = arg),\n };\n}", "function SecretKey() {\n var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date();\n\n _public_key2.default.call(this, date);\n /**\n * Packet type\n * @type {module:enums.packet}\n */\n this.tag = _enums2.default.packet.secretKey;\n /**\n * Encrypted secret-key data\n */\n this.encrypted = null;\n /**\n * Indicator if secret-key data is available in decrypted form\n */\n this.isDecrypted = false;\n}", "function createSecretHolder(secret) {\n let secr = secret;\n let obj = {\n getSecret: function() {\n return secr;\n },\n setSecret: function(s) {\n secr = s;\n }\n }\n\n return obj;\n}", "function decryptWithYourPrivate() {\n decryptMyPrivate();\n}", "_getSharedSecret() {\n // Once every ~256 attempts, we will get a key that starts with a `00` byte, which\n // can lead to problems initializing AES if we don't force a 32 byte BE buffer.\n return Buffer.from(this.key.derive(this.ephemeralPub.getPublic()).toArray('be', 32));\n }", "function makesecret() {\n secret = makerandword(); }", "unlock(key) {\n const me = this;\n\n me._unlock(key);\n }", "function SecretKey(date = new Date()) {\n _public_key2.default.call(this, date);\n /**\n * Packet type\n * @type {module:enums.packet}\n */\n this.tag = _enums2.default.packet.secretKey;\n /**\n * Encrypted secret-key data\n */\n this.encrypted = null;\n /**\n * Indicator if secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.\n */\n this.isEncrypted = null;\n}", "lock() { this.private_key = null }", "function SecretKey(date=new Date()) {\n publicKey.call(this, date);\n /**\n * Packet type\n * @type {module:enums.packet}\n */\n this.tag = enums.packet.secretKey;\n /**\n * Encrypted secret-key data\n */\n this.encrypted = null;\n /**\n * Indicator if secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.\n */\n this.isEncrypted = null;\n}", "justProtect() {\n return this.keyCloak.protect();\n }", "constructor() { \n \n SecretInfo.initialize(this);\n }", "function Door() {\n this.locked = false;\n this.lock = function (l) {\n if (l) {\n this.locked = true;\n } else {\n this.locked = false;\n }\n }\n //list of key indexs that will lock/unlock this door\n this.keys = [];\n}", "accessSecret(){\n this.#secret(); // method in class be a property\n }", "function privateFunction() {\r\n let secret = \"This is a secret.\";// Changes the scope of that variable to be within the constructor function versus available globally, private property\r\n this.revealSecret = function () {\r\n console.log(secret);\r\n };\r\n}", "function Protect() {\r\n}", "function secretPassword() {\n var password = 'xh38sk';\n return {\n \t//Code here\n }\n }", "function setSecret() {\n var newSecret = {secret: uuid.v4(),\n date: null};\n return createSecret(newSecret).then(function(){return findSecrets()})\n .then(function(secrets){\n if (secrets.length > 12){\n for (var i=0;i<secrets.length-12;i++){\n secrets[i].remove();\n }\n secrets = secrets.slice(secrets.length-13);\n }\n return secrets;\n })\n .fail(function(err) {\n });\n}", "function secret() {\n\t\tvar unused1;\n\t}", "getSecret () {\n const secret = crypto.randomBytes(32);\n const hash = crypto.createHash('sha256').update(secret).digest('hex');\n\n return {\n secret: secret,\n hash: hash\n };\n }", "function SecretSubkey() {\n var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date();\n\n _secret_key2.default.call(this, date);\n this.tag = _enums2.default.packet.secretSubkey;\n}", "function generateRandomSecret() {\n\t\tvar ss = Math.floor(Math.random() * (secretSizeMax + 1 - secretSizeMin) + secretSizeMin);\n\t\t\n\t\tvar sec = new Array(); //secret\n\t\tfor (let i = 0; i < ss; i++)\n\t\t\tsec.push(Math.floor(Math.random()*keySize*valSize));\n\t\treturn sec;\n\t}", "async sharedSecret(epub) {\n // todo [REFACTOR]: the keypair from the user will not be accessible in future; must be moved to a secure section, better to a SE (secure element)\n return everblack().secret(epub, this.root._.sea);\n }", "function secretVariable() {\n var private = \"super secret code\";\n return function() {\n return private\n }\n}", "cleanSecrets () {\n this.shared = {}\n\n this.ephemeralKey = { local: null, remote: null }\n this.proposal = { in: null, out: null }\n this.proposalEncoded = { in: null, out: null }\n this.protocols = { local: null, remote: null }\n this.exchange = { in: null, out: null }\n }", "cleanSecrets () {\n this.shared = {}\n\n this.ephemeralKey = { local: null, remote: null }\n this.proposal = { in: null, out: null }\n this.proposalEncoded = { in: null, out: null }\n this.protocols = { local: null, remote: null }\n this.exchange = { in: null, out: null }\n }", "function seal(state) {\n return unseal;\n\n function unseal(key) {\n if (key === KEY) {\n return state;\n }\n throw new Error(\"Wrong key\");\n }\n}", "function secretValidator(control) {\n var secret = \"turtleneck\";\n var typedSecret = control.value;\n if (secret == typedSecret) {\n return null;\n }\n else {\n return control.value;\n }\n}", "function SecretSubkey(date = new Date()) {\n _secret_key2.default.call(this, date);\n this.tag = _enums2.default.packet.secretSubkey;\n}", "unlock() {\n const that = this;\n\n that.locked = false;\n }", "_unlock(key) {\n const me = this;\n\n debug(`${me._unlock.name}: ${key}`);\n\n if (me.keyLockCounterMap.has(key)) {\n let counter = me.keyLockCounterMap.get(key);\n\n if (counter !== 0) {\n me.keyLockCounterMap.set(key, --counter);\n\n if (counter === 0) {\n me.emit(`_unlock_${key}`);\n }\n }\n }\n }", "function PrivateKey() {\r\n this.conn = null;\r\n this.createPrivateKeyBox();\r\n}", "cleanSecrets() {\n this.shared = {};\n this.ephemeralKey = {\n local: null,\n remote: null\n };\n this.proposal = {\n in: null,\n out: null\n };\n this.proposalEncoded = {\n in: null,\n out: null\n };\n this.protocols = {\n local: null,\n remote: null\n };\n this.exchange = {\n in: null,\n out: null\n };\n }", "static fromSecretName(scope, id, secretName) {\n return new class extends SecretBase {\n constructor() {\n super(...arguments);\n this.encryptionKey = undefined;\n this.secretArn = secretName;\n this.secretName = secretName;\n this.autoCreatePolicy = false;\n }\n get secretFullArn() { return undefined; }\n // Overrides the secretArn for grant* methods, where the secretArn must be in ARN format.\n // Also adds a wildcard to the resource name to support the SecretsManager-provided suffix.\n get arnForPolicies() {\n return core_1.Stack.of(this).formatArn({\n service: 'secretsmanager',\n resource: 'secret',\n resourceName: this.secretName + '*',\n arnFormat: core_1.ArnFormat.COLON_RESOURCE_NAME,\n });\n }\n }(scope, id);\n }", "function decryptFromPassword(something){\n return sjcl.decrypt(userPassword, something);\n}", "computeSharedSecret(other) {\n const pubKey = SigningKey.computePublicKey(other);\n return hexlify(secp256k1.getSharedSecret(getBytesCopy(this.#privateKey), getBytes(pubKey)));\n }", "unlocked(){return true}", "function getSecret(lines) {\n\t return lines[secretKey];\n\t}", "function getSecret(lines) {\n\t return lines[secretKey];\n\t}", "constructor(k,p){\n this.privatekey = k;\n this.publickey = p;\n}", "aes_private(password, key_checksum){\n\t var [iterations, salt, checksum] = key_checksum.split(',');\n\t var secret = salt + password;\n\t for (var i = 0; 0 < iterations ? i < iterations : i > iterations; 0 < iterations ? i++ : i++) {\n\t secret = Object(__WEBPACK_IMPORTED_MODULE_4__hash__[\"sha256\"])(secret);\n\t }\n\t var new_checksum = Object(__WEBPACK_IMPORTED_MODULE_4__hash__[\"sha256\"])(secret);\n\t if (!(new_checksum.slice(0, 4).toString('hex') === checksum)) {\n\t throw new Error(\"wrong password\");\n\t }\n\t return __WEBPACK_IMPORTED_MODULE_3__aes__[\"a\" /* default */].fromSeed(secret);\n\t }", "function sharedKey(nSecret, publicKey, p) {\n p = p || P_NIST;\n\n var rawS = bignum(publicKey.powm(nSecret, p));\n\n return createKey(rawS.toBuffer({ endian: 'big' }), 'sha1');\n}", "function setSecretVariable() {\n var private = 'super secret code';\n return function() {\n return private\n }\n}", "constructor(keyData) {\n if (!isInitialized) {\n initialize();\n }\n // Only AES-128 and AES-256 supported. AES-192 is not.\n if (keyData.length !== 16 && keyData.length !== 32) {\n throw new Error(`Miscreant: invalid key length: ${keyData.length} (expected 16 or 32 bytes)`);\n }\n this._encKey = expandKey(keyData);\n this._emptyPromise = Promise.resolve(this);\n }", "validateSecret() {\n if (typeof this.options.secret !== 'string') {\n throw AppKeyException_1.AppKeyException.missingAppKey();\n }\n if (this.options.secret.length < 16) {\n throw AppKeyException_1.AppKeyException.insecureAppKey();\n }\n }", "constructor(cryptor, db, checkRand = false, verifyRandDB = undefined) {\n if (!(cryptor instanceof Cryptor)) {\n throw new TypeError(\n \"'cryptor' argument must be an instance of class extending class Cryptor\"\n );\n }\n if (!(db instanceof DB)) {\n throw new TypeError(\n \"'cryptor' argument must be an instance of class extending class Cryptor\"\n );\n }\n if (checkRand) {\n if (!verifyRandDB) {\n verifyRandDB = new MemoryDB();\n }\n if (!(verifyRandDB instanceof DB)) {\n throw new TypeError(\n \"'verifyRandDB' argument must be instance of class extending DB class\"\n );\n }\n this.verifyRandDB = verifyRandDB;\n }\n this.checkRand = checkRand;\n this.cryptor = cryptor;\n this.db = db;\n try {\n const server = db.get('TGS_SERVER');\n this.key = server.key;\n } catch (e) {\n this.key = this.cryptor.getRandomKey();\n //! CHANGE THIS, maybe add IP address as uid2\n const name = 'TGS_SERVER';\n let server = {};\n server.uid1 = 'TGS';\n server.uid2 = 'SERVER';\n server.key = this.key;\n this.db.save(name, server);\n }\n }", "constructor(publickey,privatekey){\n this.publickey = p\n this.privatekey = k\n\n}", "_clearCachedSecret(secret) {\n if (!!secret && secret === this._cachedSecret) return;\n\n this._cachedSecret = null;\n clearTimeout(this._clearCachedSecretRef);\n this._clearCachedSecretRef = null;\n }", "function getSecret(callback){\n var data = fs.readFileSync('../sensitive_data/secret.txt');\n console.log(\"The secret is: \" + data);\n return data;\n}", "unlock() {\n this.locked = 0\n }", "function SecretGenerator(manifest, secrets) {\n ApiModule.call(this);\n\n var self = this;\n\n self._manifest = manifest;\n self._secrets = secrets;\n}", "function privateFunction() {\n\n}", "constructor(key, publicKey) {\n this._key = ensureKey(key, crypto.privateKeyLength);\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength);\n }", "static fromSecretNameV2(scope, id, secretName) {\n return new class extends SecretBase {\n constructor() {\n super(...arguments);\n this.encryptionKey = undefined;\n this.secretName = secretName;\n this.secretArn = this.partialArn;\n this.autoCreatePolicy = false;\n }\n get secretFullArn() { return undefined; }\n // Creates a \"partial\" ARN from the secret name. The \"full\" ARN would include the SecretsManager-provided suffix.\n get partialArn() {\n return core_1.Stack.of(this).formatArn({\n service: 'secretsmanager',\n resource: 'secret',\n resourceName: secretName,\n arnFormat: core_1.ArnFormat.COLON_RESOURCE_NAME,\n });\n }\n }(scope, id);\n }", "createSecret() {\n if (!this.secretForm.$valid) return;\n\n /** @type {!backendApi.SecretSpec} */\n let secretSpec = {\n name: this.secretName,\n namespace: this.namespace,\n data: this.data,\n };\n this.tokenPromise.then(\n (token) => {\n /** @type {!angular.Resource} */\n let resource = this.resource_(\n `api/v1/secret/`, {},\n {save: {method: 'POST', headers: {[this.csrfHeaderName_]: token}}});\n\n resource.save(\n secretSpec,\n (savedConfig) => {\n this.log_.info('Successfully created secret:', savedConfig);\n this.mdDialog_.hide(this.secretName);\n },\n (err) => {\n this.mdDialog_.hide();\n this.errorDialog_.open('Error creating secret', err.data);\n this.log_.info('Error creating secret:', err);\n });\n },\n (err) => {\n this.mdDialog_.hide();\n this.errorDialog_.open('Error creating secret', err.data);\n this.log_.info('Error creating secret:', err);\n });\n }", "function secretkey(password,secret) {\n\n const hash = crypto.createHmac('sha256', secret)\n .update(password)\n .digest('hex');\n return hash;\n}", "get key()\n\t{\n\t\tvar priv = PRIVATE.get(this);\n\t\treturn priv.key;\n\t}", "async function createAndAccessSecret() {\n // Create the secret with automation replication.\n const [secret] = await client.createSecret({\n parent: parent,\n secret: {\n name: secretId,\n replication: {\n automatic: {},\n },\n },\n secretId,\n });\n\n console.info(`Created secret ${secret.name}`);\n\n // Add a version with a payload onto the secret.\n const [version] = await client.addSecretVersion({\n parent: secret.name,\n payload: {\n data: Buffer.from(payload, 'utf8'),\n },\n });\n\n console.info(`Added secret version ${version.name}`);\n\n // Access the secret.\n const [accessResponse] = await client.accessSecretVersion({\n name: version.name,\n });\n\n const responsePayload = accessResponse.payload.data.toString('utf8');\n console.info(`Payload: ${responsePayload}`);\n }", "constructor (key, publicKey) {\n this._key = ensureKey(key, crypto.privateKeyLength)\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength)\n }", "constructor (key, publicKey) {\n this._key = ensureKey(key, crypto.privateKeyLength)\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength)\n }", "constructor (key, publicKey) {\n this._key = ensureKey(key, crypto.privateKeyLength)\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength)\n }", "constructor (key, publicKey) {\n this._key = ensureKey(key, crypto.privateKeyLength)\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength)\n }", "constructor (key, publicKey) {\n this._key = ensureKey(key, crypto.privateKeyLength)\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength)\n }", "function genSecret(nModulus) {\n return bignum(Math.floor(Math.random() * nModulus)).mod(nModulus);\n}", "async function getRoomKey (roomId, secret)\n\t{\n\t\tconst enc = new TextEncoder ();\n\t\tconst keyMaterial = await window.crypto.subtle.importKey (\n\t\t\t\"raw\",\n\t\t\tenc.encode (secret),\n\t\t\t{name: \"PBKDF2\"},\n\t\t\tfalse,\n\t\t\t[\"deriveBits\", \"deriveKey\"]\n\t\t\t);\n\t\treturn window.crypto.subtle.deriveKey (\n\t\t\t{\n\t\t\t\tname: \"PBKDF2\",\n\t\t\t\tsalt: enc.encode (roomId),\n\t\t\t\titerations: 100000,\n\t\t\t\thash: \"SHA-256\"\n\t\t\t},\n\t\t\tkeyMaterial,\n\t\t\t{\"name\": \"AES-CTR\", \"length\": 256},\n\t\t\ttrue,\n\t\t\t[\"encrypt\", \"decrypt\"]\n\t\t\t);\n\t}", "static importKey(provider, keyData) {\n return __awaiter(this, void 0, void 0, function* () {\n const cipher = yield provider.importBlockCipherKey(keyData);\n // Generate subkeys.\n const subkey1 = new block_1.default();\n yield cipher.encryptBlock(subkey1);\n subkey1.dbl();\n const subkey2 = subkey1.clone();\n subkey2.dbl();\n return new CMAC(cipher, subkey1, subkey2);\n });\n }", "validatePassword(password, unlock = false, account = null, roles = [\"active\", \"owner\", \"memo\"]) {\n if (account) {\n let id = 0;\n\n function setKey(role, priv, pub) {\n if (!_passwordKey) _passwordKey = {};\n _passwordKey[pub] = priv;\n id++;\n stores_PrivateKeyStore__WEBPACK_IMPORTED_MODULE_4__[\"default\"].setPasswordLoginKey({\n pubkey: pub,\n import_account_names: [account],\n encrypted_key: null,\n id,\n brainkey_sequence: null\n });\n }\n /* Check if the user tried to login with a private key */\n\n\n let fromWif;\n\n try {\n fromWif = bitsharesjs__WEBPACK_IMPORTED_MODULE_11__.PrivateKey.fromWif(password);\n } catch (err) {}\n\n let acc = bitsharesjs__WEBPACK_IMPORTED_MODULE_11__.ChainStore.getAccount(account, false);\n let key;\n\n if (fromWif) {\n key = {\n privKey: fromWif,\n pubKey: fromWif.toPublicKey().toString()\n };\n }\n /* Test the pubkey for each role against either the wif key, or the password generated keys */\n\n\n roles.forEach(role => {\n if (!fromWif) {\n key = this.generateKeyFromPassword(account, role, password);\n }\n\n let foundRole = false;\n\n if (acc) {\n if (role === \"memo\") {\n if (acc.getIn([\"options\", \"memo_key\"]) === key.pubKey) {\n setKey(role, key.privKey, key.pubKey);\n foundRole = true;\n }\n } else {\n acc.getIn([role, \"key_auths\"]).forEach(auth => {\n if (auth.get(0) === key.pubKey) {\n setKey(role, key.privKey, key.pubKey);\n foundRole = true;\n return false;\n }\n });\n\n if (!foundRole) {\n let alsoCheckRole = role === \"active\" ? \"owner\" : \"active\";\n acc.getIn([alsoCheckRole, \"key_auths\"]).forEach(auth => {\n if (auth.get(0) === key.pubKey) {\n setKey(alsoCheckRole, key.privKey, key.pubKey);\n foundRole = true;\n return false;\n }\n });\n }\n }\n }\n });\n /* If the unlock fails and the user has a wallet, check the password against the wallet as well */\n\n if (!_passwordKey && !!this.state.wallet) {\n let {\n success,\n cloudMode\n } = this.validatePassword(password, true);\n\n if (success && !cloudMode) {\n bitshares_ui_style_guide__WEBPACK_IMPORTED_MODULE_15__.Notification.success({\n message: counterpart__WEBPACK_IMPORTED_MODULE_16___default().translate(\"wallet.local_switch\")\n });\n actions_SettingsActions__WEBPACK_IMPORTED_MODULE_14__[\"default\"].changeSetting({\n setting: \"passwordLogin\",\n value: false\n });\n return {\n success: true,\n cloudMode: false\n };\n }\n }\n\n return {\n success: !!_passwordKey,\n cloudMode: true\n };\n } else {\n let wallet = this.state.wallet;\n\n try {\n let password_private = bitsharesjs__WEBPACK_IMPORTED_MODULE_11__.PrivateKey.fromSeed(password);\n let password_pubkey = password_private.toPublicKey().toPublicKeyString();\n if (wallet.password_pubkey !== password_pubkey) return false;\n\n if (unlock) {\n let password_aes = bitsharesjs__WEBPACK_IMPORTED_MODULE_11__.Aes.fromSeed(password);\n let encryption_plainbuffer = password_aes.decryptHexToBuffer(wallet.encryption_key);\n aes_private = bitsharesjs__WEBPACK_IMPORTED_MODULE_11__.Aes.fromSeed(encryption_plainbuffer);\n }\n\n return {\n success: true,\n cloudMode: false\n };\n } catch (e) {\n console.error(e);\n return {\n success: false,\n cloudMode: false\n };\n }\n }\n }", "static async getSecret (secretName, region){\n const config = { region : region }\n var secret, decodedBinarySecret;\n let secretsManager = new AWS.SecretsManager(config);\n try {\n let secretValue = await secretsManager.getSecretValue({SecretId: secretName}).promise();\n if ('SecretString' in secretValue) {\n return secret = secretValue.SecretString;\n } else {\n let buff = new Buffer(secretValue.SecretBinary, 'base64');\n return decodedBinarySecret = buff.toString('ascii');\n }\n } catch (err) {\n if (err.code === 'DecryptionFailureException')\n // Secrets Manager can't decrypt the protected secret text using the provided KMS key.\n // Deal with the exception here, and/or rethrow at your discretion.\n throw err;\n else if (err.code === 'InternalServiceErrorException')\n // An error occurred on the server side.\n // Deal with the exception here, and/or rethrow at your discretion.\n throw err;\n else if (err.code === 'InvalidParameterException')\n // You provided an invalid value for a parameter.\n // Deal with the exception here, and/or rethrow at your discretion.\n throw err;\n else if (err.code === 'InvalidRequestException')\n // You provided a parameter value that is not valid for the current state of the resource.\n // Deal with the exception here, and/or rethrow at your discretion.\n throw err;\n else if (err.code === 'ResourceNotFoundException')\n // We can't find the resource that you asked for.\n // Deal with the exception here, and/or rethrow at your discretion.\n throw err;\n }\n }", "function myPowerConstructor(x) {\n var that = otherMaker(x);\n var secret = f(x);\n that.priv = function () {\n ... secret x that ...\n };\n return that;\n}", "async getPrivateState(key) {\n let makeKey = State.makeKey(key);\n let ledgerKey = this.ctx.stub.createCompositeKey(this.name, State.splitKey(key));\n let data = await this.ctx.stub.getPrivateData(this.collectionName, ledgerKey);\n if (data.length > 0) {\n let state = State.deserialize(data, this.supportedClasses);\n return state;\n } else {\n return null;\n }\n }", "function exportSecret(name, val) {\r\n exportVariable(name, val);\r\n // the runner will error with not implemented\r\n // leaving the function but raising the error earlier\r\n command_1.issueCommand('set-secret', {}, val);\r\n throw new Error('Not implemented.');\r\n}", "function exportSecret(name, val) {\r\n exportVariable(name, val);\r\n // the runner will error with not implemented\r\n // leaving the function but raising the error earlier\r\n command_1.issueCommand('set-secret', {}, val);\r\n throw new Error('Not implemented.');\r\n}", "constructor(secret, maxTokenAge) {\n\t\tif (!secret) {\n\t\t\tthrow new Error(\"You must provide a secret!\");\n\t\t}\n\n\t\tthis.secret = new Buffer(secret);\n\t\tthis.maxTokenAge = maxTokenAge || 900000; // 15 minutes\n\t\tthis.iterations = 1000;\n\n\t\t// Use a zero vector as the default IV. It isn't necessary to enforce distinct ciphertexts.\n\t\tthis.iv = new Buffer(8);\n\t\tthis.iv.fill(0);\n\t}", "constructor(pri,pub){\n this.privatekey=pri;\n this.publickey=pub;\n}", "function exportSecret(name, val) {\n exportVariable(name, val);\n // the runner will error with not implemented\n // leaving the function but raising the error earlier\n command_1.issueCommand('set-secret', {}, val);\n throw new Error('Not implemented.');\n}", "get privKey () {\n this.assert(this._privKey, 'This is a public key only wallet')\n return this._privKey\n }", "function getUserSecretKey() {\n return localStorage.getItem('userSecretKey');\n}", "function generate_proper_master_secret() {\n\n while (true) {\n var master_secret = new Uint8Array(32)\n window.crypto.getRandomValues(master_secret)\n var k = h512(master_secret)\n var kL = k.slice(0, 32)\n\n if (!(kL[31] & 0b00100000))\n break\n }\n\n return master_secret\n\n }", "function cryptedKey(){\n key = prompt(\"Please enter the secret key\");\n var bytes = CryptoJS.AES.decrypt(\"U2FsdGVkX1//PdVDNuJJOlKPaT1AKqn33MUelbyPIxNu+NdqYMV/uChgR+tdmGFy8NL0B1zbc1OMl1omq8Ljbg==\", key.toString());\n plaintext = bytes.toString(CryptoJS.enc.Utf8);\n return plaintext;\n}", "function keyExchange(oAlice, oBob, p, g) {\n var aKeys = keyPair(p, g);\n var bKeys = keyPair(p, g);\n\n oAlice.secret = sharedKey(aKeys.secretKey, bKeys.publicKey, p); \n oBob.secret = sharedKey(bKeys.secretKey, aKeys.publicKey, p);\n \n return oAlice.secret.equals(oBob.secret);\n}", "key(username, password, iterations) {\n if (iterations < 2) throw new Error('Iterations < 2 not implemented, and probably not secure anyway');\n return Sha256.pbkdf2(ByteArray.fromString(password), ByteArray.fromString(username), iterations, 32);\n }", "persistKey(successCallback) {\n let secret = this.model;\n let secretData = this.modelForData;\n let isV2 = this.isV2;\n let key = secretData.get('path') || secret.id;\n\n if (key.startsWith('/')) {\n key = key.replace(/^\\/+/g, '');\n secretData.set(secretData.pathAttr, key);\n }\n\n return secretData.save().then(() => {\n if (!secretData.isError) {\n if (isV2) {\n secret.set('id', key);\n }\n if (isV2 && Object.keys(secret.changedAttributes()).length) {\n // save secret metadata\n secret\n .save()\n .then(() => {\n this.saveComplete(successCallback, key);\n })\n .catch(e => {\n this.set(e, e.errors.join(' '));\n });\n } else {\n this.saveComplete(successCallback, key);\n }\n }\n });\n }", "function generateSecret(callback) {\n crypto.randomBytes(32, function (err, buf) {\n callback(err, buf && buf.toString('hex'))\n })\n}", "setLocked() {\n return privates.get(this).keyring.setLocked();\n }", "function keyFromPrivate(indutnyCurve, priv) {\n const keyPair = indutnyCurve.keyPair({ priv: priv });\n return keyPair;\n}", "function encryptPrivKey(privKey, encryptionKey) {\n var encoded = btoa(JSON.stringify(privKey))\n return CryptoJS.AES.encrypt(encoded, encryptionKey)\n}", "static fromUnsafePlaintext(secretValue) { try {\n jsiiDeprecationWarnings.print(\"aws-cdk-lib.aws_secretsmanager.SecretStringValueBeta1#fromUnsafePlaintext\", \"Use `cdk.SecretValue` instead.\");\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, this.fromUnsafePlaintext);\n }\n throw error;\n } return new SecretStringValueBeta1(secretValue); }", "unlock(updateData=true) {\n return new Promise((resolve, reject) => {\n this._getCreds()\n .then((creds) => {\n if (creds) {\n this.creds.deviceID = creds.deviceID;\n this.creds.password = creds.password;\n }\n return this._initSession();\n })\n .then(() => {\n return this._connect(updateData);\n })\n .then(() => {\n return resolve('Unlocked');\n })\n .catch((err) => {\n return reject(new Error(err));\n })\n })\n }", "function SafeValue() {}", "function SafeValue() {}", "function unserializePrivateKey(serPriv){\n return new sjcl.ecc.elGamal.secretKey(\n sjcl.ecc.curves.c256,\n sjcl.ecc.curves.c256.field.fromBits(sjcl.codec.base64.toBits(serPriv))\n );\n}", "constructor(notificationHandler) {\n this.notificationHandler = notificationHandler;\n var privateKey = this.getPrivateKey();\n if (privateKey) {\n //private key was found, there is already a wallet initialized\n //authentication\n var password = \"\";\n var decryptedPrivateKey = false;\n password = this.getPassword(false);\n decryptedPrivateKey = this.decryptPrivateKey(privateKey, password);\n while (!decryptedPrivateKey) {\n //repeat password prompt until the right password is given\n password = this.getPassword(true);\n decryptedPrivateKey = this.decryptPrivateKey(privateKey, password);\n }\n this.wallet = new SimpleWallet(decryptedPrivateKey); //create the simplewallet object from the decrypted private key\n return true;\n } else {\n //there is no private key initialized\n var password = this.setPassword(); //create and set password\n //generate private key and save it\n var privateKey = this.generatePrivateKey();\n this.savePrivateKey(this.encryptPrivateKey(privateKey, password));\n this.wallet = new SimpleWallet(privateKey);\n this.notificationHandler.message(\n \"Wallet created successfully. Please save your private key in a safe place: \" +\n privateKey,\n \"primary\"\n );\n return true;\n }\n }", "function unseal(sealedState) {\n return sealedState(KEY);\n}", "function SoftwareKeyProvider(utils, encryptedWallet, id) {\n this._id = id;\n this._encryptedWallet = encryptedWallet;\n this._utils = utils;\n }", "secret() {\n let self = this;\n\n // User-input.\n let client = document.createElement('textarea');\n client.setAttribute('id', 'client');\n client.setAttribute('rows', '1');\n client.setAttribute('tabindex', '1');\n\n\n let caption = document.createElement('p');\n caption.innerHTML = 'Type \"help\" for help.';\n\n self.virtualProtect.appendChild(client);\n self.virtualProtect.appendChild(caption);\n\n client.addEventListener('keypress', function(e) {\n // 'Enter' key.\n if ((e.keyCode || e.which) === 13) {\n self.handleCommand(this.value);\n e.preventDefault();\n\n this.value = \"\";\n }\n }, false);\n }", "formatSecret() {\n return \"0x\" + this.secret.toString('hex')\n }", "getPrivateKey() {\n var key = ''\n if (isNode) {\n //If the key file exist\n /*if (fs.existsSync('./data/ipfs/swarm.key')) {\n \n } else {\n //generate a random key\n key = this.generatePrivateKey()\n }*/\n key = fs.readFileSync('./data/ipfs/swarm.key', 'utf8')\n } else {\n key = localStorage.getItem('swarm.key')\n if (!key) {\n key = this.generatePrivateKey()\n }\n }\n return key\n }", "function KeyRing(extendedKey, cache) {\n this._receiveChain = null;\n this._changeChain = null;\n this.init(extendedKey, cache);\n}", "lock(key) {\n const me = this;\n\n me._lock(key);\n }" ]
[ "0.7004947", "0.6468158", "0.6461388", "0.63240784", "0.6282125", "0.6166142", "0.60906196", "0.6063269", "0.60191566", "0.59833264", "0.5963176", "0.5954877", "0.58581156", "0.5850836", "0.57865334", "0.5706168", "0.56646407", "0.56621164", "0.55816835", "0.55759335", "0.5551261", "0.5509384", "0.54887694", "0.54757077", "0.54672134", "0.543562", "0.5395046", "0.5395046", "0.539115", "0.53366196", "0.5301864", "0.5275627", "0.52426404", "0.5231624", "0.51848537", "0.5167321", "0.5142435", "0.5126595", "0.5122904", "0.5121288", "0.5121288", "0.5092315", "0.5084259", "0.5075848", "0.5055051", "0.505395", "0.50539345", "0.5046079", "0.5034884", "0.5027031", "0.50131685", "0.5005661", "0.4993135", "0.49919426", "0.49821556", "0.49805138", "0.49795973", "0.4979504", "0.49783906", "0.49759027", "0.4972691", "0.4972691", "0.4972691", "0.4972691", "0.4972691", "0.49707776", "0.49665335", "0.495457", "0.49527186", "0.4927066", "0.49215835", "0.49214295", "0.49037707", "0.49037707", "0.49020913", "0.48893023", "0.48862857", "0.48854077", "0.48815614", "0.4877264", "0.4870491", "0.4869457", "0.4868077", "0.48528492", "0.48511934", "0.4847467", "0.4845849", "0.48441312", "0.48438498", "0.48391932", "0.48391205", "0.48391205", "0.48343948", "0.48313984", "0.48290074", "0.4827664", "0.48235184", "0.48117206", "0.48094302", "0.47984537", "0.47959816" ]
0.0
-1
On Change event handler
onChange(e) { this.setState({ [e.target.name]: e.target.value }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "onchange() {}", "function onChange() {\n\t\t__debug_452( 'Received a change event.' );\n\t\tself.render();\n\t}", "function onChange() {\n\t\t__debug_330( 'Received a change event.' );\n\t\tself.render();\n\t}", "onChanged(e){}", "function onChange() {\n if (input.get.call(element, valueField) !== observer.oldValue && !element.readOnly) {\n observer.set(input.get.call(element, valueField));\n }\n }", "function onChangeHandler(e) {\n\n }", "function onChangeHandler(e) {\n\n }", "function onChange() {\n\t\t/* eslint-disable no-underscore-dangle */\n\t\t__debug_730( 'Received a change event.' );\n\t\tif ( self._autoRender ) {\n\t\t\tself.render();\n\t\t}\n\t}", "function onChange() {\n\t\t/* eslint-disable no-underscore-dangle */\n\t\t__debug_259( 'Received a change event.' );\n\t\tif ( self._autoRender ) {\n\t\t\tself.render();\n\t\t}\n\t}", "change() { }", "change(/*event*/) {\n this._super(...arguments);\n this._parse();\n }", "function onChange() {\n\t\t__debug_587( 'Received a change event.' );\n\t\tif ( self._autoRender ) { // eslint-disable-line no-underscore-dangle\n\t\t\tself.render();\n\t\t}\n\t}", "function onChange() {\n\t\t__debug_412( 'Received a change event.' );\n\t\tif ( self._autoRender ) { // eslint-disable-line no-underscore-dangle\n\t\t\tself.render();\n\t\t}\n\t}", "function onChange() {\n\t\t/* eslint-disable no-underscore-dangle */\n\t\t__debug_596( 'Received a change event.' );\n\t\tif ( self._autoRender ) {\n\t\t\tself.render();\n\t\t}\n\t}", "function onChange() {\n\t\t__debug_520( 'Received a change event.' );\n\t\tif ( self._autoRender ) { // eslint-disable-line no-underscore-dangle\n\t\t\tself.render();\n\t\t}\n\t}", "function onChange() {\n\t\t__debug_429( 'Received a change event.' );\n\t\tif ( self._autoRender ) { // eslint-disable-line no-underscore-dangle\n\t\t\tself.render();\n\t\t}\n\t}", "onChange () {}", "onChange () {}", "function onChange() {\n\t\t__debug_488( 'Received a change event.' );\n\t\tif ( self._autoRender ) { // eslint-disable-line no-underscore-dangle\n\t\t\tself.render();\n\t\t}\n\t}", "function onChange() {\n\t\t__debug_475( 'Received a change event.' );\n\t\tif ( self._autoRender ) { // eslint-disable-line no-underscore-dangle\n\t\t\tself.render();\n\t\t}\n\t}", "function onChange() {\n\t\t__debug_577( 'Received a change event.' );\n\t\tif ( self._autoRender ) { // eslint-disable-line no-underscore-dangle\n\t\t\tself.render();\n\t\t}\n\t}", "function onChange() {\n\t\t__debug_332( 'Received a change event.' );\n\t\tif ( self._autoRender ) { // eslint-disable-line no-underscore-dangle\n\t\t\tself.render();\n\t\t}\n\t}", "function onChange() {\n\t\t__debug_457( 'Received a change event.' );\n\t\tif ( self._autoRender ) { // eslint-disable-line no-underscore-dangle\n\t\t\tself.render();\n\t\t}\n\t}", "function onChange() {\n\t\t__debug_395( 'Received a change event.' );\n\t\tif ( self._autoRender ) { // eslint-disable-line no-underscore-dangle\n\t\t\tself.render();\n\t\t}\n\t}", "handleChange(event) {\n this.dispatchEvent(new CustomEvent('change', {detail: event.target.value}));\n }", "function onChange(e) {\n setValue(e.target.value);\n }", "handleEventChange() {\n }", "function changeFunction() {\n\tconsole.log(\"onchange\");\n}", "handleChange(event) {\n\n }", "function onChange(event)\n\t{\n\t\tconst val = event.target.value\n\t\tsetValue(val)\n\t}", "handleChange(e) {\n e.stopPropagation();\n const value = this.getInputEl().value;\n this.model.set({ value }, { fromInput: 1 });\n this.elementUpdated();\n }", "function changeEvent(event){\n setTipo(event.target.value);\n x = unidades.transformar_lista_longitud(x, old_unit.ds_Longitud, usr_unit.ds_Longitud);\n old_unit.ds_Longitud = usr_unit.ds_Longitud;\n usr_unit.ds_Longitud = event.target.value;\n setValor(unidades.transformar_unidad_longitud(total,old_unit.ds_Longitud, usr_unit.ds_Longitud));\n setTotal(unidades.transformar_unidad_longitud(total,old_unit.ds_Longitud, usr_unit.ds_Longitud));\n setValor4(unidades.transformar_unidad_longitud(valor4,old_unit.ds_Longitud, usr_unit.ds_Longitud));\n usr_unit.saveConfig(\"1\");\n }", "function onChange() {\n console.log(\"something changed...\");\n \n }", "function onChange() {\n\n // hide and show input elements for which this is necessary\n setVisibility();\n\n // update preview considering the changed input value\n updatePreview();\n\n // perform change actions\n self.onchange && self.onchange( self );\n\n }", "function onChange() {\n\n // hide and show input elements for which this is necessary\n setVisibility();\n\n // update preview considering the changed input value\n updatePreview();\n\n // perform change actions\n self.onchange && self.onchange( self );\n\n }", "setOnValueChangeEvent(func){\r\n this._onValueChange = func;\r\n }", "function handleChange(values) {\n // gradeShow = \"\";\n // clearSelected();\n // onFinish()\n setField(values);\n // clearSelected();\n\n }", "handleChange (event) {\n }", "function changeEvent() {\n var value_sub = properties.value;\n trigger_param_list.push(value_sub);\n // 'seek' event is like a forced-change event\n $pebble_slider_object.triggerHandler('seek', trigger_param_list);\n if (prev_change_value !== value_sub) {\n $pebble_slider_object.triggerHandler('change', trigger_param_list);\n prev_change_value = value_sub;\n }\n trigger_param_list.length = 0;\n }", "function onChange(e) {\n let val = e.target.value\n setValue(val)\n }", "reportValueChange() {\n if (this.options) {\n const value = this.getSelectedOptionValues();\n this.onChange(value);\n this._value = value;\n }\n }", "_triggerChange (e) {\n var args = [this.getValue(), this.getFormElement(), this.getUIElement()];\n if (e) {\n args.push(e);\n }\n if (this.options.onChange) {\n this.options.onChange.apply(this, args);\n }\n }", "onChange(item) {}", "function handleChange(event) {\n switch (event.target.name) {\n case \"degree\":\n setDegree(event.target.value);\n break;\n case \"major\":\n setMajor(event.target.value);\n break;\n case \"organization\":\n setOrganization(event.target.value);\n break;\n default:\n break;\n }\n }", "onChange(callback) {\n this.events.change.push({ callback });\n }", "function handleChanged(event) {\n console.log(event.target.value);\n setName(event.target.value);\n }", "onChange() {\n triggerEvent(this.input, 'input');\n triggerEvent(this.input, 'change');\n }", "handleChange(event){\n changeHandler(event,this);\n }", "function handleChange(event, value) {\n setValue(value);\n }", "function handleChange(event, newValue) {\n setValue(newValue);\n }", "onChange(callback) {\n\t\tthis.changeCallback = callback;\n\t}", "onDataChange() {}", "function v(e){return function(){var t=this.element.val();e.apply(this,arguments),this._refresh(),t!==this.element.val()&&this._trigger(\"change\")}}", "function handleChange(editor, data, value) {\n onChange(value);\n }", "function handleChange(editor, data, value) {\n onChange(value);\n }", "handleChange(event, index, value, type){\n\t\tthis.filterData(type, value)\n\t}", "_onChange() {\n let value = this.get('value');\n return this.attrs.onChange(value, this);\n }", "handleChange(event) {\n let elemName = event.target.name;\n let value = event.target.value;\n //reason picklist is selected\n if (elemName === \"reasonCombo\"){\n this.objInputFields.sReason = value;\n this.reasonSelected = true;\n }\n //comment text area is selected\n else if (elemName === \"commentField\"){\n this.objInputFields.sComment = value;\n } \n \n //this.sReason = event.target.value;\n //this.reasonSelected = true;\n this.bFormEdited = true;\n }", "changedInput() {\n\n\t\tlet {isValid, error} = this.state.wasInvalid ? this.validate() : this.state;\n\t\tlet onChange = this.props.onChange;\n\t\tif (onChange) {\n\t\t\tonChange(this.getValue(), isValid, error);\n\t\t}\n\t\tif (this.context.validationSchema) {\n\t\t\tlet value = this.getValue();\n\t\t\tif (this.state.isMultiSelect && value === '') {\n\t\t\t\tvalue = [];\n\t\t\t}\n\t\t\tif (this.shouldTypeBeNumberBySchemeDefinition(this.props.pointer)) {\n\t\t\t\tvalue = Number(value);\n\t\t\t}\n\t\t\tthis.context.validationParent.onValueChanged(this.props.pointer, value, isValid, error);\n\t\t}\n\t}", "afterValidChange() { }", "internalOnChange(event) {\n const me = this,\n value = me.value,\n oldValue = me._lastValue;\n\n // Don't trigger change if we enter invalid value or if value has not changed (for IE when pressing ENTER)\n if (me.isValid && value !== oldValue) {\n me._lastValue = value;\n\n // trigger change event, signaling that origin is from user\n me.trigger('change', { value, oldValue, event, userAction: true });\n\n // per default Field triggers action event on change, but might be reconfigured in subclasses (such as Combo)\n if (me.defaultAction === 'change') {\n me.trigger('action', { value, oldValue, event });\n }\n }\n\n // since Widget has Events mixed in configured with 'callOnFunctions' this will also call onClick and onAction\n }", "dispatchChange() {\n this.toggleAttribute(\"empty\", !this.value);\n this.dispatchEvent(new CustomEvent(\"change\", { bubbles: true }));\n }", "handleChangeInLookup(event){\n //Show spinner : wire will hide the spinner at the end\n this.isLoading = true;\n var value = event.detail.value.length>0?event.detail.value[0]:BLANK_STRING;\n //set the value based on the lookup changed\n switch (event.detail.source) {\n case MANAGER_LOOKUP:\n this.selectedManager = value;\n break;\n case USER_LOOKUP:\n this.selectedUser = value;\n break;\n case PROJECT_LOOKUP:\n this.selectedProject = value;\n break;\n default:\n console.log('Invalid Field');\n break;\n }\n }", "addChangeListener(callback) {\n this.on('change', callback);\n }", "on_change(event)\n\t{\n\t\t// Extract `value` from the argument\n\t\t// of this `onChange` listener\n\t\t// (for convenience)\n\n\t\tlet value = event\n\n\t\tif (event.target !== undefined)\n\t\t{\n\t\t\tvalue = event.target.value\n\t\t}\n\n\t\t// Call the parent `onChange` handler\n\t\t// with the `value` as an argument\n\t\t// (for convenience)\n\n\t\tconst { onChange } = this.props\n\n\t\tonChange(value)\n\t}", "_setOnChanges(){\n\t\tthis.inputs.forEach(i => i.addEventListener('change', this._onChange.bind(this)));\t\n\t}", "changeValue(event) {\n this.setValue(event.currentTarget.value);\n }", "function handleChange(e) {\n setName(e.target.value);\n }", "handleChange () {\n this.props.onStatusChange(\n this.props.item.id,\n this.refs.checkbox.checked ? 'RESERVED' : 'NEW'\n );\n }", "_onValueChanged() {\n\t\tconst { values, selectedIndex } = this.state;\n\t\tconst { onChange, name, expandSize } = this.props;\n\n\t\tconst visibleValues = getVisibleValues(values, expandSize);\n\n\t\tonChange(visibleValues[selectedIndex], name);\n\t}", "internalOnChange(event) {\n const me = this; // Don't trigger change if we enter invalid value or if value has not changed (for IE when pressing ENTER)\n\n if (me.isValid && me.hasChanged(me._lastValue, me.value)) {\n me.triggerChange(event, true);\n me._lastValue = me.value;\n }\n }", "handleChange(e) {\n const {name, value} = e.target\n this.validateData(name, value)\n }", "function handleChange(event) {\n setSelectedIndex(event.target.value);\n }", "function handleChange(e) {\n const value = e.target.value;\n const name = e.target.name;\n dispatch({ value: value, update: name });\n }", "function optionChanged(){\n init();\n}", "function onChange(value) {\n console.log(value);\n}", "_iStateOnValueChange() {\n this.dirty = true;\n }", "handleChange() {\r\n var e = document.getElementById(\"selection\")\r\n // call passed in function to spawn any necessary actions on the parent component.\r\n this.props.sendChange(e.value)\r\n }", "function g(e){return function(){var t=this.element.val();e.apply(this,arguments),this._refresh(),t!==this.element.val()&&this._trigger(\"change\")}}", "_handleChange(){\n\t\tlet text = this._text.value;\n\t\tthis.props.onChange(this.props.id, text);\n\t}", "handleTechChange(e) {\n console.log(\"tech name change:\" + e.target.value);\n }", "function changed(change) {\n if (change.changeType === \"property\" && change.property === property) {\n fn(change);\n }\n }", "function handleChange(event) {\n //event.preventDefault()\n \n if(!event.target.value){\n console.log('Input limpio');\n setValue('limpio');\n }\n setValue(event.target.value);\n \n \n\n }", "function handleChange(e, func) {\n const {value} = e.target;\n console.log(e.target.id,\":\",value);\n func(value);\n }", "function handleChange(e) {\n\t\tsetNewData({\n\t\t\t...newData,\n\t\t\t[e.target.name]: e.target.value,\n\t\t})\n\t}", "function l(e){return function(){var t=this.element.val();e.apply(this,arguments),this._refresh(),t!==this.element.val()&&this._trigger(\"change\")}}", "function l(e){return function(){var t=this.element.val();e.apply(this,arguments),this._refresh(),t!==this.element.val()&&this._trigger(\"change\")}}", "function l(e){return function(){var t=this.element.val();e.apply(this,arguments),this._refresh(),t!==this.element.val()&&this._trigger(\"change\")}}", "function l(e){return function(){var t=this.element.val();e.apply(this,arguments),this._refresh(),t!==this.element.val()&&this._trigger(\"change\")}}", "function l(e){return function(){var t=this.element.val();e.apply(this,arguments),this._refresh(),t!==this.element.val()&&this._trigger(\"change\")}}", "function l(e){return function(){var t=this.element.val();e.apply(this,arguments),this._refresh(),t!==this.element.val()&&this._trigger(\"change\")}}", "function l(e){return function(){var t=this.element.val();e.apply(this,arguments),this._refresh(),t!==this.element.val()&&this._trigger(\"change\")}}", "function l(e){return function(){var t=this.element.val();e.apply(this,arguments),this._refresh(),t!==this.element.val()&&this._trigger(\"change\")}}", "onChange() {\n this.validate();\n this.triggerContextUpdate();\n }", "handleChangeSelect(val){\n this.formatValue(val, () => {\n this.triggerDropValueChange();\n this.toggleOpen(this.props.multi);\n });\n }", "function handleChange(ev) {\n\n switch (ev.name) {\n case \"duration\":\n handleDurationChange(ev);\n break;\n case \"type\":\n handleTypeChange(ev);\n break;\n case \"unit\":\n handleUnitChange(ev);\n break;\n case \"display\":\n handleDisplayChange(ev);\n break;\n }\n}", "function handleChange(event){\r\n switch (event.target.name) {\r\n case \"userName\":\r\n setName(event.target.value)\r\n break;\r\n \r\n default:\r\n break;\r\n }\r\n }", "change(fn, options) {\n\t\treturn this.on({ change: fn }, options);\n\t}", "change(fn, options) {\n\t\treturn this.on({ change: fn }, options);\n\t}", "handleChange() {\n this.forceUpdate();\n }", "change() {\n\n const divs = this.parent.querySelectorAll('[class^=\"toggle-select-\"],[class*=\" toggle-select-\"]');\n const selectOption = this.select.options[this.select.selectedIndex];\n let value;\n\n if(this.options.field == 'group')\n {\n value = selectOption.parentNode.label ? selectOption.parentNode.label.toLowerCase() : null;\n } else {\n value = selectOption.value;\n }\n\n // Toggle each div\n divs.forEach(div => {\n const isVisible = div.classList.contains('toggle-select-'+value);\n const inputs = div.querySelectorAll('select,textarea,input:not([type=\"hidden\"],[type=\"checkbox\"],[type=\"radio\"])');\n\n // Toggle the visible div\n isVisible ? div.classList.remove('d-none') : div.classList.add('d-none');\n\n // Toggle the inputs\n if(inputs)\n {\n this.toggleForm(inputs,isVisible);\n }\n\n });\n\n // Run the custom callback\n this.options.onChanged(value);\n\n }" ]
[ "0.7940083", "0.766246", "0.76455235", "0.76388896", "0.75334346", "0.74983007", "0.74983007", "0.74853224", "0.7462203", "0.74598056", "0.74476886", "0.7440492", "0.74304813", "0.74270743", "0.74258375", "0.7424743", "0.7422155", "0.7422155", "0.7418929", "0.74176645", "0.7401884", "0.7386264", "0.73843354", "0.7382324", "0.72894126", "0.7266091", "0.7217247", "0.7215881", "0.72116756", "0.7145642", "0.711751", "0.7112472", "0.70946544", "0.7077874", "0.7077874", "0.7054155", "0.7046087", "0.7034954", "0.7010269", "0.6966104", "0.69565344", "0.6954211", "0.6938436", "0.69164187", "0.6915211", "0.69145274", "0.6904321", "0.6900082", "0.6893109", "0.687844", "0.68651885", "0.6864899", "0.6850794", "0.68458253", "0.68458253", "0.68431836", "0.6800984", "0.67996234", "0.67988396", "0.6790132", "0.67858565", "0.6766369", "0.67529655", "0.6745671", "0.67307913", "0.669767", "0.66928744", "0.66883546", "0.6683058", "0.66533136", "0.6651594", "0.66475207", "0.6638244", "0.66344833", "0.6632154", "0.66319436", "0.6630988", "0.66300756", "0.66218984", "0.6619761", "0.66172206", "0.6616473", "0.66159946", "0.6612736", "0.660068", "0.6583124", "0.6583124", "0.6583124", "0.6583124", "0.6583124", "0.6583124", "0.6583124", "0.6583124", "0.6580381", "0.65747786", "0.6567384", "0.6567339", "0.6566757", "0.6566757", "0.6563512", "0.6561836" ]
0.0
-1
Signin form submit event handler
onSubmit(e) { e.preventDefault(); const userData = { email: this.state.email, password: this.state.password, }; this.props.loginUser(userData); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function handleSubmit(event){\n setButton(false);\n console.log(\"Submitted\");\n event.preventDefault();\n console.log(email,password);\n SignIn(email,password,props,setButton);\n\n }", "async function handleSubmit(event) {\n event.preventDefault();\n \n try {\n await Auth.signIn(fields.email, fields.password);\n userHasAuthenticated(true);\n history.push(\"/\");\n } catch (e) {\n alert('usuario ou senha inválidos.');\n }\n }", "function initSignin() {\n const signinForm = document.querySelector('.signup-signin-form form');\n signinForm.addEventListener('submit', signin);\n}", "function submit() {\n\t\t\t// make sure the form is submitted,\n\t\t\t$('#signUp').on('submit', function() {\n\t\t\t\t// and head to the dashboard state\n\t\t\t\t$state.go('dashboard');\n\t\t\t});\n\t\t}", "function handleSubmit(event) {\n event.preventDefault();\n\n logInUser(formObject.email, formObject.password);\n function logInUser(email, password) {\n if (formObject.email && formObject.password) {\n API.getUser({\n email: formObject.email,\n password: formObject.password,\n })\n .then()\n .catch((err) => console.log(err));\n }\n }\n }", "function handleSignInRequest() {\n var $inputs = $('#sign-in-form :input');\n var values = captureFormData($inputs);\n var url;\n\n // submitRequest(values, url)\n}", "function handleSubmit(event){\n event.preventDefault()\n \n //this is where I am calling the function above to submit the username/password\n registration()\n //setUserName(\"\")\n //setPassword(\"\")\n }", "function handleSubmit(event) {\n\t\tevent.preventDefault()\n\t\tsignIn(formState)\n\t\t.then(({username,jwt}) => {\n\t\t\tconsole.log(username, jwt);\n\t\t\t// stores username and jwt token in session storage\n\t\t\tsessionStorage.setItem(\"token\", jwt);\n\t\t\tsessionStorage.setItem(\"user\", username);\n\t\t\tdispatch({type: 'setLoggedInUser', data: username})\n\t\t\tdispatch({type: 'setToken', data: jwt})\n\t\t\tshowUser()\n\t\t\t.then((user) => dispatch({ type: \"setProfile\", data: user }))\n \t\t.catch((error) => console.log(error));\n\t\t\thistory.push('/dashboard/flick')\n\t\t})\n\t\t// customer error message\n\t\t.catch((error) => setFormState({\n\t\t\terrorMessage: \"Login Failed, please check email and password\"}))\n\t\t}", "async function handleSubmit(e) {\n e.preventDefault()\n try {\n setError('')\n setLoading(true)\n // call signin function from firebase\n await signin(emailRef.current.value, passwordRef.current.value)\n alert('Logged in successfully')\n setError('')\n openLogin();\n history.push('/')\n } catch {\n setError('Invalid email or password')\n }\n setLoading(false)\n }", "async function onHandleSubmit(e) {\n\n e.preventDefault();\n\n try {\n await signin(formValues)\n\n } catch (error) {\n console.log(error.message);\n setError(error.message);\n }\n if (user) {\n routeOnLogin(user);\n }\n\n }", "handleSignIn(e) {\n e.preventDefault();\n //generates an auth request and redirects the user to the blockstack Browser\n //to approve the sign in request\n userSession.redirectToSignIn();\n }", "submitForm(evt) {\n\t\tevt.preventDefault()\n\t\tUserAuth.Login(this.state.inputFields)\n\t\t.then(()=> this.setState({redirect: true}))\n\t}", "async function handleSubmit(e) {\n // stop default refreshing\n e.preventDefault();\n // login\n try {\n await auth.login(email, password);\n } catch (error) {\n alert(\"Houston - we have an error logging in\");\n console.error(error);\n return;\n }\n // if no error redirect back - or \"./\"?\n history.push(\"/\");\n }", "function handleSubmit(event) {\n event.preventDefault();\n\n firebaseInstance.auth().signInWithEmailAndPassword(email, password)\n .then(() => {\n router.push(\"/\");})\n .catch((error) => { \n setError(error.message);\n });\n }", "function handleSignIn(event) {\n GoogleAuth.signIn();\n loginHandler();\n }", "function handleSubmit(event) {\n event.preventDefault();\n\n if (!checkForm()) {\n return false;\n }\n\n AuthService.register({\n lastName: lastnameInput.current.value,\n firstName: firstnameInput.current.value,\n email: emailInput.current.value,\n password: passwordInput.current.value,\n birthDate: birthdateInput.current.value,\n username: usernameInput.current.value,\n description: descInput.current.value,\n country: countryInput.current.value,\n }).then(response => {\n if (response.ok) {\n UIkit.modal(\"#signup\").hide();\n }\n return response.json().then(data => {\n UIkit.notification({\n message: data.message,\n status: (response.ok) ? 'success' : 'danger',\n pos: 'top-right',\n timeout: 5000\n });\n return true;\n });\n });\n }", "function submitHandler(e) {\n e.preventDefault();\n \n const validation = new Validation(form);\n validation.init();\n if (!validation.check()) return message.show({text: \"Fill in all marked fields correctly\", error: true});\n\n let newUser = {\n email: emailInput.value,\n password: passwordInput.value,\n nickname: nicknameInput.value,\n first_name: first_nameInput.value,\n last_name: last_nameInput.value,\n phone: phoneInput.value,\n gender_orientation: gender_orientationInput.value,\n city: cityInput.value,\n country: countryInput.value,\n date_of_birth_day: date_of_birth_dayInput.value,\n date_of_birth_month: date_of_birth_monthInput.value,\n date_of_birth_year: date_of_birth_yearInput.value\n }\n\n signUp.register(newUser)\n .then(res => {\n if(!res.error) {\n message.show({text: res.message, error: res.error});\n setTimeout(() => window.location = \"login.html\", 3000);\n } else {\n message.show({text: res.message, error: res.error});\n passwordInput.value = '';\n }\n })\n .catch((error) => {\n console.log(error);\n });\n }", "handleSignIn() {\n const loginRequest = {};\n loginRequest[USERNAME_ID] = this.state.formFields[USERNAME_ID];\n loginRequest[PASSWORD_ID] = this.state.formFields[PASSWORD_ID];\n sendLoginRequest(loginRequest, true, this.state.formFields[USERNAME_ID], null);\n }", "function handleSubmit(e) {\n e.preventDefault()\n signIn(formData)\n .then((response) => {\n console.log(response)\n const {username, jwt, isAdmin} = response\n sessionStorage.setItem('token', jwt)\n sessionStorage.setItem('user', username)\n sessionStorage.setItem('admin', isAdmin)\n dispatch({type: 'setLoggedInUser', data: username})\n dispatch({type: 'setToken', data: jwt})\n dispatch({type: 'setIsAdmin', data: isAdmin})\n })\n .catch((e)=>{console.log(e)})\n\n return history.push(\"/\") //redirects user to home page after log in submit\n }", "function handleSubmit(event) {\n event.preventDefault()\n\n if(formData.password === formData.confirm_password) {\n console.log(\"Successfuly sugned up!\")\n } else {\n console.log(\"Pasword do not match!\")\n return\n }\n /* 4. Also when submitting the form, if the person checked\n * the \"newsletter\" checkbox, log \"Thanks for signing\n * up for our newsletter!\" to the console.\n */\n if(form.joinedNewsletter) {\n console.log(\"Thanks for signing up for our newsletter!\")\n }\n\n }", "handleSubmit(event) {\n event.preventDefault();\n this.props.signInRequest(this.state.emailAddress, this.state.password, this.props.history, this.handleFailure);\n }", "function submitForm(event) {\n event.preventDefault();\n if (checkLength(fullName.value, 0) && validateEmail(email.value) && checkLength(password.value, 7)) {\n window.location.href = \"signedIn_congratulations.html\";\n }\n}", "submit() {\n this.$auth.login(this.credentials)\n .then(() => {\n this.$state.go('dashboard');\n this.$toast.show('Sign In Success!');\n })\n .catch(() => {\n this.form.$submitted = false;\n this.incorrect = true;\n });\n }", "handleSubmit(e) {\n e.preventDefault();\n let username = e.target.username.value;\n let password = e.target.password.value;\n // let remember = e.target.remember.checked;\n\n this.signin(username, password);\n }", "function formSubmitHandler(event){\r\n console.log(\"formSubmitHandler\");\r\n event.preventDefault();\r\n var form = event.target || event.srcElement;\r\n var route = getFormRoute(form);\r\n var method = form.method.toLowerCase();\r\n switch(method){\r\n case \"get\":\r\n location.hash = getHashPath(route);\r\n break;\r\n case \"post\":\r\n case \"put\":\r\n // set cancelHashChange to skip the renderView on hashChange and\r\n // then proccess it manually.\r\n cancelHashChange = true;\r\n location.hash = getHashPath(route);\r\n sessionStorage[\"currentPostParams\"] = JSON.stringify(route.postParams);\r\n setTimeout(function(){\r\n viewRender(route);\r\n cancelHashChange = false;\r\n },0);\r\n case \"path\":\r\n case \"delete\":\r\n case \"option\":\r\n default:\r\n break;\r\n }\r\n return false;\r\n }", "onFormSubmit(evt) {\n\t\tevt.preventDefault()\n\t\thttpClient.signUp(this.state.fields).then(user => {\n\t\t\tthis.setState({ fields: { name: '', email: '', password: '' } })\n\t\t\tif (user) {\n\t\t\t\tthis.props.onSignUpSuccess(user)\n\t\t\t\tthis.props.history.push('/')\n\t\t\t}\n\t\t})\n\t}", "async function handleSubmit(e) {\n e.preventDefault();\n $(formRegister.current).validate({\n rules: {\n email: { required: true },\n password: { required: true },\n },\n messages: {\n email: { required: \"Email is required\" },\n password: { required: \"Password is required\" },\n },\n submitHandler: async () => {\n const { email, password } = loginData;\n console.log(\"submit \", email);\n logIn(email, password)\n .then((response) => {\n console.log(response);\n setLoginSuccess(true);\n dispatch(setUserLogged());\n })\n .catch((error) => console.log(error));\n },\n });\n }", "function handleLoginOnsubmit(evt) {\n evt.preventDefault()\n const alluser = {...loginObject}\n\t\thttpClient.logIn(alluser).then(user => {\n console.log(\"user\", user )\n\t\t\tif(user) {\n window.location.replace(\"/home\") \n this.props.onLoginSuccess(user)\n\t\t\t\tthis.props.history.push('/')\n }\n validate(user)\n }).catch(validate);\n clearForm();\n \n }", "render() {\n super.render();\n\n this.eventBusCollector.on(SIGNIN.fail, SignInView._fail);\n\n const usernameInput = document.forms.signIn.username;\n const passwordInput = document.forms.signIn.password;\n\n const func = (e) => {\n e.preventDefault();\n this.eventBus.emit(SIGNIN.submit, {\n login: usernameInput.value,\n password: passwordInput.value,\n });\n };\n\n document.forms.SignIn.addEventListener('submit', func, false);\n this.eventCollector.addEvent(document.forms.SignIn, 'submit', func, false);\n }", "function handleSubmit(event) {\n event.preventDefault();\n\n theFrontApi.login({ email: email, password: password })\n .then((resp) => {\n if (resp.status == 201) {\n console.log('yeet')\n setUser(resp.data.user);\n history.push('/');\n }\n })\n .catch((error) => {\n console.log(error.response);\n if (error.response.status == 401) {\n setError(true);\n setEmail('');\n setPassword('');\n }\n });\n }", "function listenSigninBtn() {\n\t$('.signin-button').on('click', event => {\n\t\tlocation.reload();\n\t});\n}", "function handleSubmit(event) {\n event.preventDefault();\n dispatch(loginUser(email, password));\n }", "function submitForm() {\r\n var args = {};\r\n args.Email = session.forms.emarsyssignup.emailAddress.value;\r\n args.EmarsysSignupPage = true;\r\n args.SubscriptionType = \"footer\";\r\n args.SubscribeToEmails = true;\r\n args.Map = EmarsysNewsletter.MapFieldsSignup(); // map the form fields\r\n // send form to processing\r\n processor(args);\r\n}", "function handleSubmitForm(e) {\n e.preventDefault();\n loggingDispatch({ type: 'usernameOrEmailImmediately', value: state.usernameOrEmail.value });\n loggingDispatch({ type: 'passwordImmediately', value: state.password.value });\n\n loggingDispatch({ type: 'submitForm' });\n }", "function handleLoginFormSubmit(event){\n event.preventDefault()\n API.loginUser({\n email: loginFormObject.email,\n password: loginFormObject.password,\n })\n .then(res => {\n //if the email and password match a record in the database, send to the home page\n if(res.data){\n history.push(`/`)\n }\n //if the email and password do not match a record in the database, send an alert and keep on login page\n else{\n alert(\"login failed\")\n history.push(`/login`)\n }\n })\n .catch(err => console.log(err))\n }", "function doSubmit() {\n loggIn(email, pass);\n localStorage.clear(); \n localStorage.setItem(\"email\", email);\n}", "function main() {\n // Handle the form's submit event\n loginForm.addEventListener(\"submit\", function (event) {\n handleSubmitLogin(event);\n });\n}", "function handleSignInButtonClick() {\n if (!loggedIn) {\n setHasError(true);\n setErrorMessage('Please log in to continue');\n setShowLogin(!showLogin);\n } else {\n setLoggedIn(true);\n }\n }", "function identifiedSignIn(e) {\n e.preventDefault();\n errorReset();\n var emailInput = document.querySelector('.Modal-emailInput>input').value;\n var nameInput = document.querySelector('.Modal-fullNameInput>input').value;\n if (emailInput !== '' && nameInput !== '') {\n window.Babble.register({ name: nameInput, email: emailInput });\n } else {\n //handling errors - blank inputs\n if (emailInput === '') {\n var emailErrorMessage = document.querySelector('.Modal-errorEmail');\n emailErrorMessage.classList.remove('no-show');\n emailErrorMessage.classList.add('show');\n }\n if (nameInput === '') {\n var nameErrorMessage = document.querySelector('.Modal-errorName');\n nameErrorMessage.classList.remove('no-show');\n nameErrorMessage.classList.add('show');\n }\n }\n}", "async function handleSubmit(event) {\n event.preventDefault();\n setIsLoading(true);\n\n// Perform asynchronous call to Cognito via Amplify\n try {\n await Auth.signIn(fields.email, fields.password);\n\n// Set isAuthenticated state to true\n props.userHasAuthenticated(true);\n\n// Consequently UnauthenticatedRoute.js (as caller) re-directs to Home.js following successful login\n// props.history.push(\"/\");\n }\n catch (e) {\n alert(e.message);\n setIsLoading(false);\n }\n }", "function hook_signup_form() {\n console.log(\"hooking the signup form\")\n \n\t$(\"#signup-form\").submit(function(event) {\n\t\tevent.preventDefault();\n\t\tsignup_user();\n });\n}", "function listenLogin() {\n\t$('.login-form').submit(event => {\n\t\tevent.preventDefault();\n\t\tlet userCreds = {\n \t\tusername: $(\".username\").val().toLowerCase(),\n \t\tpassword: $(\".password\").val()\n \t};\n\n \tlogin(userCreds);\n \t});\n\n}", "function formSubmitHandler(event) {\n // alert(event);\n event.preventDefault();\n console.log(event);\n var firstName = document.querySelector(\"#f-name\").value;\n var lastName = document.querySelector(\"#l-name\").value;\n var email = document.querySelector(\"#email\").value;\n var password = document.querySelector(\"#password\").value;\n\n alert(\n \"First name: \" +\n firstName +\n \" Last name: \" +\n lastName +\n \" Email: \" +\n email +\n \" Password: \" +\n password\n );\n}", "function handleSignIn(event){\n\n event.preventDefault();\n let credentials = { email: email, password: md5(password)};\n\n axios.post(DATABASE_URL + CLIENTS+ '/signin', credentials).then( res => {\n\n //Validates the credentials\n if(res.data === 'Email wrong'){\n alert(labels.noEmailLabel)\n } else if(res.data === 'Password wrong'){\n alert(labels.wrongPasswordLabel)\n } else {\n localStorage.setItem('client', JSON.stringify(res.data));\n localStorage.setItem('isLogged', 'true');\n context.client = res.data;\n context.login();\n context.updateContext(context);\n router.push(router.locale+'/dashboard');\n }\n })\n\n }", "function signIn() {\n $('#form-signin').on('submit', function(event){\n event.preventDefault();\n $.ajax({\n url:`${url}/user/signin?loginVia=website`,\n method:'POST',\n data: {\n email: $('#inputEmail').val(),\n password: $('#inputPassword').val(),\n loginVia: 'website'\n }\n })\n .done(response => {\n notif('top-end', 'success', 'Sign in Success');\n localStorage.setItem('token', response.token);\n user._id = response.userId;\n user.name = response.userName;\n isSignIn();\n })\n .fail(response => {\n notif('top-end', 'error', response.responseJSON.err)\n }) \n })\n}", "function handleSubmit(event){\nevent.preventDefault();\n\n // logIn the user\n fire.auth()\n .signInWithEmailAndPassword(email,password)\n .then(user => {})\n .catch((error)=>{\n console.log(error);\n });\n\n\n}", "function onSubmit() {\n\n\t\tif (submitButtonProcessing) {\n\t\t\treturn;\n\t\t}\n\n\t\t// set submit button to processing (prevent multiple clicks)\n\t\tsetSubmitButtonProcessing(true);\n\n\t\tconst userData = {\n\t\t\tusername: username,\n\t\t\tpassword: password,\n\t\t\temail: email,\n\t\t\tname: name\n\t\t};\n\n\t\tcreateUser(userData).then(function (response) {\n\n\t\t\tif (response.isAuthenticated) {\n\n\t\t\t\tconst authUserData = {\n\t\t\t\t\tusername: response.username,\n\t\t\t\t\temail: response.email,\n\t\t\t\t\tname: response.name,\n\t\t\t\t\tsignupDate: response.signupDate\n\t\t\t\t};\n\n\t\t\t\t// Save user data and authentication to the store\n\t\t\t\tdispatch(SET_USERDATA(authUserData));\n\t\t\t\tdispatch(SET_ISAUTH(true));\n\n\t\t\t\tauth.signin( () => {\n\t\t\t\t\thistory.push('/post-signup/rivals');\n\t\t\t\t});\n\n\t\t\t} else {\n\n\t\t\t\t// Login failed, reset processing\n\t\t\t\tsetSubmitButtonProcessing(false);\n\n\t\t\t\t// TODO: Show some type of error\n\t\t\t}\n\t\t});\n\t}", "function form_submit_catcher(form) {\n var password_fields = form.querySelectorAll(\"input[type='password']\");\n if (password_fields.length !== 1) {\n return;\n }\n\n if (form.classList.contains(\"psono-form_submit_catcher-covered\")) {\n return;\n }\n form.classList.add(\"psono-form_submit_catcher-covered\");\n\n form.addEventListener(\"submit\", function (event) {\n var form = this;\n var form_data = get_username_and_password(form);\n if (form_data) {\n base.emit(\"login-form-submit\", get_username_and_password(form));\n }\n });\n }", "function handleUserFormSubmit(event) {\n console.log(\"Submit function called\");\n event.preventDefault();\n\n localStorage.setItem(\"loggedIn\", false);\n localStorage.removeItem(\"currentUser\");\n\n var userNameInput = $(\"#user-name\");\n var password1 = $(\"#password-1\").val().trim();\n var password2 = $(\"#password-2\").val().trim();\n\n // Don't do anything if the name fields hasn't been filled out\n if (!userNameInput.val().trim() || !password1 || !password2) {\n return;\n }\n // Calling the upsertUser function and passing in the value of the name input\n if(password1 === password2){\n $(\"#passwordMatchAlert\").empty();\n upsertUser(\n {\n name: userNameInput.val().trim(),\n login_password: password1\n }\n );\n } else{\n $(\"#passwordMatchAlert\").html(\"Passwords must match\");\n }\n \n }", "function formLoginAction(){\t\n\t\tfrmLogin.onsubmit = function(e) {\t\t\t\n\t\t\te.preventDefault();\t\t\n\t\t\tif(form.isValid()){\n\t\t\t\t Play.sendRequest(e.target,function(){\n\t\t\t\t notify.wait('Loading...');\n\t\t\t\t btnLogin.disabled = true;\n\t\t\t\t\t },function(xhr) {\t\t\t\t\t\t\n\t\t\t\t\t\t\tlocalStorage.clear();\n\t\t\t\t\t\t\tsessionStorage.clear();\n\t\t\t\t\t\t\tbtnLogin.disabled = false;\n\t\t\t\t\t\t\tif (Constants.UNSUCCESSFULLY_REQUEST === xhr.responseText) {\n\t\t\t\t\t\t\t\tnotify.danger('The name, password or user are incorrect!!!');\n\t\t\t\t\t\t\t} else {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\twindow.location = xhr.responseText;\n\t\t\t\t\t\t\t}\t\t\t\t\t \n\t\t\t\t }\n\t\t\t );\n\t\t\t}\n\t\t}\n\t}", "handleSubmit(event) {\n this.GetFromNW();\n this.GetTotalLogins();\n }", "function handleFormOnsubmit(evt) {\n evt.preventDefault()\n httpAdmin.signUp({\n name: values.name,\n phone: values.phone,\n city: values.city,\n state: values.state,\n email: values.email,\n password: values.password,\n image: values.image,\n checked: values.checked\n }).then(admin => {\n console.log(\"admin\", admin)\n if (admin) {\n window.location.replace(\"/admin-12152011\")\n this.props.onSignUpSuccess(admin)\n this.props.history.push('/')\n }\n $('#errorMsg').attr(\"style\", \"color:red\")\n $('#errorMsg').text(\"An error occured please review your entries\");\n return\n }).catch(err => console.log('err', err));\n \n }", "function handleSubmit(e) {\n // prevent default\n e.preventDefault()\n // clear errors if any\n setUsernameError({\n status: false,\n message: ''\n })\n setPasswordError({\n status: false,\n message: ''\n })\n // log in\n handleLogin({\n username: username,\n password: password\n })\n }", "handleSubmit(event){\n\t\tcogoToast.loading('Logging in...', {position: 'top-right'}).then(() => {\t\n\t\t\taxios.post(\"https://alarmbuddy-312620.uc.r.appspot.com/login\", {\n\t\t\t\tusername: this.state.username,\n\t\t\t\tpassword: this.state.password\n\t\t\t}\n\t\t\t//{ withCredentials: true }\n\t\t\t).then(response => {\n\t\t\t\tconsole.log(\"res from login: \", response);\n\t\t\t\tif(response.status === 200) {\n\t\t\t\t\t//console.log(response.data.token);\n\t\t\t\t\tcogoToast.success(\"Logged in!\", {position: 'top-right'});\n\t\t\t\t\tthis.props.handleSuccessfulAuth(response.data,\n\t\t\t\t\tthis.state.username,\n\t\t\t\t\tthis.state.password);\n\t\t\t\t}\t\n\t\t\t}).catch(error => {\n\t\t\t\tconsole.log(\"login error\", error);\n\t\t\t\tcogoToast.error(\"Error Logging in\", {position: 'top-right'});\n\t\t\t});\n\t\t});\n\t\tevent.preventDefault();\n\t\t\n\t}", "async function handleSubmit(event) {\n event.preventDefault();\n // Trigger display of the loading bar\n setLoading(true);\n\n try {\n const result = await axios.post(\"https://tweetersocial.azurewebsites.net/api/Login?code=nEMA1fDDIsxWoasb2x0qJ7jOpurajoqbCQzaIRua34YEouZo6Hw2Dw==\", {\n username: username,\n password: password\n });\n // If success, authenticate the user and redirect to their timeline\n props.userHasAuthenticated(true);\n props.setAuthenticatedUser(result.data.userid);\n props.history.push(\"/timeline\");\n } catch (e) {\n // If it failed display the alert, remove the loading bar and trigger the error highlight on the form inputs\n alert(\"Login failed, please check your credentials and retry\");\n setError(true);\n setLoading(false);\n }\n }", "async function handleSubmit(e) {\n\t\te.preventDefault();\n\t\t// Clear any past errors\n\t\tsetErrors(null);\n\t\tsetIsLoading(true);\n\t\t/** Format data based on if user is signing up or logging in\n\t\t * and store response\n\t\t */\n\t\tlet data;\n\t\tlet resp;\n\n\t\tif (activeView === 'signup') {\n\t\t\tdata = {\n\t\t\t\tusername: formData.username,\n\t\t\t\tpassword: formData.password,\n\t\t\t\tfirst_name: formData.first_name || undefined,\n\t\t\t\tlast_name: formData.last_name || undefined,\n\t\t\t\temail: formData.email || undefined,\n\t\t\t};\n\n\t\t\tresp = await signup(data);\n\t\t} else {\n\t\t\tdata = {\n\t\t\t\tusername: formData.username,\n\t\t\t\tpassword: formData.password,\n\t\t\t};\n\n\t\t\tresp = await login(data);\n\t\t}\n\t\tsetIsLoading(false);\n\t\tconsole.log(resp);\n\t\t/** Direct user to '/companies' after successful sign in */\n\t\tif (resp.success) {\n\t\t\thistory.push('/companies');\n\t\t} else {\n\t\t\t/** if registering new user returns errors,\n\t\t\t * append to 'errors' state */\n\t\t\tsetErrors(resp.errors);\n\t\t}\n\t}", "async function handleSubmit(event){\n event.preventDefault()\n await api.post('/signup', userData)\n .then(response =>{\n alert(\"Conta criada com sucesso!\")\n window.location.href = '/signin'\n })\n .catch(error =>{\n alert(\"Problema ao criar conta, tente novamente!\")\n }\n )\n\n }", "function onLoginSubmit(event) {\n event.preventDefault();\n loginForm.classList.add(HIDDEN_CLASSNAME);\n const username = loginInput.value;\n localStorage.setItem(USERNAME_KEY, username);\n paintGreetings(username);\n}", "submit() {\n\t\tif (!this.state.submitButtonEnabled) {\n\t\t\treturn;\n\t\t}\n\t\tthis.state.executing = true;\n\t\tthis.opts.callback && this.opts.callback(this.login);\n\t\tetch.update(this);\n\t}", "function watchSubmit() {\n $(\"form[name='js-login-submit-form']\").submit(function(event) {\n event.preventDefault();\n let username = $(this).find('.js-username').val();\n let password = $(this).find('.js-password').val();\n console.log(\"submitLogin firing with username/password: \" + username + \"/\" + password);\n submitLogin(username, password);\n });\n}", "function in_login() {\n\t$('#login-submit').on(\"click\", function () {\n\t\t// console.log(\"entra LOGIN\");\n\t\tlogin();\n\n\t})\n\n\n\t$('#form_login').on(\"keydown\", function (e) {\n\t\t// console.log(\"clickpass\")\n\t\tif (e.which == 13) {\n\t\t\t// console.log(\"entra LOGIN\");\n\n\t\t\tlogin();\n\t\t}\n\t});\n}", "function onMessageFormSubmit(e) {\n e.preventDefault();\n // Check that the user entered a message and is signed in.\n if (messageInputElement.value && checkSignedInWithMessage()) {\n saveMessage(messageInputElement.value).then(function () {\n // Clear message text field and re-enable the SEND button.\n resetMaterialTextfield(messageInputElement);\n toggleButton();\n });\n }\n }", "onSubmit() {\n console.warn(\"onSubmit() should be implemented in subclasses\");\n // this.attemptLogin();\n }", "function interactiveSignIn() {\r\n }", "function loginSubmitButtonEvent(e) {\n if (e.keyCode == 13) {\n checkLoginCredentials();\n }\n}", "handleKeyPress(e) {\n if (e.key === \"Enter\") {\n this.handleSignIn()\n }\n }", "function fireUserLoginEvent(form){\n $('#deals-review-form .success_msg').focus();\n $.post($(form).attr('action'),$(form).serialize(),function(data){\n if(data == 'Success'){\n if(form.isReviewForm){\n $('#deals-review-form').submit();\n $.fancybox.close();\n }else{\n window.location = SITE_ROOT_URL+'/customer/dashboard'\n }\n }else{\n $(form).find('.validation_errors').html(data);\n }\n })\n}", "function submit(form) {\n\n loginService.login($scope.user).then(function (response) {\n toastr.success('SUCCESS!', response.message);\n $state.go(\"snapshot\");\n }, function (error) {\n toastr.error('ERROR!', error.message);\n });\n\n }", "function signInSetup() {\n\n // Set the sign in button on-click function\n $('#login').submit(function(event) {\n\n event.preventDefault();\n\n // Get the data from form\n let formData = $('#login').serialize();\n\n // Send post AJAX\n $.post('/signIn', formData, function(data) {\n window.location.replace('/dashboard');\n })\n\n .fail(function(response) {\n alert(response.responseText);\n });\n\n return false;\n })\n}", "handleSignIn() {\n // Sign in the user -- this will trigger the onAuthStateChanged() method\n\n }", "function handleSubmit() {\r\n setLoading(true)\r\n const body = {\r\n email,\r\n password\r\n }\r\n axios.post('https://reqres.in/api/login', body).then((res) => {\r\n if (res.data && res.data.token) {\r\n setEmail(\"\")\r\n setPassword(\"\")\r\n // alert(\"Logged In Successfully!\")\r\n history.push('/dashboard')\r\n }\r\n }).catch((err) => {\r\n setLoading(false)\r\n if (err.response.data) {\r\n alert(err.response.data.error)\r\n }\r\n })\r\n }", "function onSignIn(e) {\n\te.preventDefault();\n\tuserName = inputField.value;\n\tif (userName === '' || userName.length < 3 || userName[0] != userName[0].toUpperCase() || !userName.match(/^[a-zA-Z\\s]+$/)) {\n\t\tsmall.style.display = 'block';\n\t} else {\n\t\tsmall.style.display = 'none';\n\t\tlocalStorage.setItem('userName', userName);\n\t\tlocation.hash = '#cardslist';\n\t};\n\tinputField.value = '';\n}", "function submit() {\r\n click(getSubmit());\r\n // Submitting still keeps the modal open until we verify that the username is unique,\r\n // and if it's not (and we have an e2e test for it), then it shows an error and keeps myInfoModal open.\r\n // So we can't do this: waitForElementToDisappear(getSubmit());\r\n }", "function handleSubmit(e) {\n\te.preventDefault();\n\tsetUpUser(apiKey.value, region.value);\n}", "async function formSubmit(event) {\n event.preventDefault();\n const res = await fetch(API_Route + `/user/login?user=${username}&pw=${password}`,\n {\n method: \"POST\", headers: {\"Content-type\": \"application/json; charset=UTF-8\"}\n });\n const content = await res.json();\n const status = JSON.parse(content);\n if (status === 200) {\n props.userHasAuthenticated(true);\n setStoredState(\"authState\", true);\n setStoredState(\"username\", username);\n // Update App authState\n props.userHasAuthenticated(true);\n props.setUsername(username);\n props.history.push(\"/trip\"); // redirect\n }\n else {\n const element = (\n <div className=\"centered\">\n <p>Incorrect username or password</p>\n </div>\n );\n ReactDOM.render(element, document.getElementById(\"error_div\"));\n }\n }", "function submitForm(e) {\n e.preventDefault();\n\n var pass = true;\n\n $usernameField.removeClass(\"error\");\n $passwordField.removeClass(\"error\");\n\n if($passwordField.val() === \"\" || $passwordField.val() === $passwordField.attr('placeholder')) {\n $passwordField.addClass(\"error\");\n pass = false;\n }\n\n if($usernameField.val() === \"\" || $usernameField.val() === $usernameField.attr('placeholder')) {\n $usernameField.addClass(\"error\");\n pass = false;\n }\n\n if(!pass) return false;\n\n // remove handlers that bind this event, so we don't go\n // into an infinite loop\n $.merge($usernameField, $passwordField).off(\"keyup\");\n\n // get those credentials\n var credentials = {\n password: $passwordField.val(),\n username: $usernameField.val()\n };\n\n // store the credentials in the DB\n _this.encryptCredentials(credentials, function() {\n // BOOM!\n _this.analytics.trackEvent('Save credentials');\n _this.submitLoginForm(credentials);\n });\n }", "function submitForm() {\n const loader = document.querySelector('.lds-ring');\n const submitBtn = document.querySelector('#submitForm');\n submitBtn.addEventListener('click', (e) => {\n\n e.preventDefault();\n\n loader.style.display = 'inline-block';\n\n const email = document.querySelector('#email').value;\n const password = document.querySelector('#password').value;\n const formData = { email, password };\n\n if (!email || !password) {\n setModalData({ display: true, head: \"Error!\", desc: \"Email or Password cannot be empty!\", color: \"danger\" });\n loader.style.display = 'none';\n return;\n }\n\n axios.post('https://my-color-palette.herokuapp.com/auth/login', formData)\n .then(res => {\n dispatch(loginUser(res.status, res.data.user, res.data.token));\n localStorage.setItem('token', res.data.token);\n localStorage.setItem('user', JSON.stringify(res.data.user));\n loader.style.display = 'none';\n })\n .catch(err => {\n console.log(err);\n loader.style.display = 'none';\n })\n\n\n });\n }", "function onVerifyCodeSubmit(e) {\n e.preventDefault();\n if (!!getCodeFromUserInput()) {\n window.verifyingCode = true;\n updateVerifyCodeButtonUI();\n // [START verifyCode]\n var code = getCodeFromUserInput();\n confirmationResult.confirm(code).then(function (result) {\n // User signed in successfully.\n var user = result.user;\n // [START_EXCLUDE]\n window.verifyingCode = false;\n window.confirmationResult = null;\n updateVerificationCodeFormUI();\n // [END_EXCLUDE]\n }).catch(function (error) {\n // User couldn't sign in (bad verification code?)\n // [START_EXCLUDE]\n console.error('Error while checking the verification code', error);\n window.alert('Error while checking the verification code:\\n\\n'\n + error.code + '\\n\\n' + error.message);\n window.verifyingCode = false;\n updateSignInButtonUI();\n updateVerifyCodeButtonUI();\n // [END_EXCLUDE]\n });\n // [END verifyCode]\n }\n }", "onSubmit() {\n console.log(\"submit form\");\n }", "function initSignup() {\n const signupForm = document.querySelector('.signup-signin-form form');\n signupForm.addEventListener('submit', signup);\n}", "function hook_login_form() {\n console.log(\"hooking the login form\")\n \n\t$(\"#login-form\").submit(function(event) {\n\t\tevent.preventDefault();\n\t\tlogin_user();\n });\n}", "submit() {\r\n\r\n this.inputsCheck();\r\n this.submitBtn.click(() => {\r\n this.pushToLocal();\r\n this.clearForm();\r\n\r\n })\r\n }", "function formSubmit(event) {\n\t// Prevent the form from reverting back to the default setting\n\tevent.preventDefault()\n\tvar passName = addName()\n\n\t// If all fields have been filled in correctly\n\tif (addName() == true && addUsername() == true && addEmail() == true) {\n\t\t// Call the gallery.html page! Success!\n\t\twindow.location.href = \"gallery.html\" + passName;\n\t};\n\n}", "function onMessageFormSubmit(e) {\n e.preventDefault();\n // Check that the user entered a message and is signed in.\n if (messageInputElement.value && checkSignedInWithMessage()) {\n saveMessage(messageInputElement.value).then(function () {\n // Clear message text field and re-enable the SEND button.\n resetMaterialTextfield(messageInputElement);\n toggleMessageButton();\n });\n }\n}", "async function handleFormSubmit(event) {\n\tevent.preventDefault();\n\n\tconst form = event.currentTarget;\n\tconst url = window.location.href;\n\t//console.log(url)\n\n\ttry {\n\t\tconst formData = new FormData(form);\n\t\tvar x1= await getkey();\n\t\t//console.log(x1[0],x1[1]);\n\t\tconst responseData = await postFormDataAsJson({ url, formData ,x1});\n\n\t\t//console.log({responseData});\n\t\tif(responseData[\"messege\"]==\"success\")\n\t\t{\n\t\t\talert(\"user \"+responseData[\"username\"]+\" successfully registered\")\n\t\t\twindow.location.href=\"/login\";\n\t\t}else if(responseData[\"messege\"]==\"username already exists\"){\n\t\t\talert (\"Username already exists\")\n\t\t}\n\t} catch (error) {\n\t\tconsole.error(error);\n\t}\n}", "function registerSubmitButtonEvent(e) {\n if (e.keyCode == 13) {\n registerNewUser();\n }\n}", "handleSignIn(e) {\n e.preventDefault()\n let username = this.refs.username.value\n let password = this.refs.password.value\n this.props.onSignIn(username, password)\n }", "function submitForm()\n\t {\n\t\t\tvar data = $(\"#login-form\").serialize();\n\n\t\t\t$.ajax({\n\n\t\t\ttype : 'POST',\n\t\t\turl : 'login_process.php',\n\t\t\tdata : data,\n\t\t\tbeforeSend: function()\n\t\t\t{\n\t\t\t\t$(\"#error\").fadeOut();\n\t\t\t\t$(\"#btn-login\").html('<span class=\"glyphicon glyphicon-transfer\"></span> &nbsp; Sending ...');\n\t\t\t},\n\t\t\tsuccess : function(response)\n\t\t\t {\n\t\t\t\t\tif(response==\"ok\"){\n\n\t\t\t\t\t\t$(\"#btn-login\").html('<img src=\"btn-ajax-loader.gif\" /> &nbsp; Signing In ...');\n\t\t\t\t\t\tsetTimeout(' window.location.href = \"index\"; ',4000);\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\n\t\t\t\t\t\t$(\"#error\").fadeIn(1000, function(){\n\t\t\t\t$(\"#error\").html('<div class=\"alert alert-danger\"> <span class=\"glyphicon glyphicon-info-sign\"></span> &nbsp; '+response+' !</div>');\n\t\t\t\t\t\t\t\t\t\t\t$(\"#btn-login\").html('<span class=\"glyphicon glyphicon-log-in\"></span> &nbsp; Sign In');\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t }\n\t\t\t});\n\t\t\t\treturn false;\n\t\t}", "function onSubmitLogin(event){\n event.preventDefault();\n const username = loginInput.value;\n\n loginForm.classList.add(HIDDEN_CLASSNAME);\n localStorage.setItem(\"username\", username);\n sayHello(username);\n}", "function pressEnterLogin(e) {\n if (e.keyCode == 13) {\n signIn();;\n }\n}", "async function handleSubmit(event) {\n\t\tevent.preventDefault();\n\t\t// this could retrieve a user object from the login, and send that to your backend. Have redux status of \"isLoggedIn = true\" -> then save the user info to redux store.\n\t\t// Need to have passport session...\n\t\taxios\n\t\t\t.post(\"/login\", {\n\t\t\t\temail: email,\n\t\t\t\tpassword: password,\n\t\t\t})\n\t\t\t.then((res) => {\n\t\t\t\t// set the JWT token to local storage (might not need this step)\n\t\t\t\tlocalStorage.setItem(\"token\", res.data.token);\n\t\t\t\t// Set the JWT token to a variable\n\t\t\t\tlet authToken = localStorage.token;\n\t\t\t\t// Send the auth token to redux function, setting auth status to true. This isn't working.\n\t\t\t\tuserAuth(authToken);\n\t\t\t\t// console.log(localStorage.token) // using local instead of Redux for now\n\t\t\t\t// Close modal\n\t\t\t\thistory.push(\"/SearchForm\");\n\t\t\t})\n\t\t\t.catch(function (error) {\n\t\t\t\tif (error.response) {\n\t\t\t\t\talert(\"Email or doesn't exist.\");\n\t\t\t\t\t// Request made and server responded\n\t\t\t\t\tconsole.log(error.response.data);\n\t\t\t\t\tconsole.log(error.response.status);\n\t\t\t\t\tconsole.log(error.response.headers);\n\t\t\t\t} else if (error.request) {\n\t\t\t\t\t// The request was made but no response was received\n\t\t\t\t\tconsole.log(error.request);\n\t\t\t\t} else {\n\t\t\t\t\t// Something happened in setting up the request that triggered an Error\n\t\t\t\t\tconsole.log(\"Error\", error.message);\n\t\t\t\t}\n\t\t\t});\n\t}", "function test_login() {\n $(\"#login_form\").submit((event) => {\n // alert($(this)[0]); // window\n // console.log($(\"input\")[0].value);\n event.preventDefault();\n if ($(\"input[name=username]\").val() === \"iamusername\" && $(\"input[name=password]\").val() === \"iampassword\") {\n window.location.replace(\"main.html\");\n } else {\n $(\"#login_span\").text(\"You enter wrong account info!\").show().fadeOut(3000);\n return false; // don't submit\n }\n });\n}", "function logInUserController() {\n attachEventListener([DOMelements.loginForm], 'submit', [loginSubmitEvent]);\n}", "submit() {\n this.$auth.login(this.credentials)\n .then(res => {\n // this.AuthService.role = res.data.role;\n this.$cookies.put('role', res.data.role);\n this.$translate('TOAST.SIGN_IN_SUCCESS')\n .then(signInSuccess => {\n this.$state.go('bucket');\n this.$toast.show(signInSuccess);\n })\n })\n .catch((res) => {\n this.form.$submitted = false;\n if (res.status != -1) {\n if (res.data.message == 'Connection to Ceph failed') {\n this.$translate('TOAST.CONNECT_CEPH_ERROR')\n .then(message => {\n this.$toast.show(message);\n })\n } else {\n this.incorrect = true;\n }\n } else {\n this.incorrect = false;\n this.$translate('TOAST.CONNECT_ERROR')\n .then(message => {\n this.$toast.show(message);\n })\n }\n });\n }", "function onMessageFormSubmit(e) {\n e.preventDefault();\n // Check that the user entered a message and is signed in.\n if (messageInputElement.value && checkSignedInWithMessage()) {\n saveMessage(messageInputElement.value).then(function() {\n // Clear message text field and re-enable the SEND button.\n resetMaterialTextfield(messageInputElement);\n toggleButton();\n });\n }\n}", "function signIn(event) {\n event.preventDefault();\n // Load local Storage data\n const dbEmail = window.localStorage.getItem('email');\n const dbPassword = window.localStorage.getItem('password');\n\n if (!dbEmail || !dbPassword) {\n alert('No email or password found!');\n return false;\n }\n\n // Form data\n const email = document.querySelector('#userEmail').value;\n const password = document.querySelector('#userPassword').value;\n\n if (email !== dbEmail && password !== dbPassword) {\n alert('Email or password not match');\n return false;\n }\n\n // Otherwise\n window.localStorage.setItem('loggedIn', true);\n window.location.replace('home.html');\n\n}", "function signIn() {\n\tconsole.log(\"Sign In Button Pressed.\");\n\tvar name = $(\"input:text[name=signInName]\").val().trim();\n\tvar pass = $(\"input:password[name=signInPassword]\").val().trim();\n\n\tvar userInfo = {\n\t\tsignInName: name,\n\t\tsignInPassword: pass\n\t}\n\n\t//=-=-=-=-=-=-=-=\n\t$.post(\"/api/user/login\", userInfo)\n .then(function(data){\n \tconsole.log(\"Sent user info: \" + userInfo);\n \tif (data.error)\n \t\t$(\"input:text[name=signInName]\").val(data.error);\n\n \tif (data.success)\n \t\twindow.location = data.redirectTo;\n });\n\t//=-=-=-=-=-=-=-=\n}", "_requestSignIn() {\n const event = new CustomEvent('sign-in', {\n detail: {\n 'sign-in': true,\n },\n });\n this.dispatchEvent(event);\n }", "function addSubmitEventListener(handler) {\n $(\"#welcome-modal-form\").submit(handler);\n }", "function handleLogin(event){\n event.preventDefault();\n loginLoader.style.display = \"block\";\n\n const email = loginForm['username'].value;\n const password = loginForm['password'].value;\n\n auth.signInWithEmailAndPassword(email,password).then( cred =>{\n console.log(cred.user);\n errorLoader.style.display = \"none\";\n loginForm.reset();\n window.location.href = \"/pages/adminDashboard.html\";\n })\n .catch(function( error ){\n loginLoader.style.display = \"none\";\n errorLoader.style.display = \"block\";\n });\n\n\n}", "function formSubmitHandler(event) {\n event.preventDefault();\n buttonSubmitHandler(deck);\n }" ]
[ "0.7436543", "0.7362524", "0.7323471", "0.7234756", "0.7013094", "0.69072306", "0.6892302", "0.6876701", "0.68308496", "0.6826685", "0.6781521", "0.67598933", "0.6754125", "0.67462677", "0.6744551", "0.6705269", "0.66970354", "0.6656132", "0.66442454", "0.66210264", "0.6617763", "0.6612644", "0.6591461", "0.6568601", "0.6555895", "0.65491587", "0.6536594", "0.6526976", "0.6522925", "0.65107197", "0.6506773", "0.65051705", "0.64970106", "0.64925885", "0.64900124", "0.64870197", "0.6485357", "0.6483992", "0.6483943", "0.6479425", "0.646863", "0.64638555", "0.6459049", "0.6457255", "0.6445473", "0.644501", "0.64425904", "0.6442072", "0.6439437", "0.64343315", "0.64242256", "0.6415764", "0.64108247", "0.64094454", "0.6408999", "0.64011097", "0.6392321", "0.6388191", "0.6374484", "0.63582927", "0.6355539", "0.6350153", "0.6345316", "0.63407165", "0.63294375", "0.63220704", "0.63168687", "0.6316053", "0.63142645", "0.6311293", "0.62917805", "0.62870514", "0.62863016", "0.62700534", "0.6263028", "0.62609786", "0.6257258", "0.6254112", "0.62530607", "0.62358844", "0.62208444", "0.6212838", "0.6211441", "0.62062246", "0.6205239", "0.6203351", "0.6203018", "0.62000096", "0.61977434", "0.6190171", "0.61892533", "0.61777556", "0.61739147", "0.6171957", "0.6171121", "0.6170664", "0.6165571", "0.61635554", "0.6157835", "0.61559737", "0.61517847" ]
0.0
-1
threeline2d normalizes the dashposition along lines based on point index, not geometric distance. this overwrites that behavior.
function _fixLine2DDistances (lineGeom) { const distAttr = lineGeom.getAttribute("lineDistance"); if (distAttr) { const posArr = lineGeom.getAttribute("position").array; const distArr = distAttr.array; let totalDist = 0; const tmpA = new Vector3(); const tmpB = new Vector3(); for (let ai=1; ai<distArr.length; ai++) { tmpA.fromArray(posArr, ai * 3 - 3); tmpB.fromArray(posArr, ai * 3); tmpB.sub(tmpA); totalDist += tmpB.length(); distArr[ai] = totalDist; } } return lineGeom; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function normalToLine(line){\r\n var vec = sub(line.p2, line.p1);\r\n var newVec = normalTo(vec);\r\n return normalize(newVec);\r\n}", "function makeNormalizedLine(p0, p1) {\n var a, b, c, toString;\n a = p1.y - p0.y;\n b = p0.x - p1.x;\n c = a*p1.x + b*p1.y;\n \n toString = function() {\n return \"[\" + this.a + \"x + \" + this.b + \"y = \" + c + \"]\";\n };\n return {a:a,b:b,c:c,p0:p0,p1:p1,toString:toString};\n }", "function lineToNormal(a, b) {\n return new V2(b.y - a.y, a.x - b.x).normalize();\n}", "function nonlinearTransform(timeline) {\n var events = timeline.events;\n\n var spacing = timeline.absLen / events.length;\n timeline.sd = spacing;\n\n for (var i = 0; i < events.length; i++) {\n var offsetFromStart = spacing * i;\n var properties = {\n y: (timeline.yOffset + offsetFromStart)\n };\n if (events[i].time.length > 1) {\n properties.path = \"M\" + timeline.xOffset + \" \" + (timeline.yOffset + offsetFromStart)+ \"V\" + (timeline.yOffset + offsetFromStart + spacing);\n }\n events[i].marker.data(\"y\", properties.y);\n events[i].marker.attr(properties);\n }\n\n }", "normalize() {\r\n let length = this.length();\r\n return new Vector2D(this.x / length, this.y / length);\r\n }", "render2d(){\n const ctx = this.canvas2dctx;\n\n ctx.clearRect(0,0,this.state.width,this.state.height);\n\n ctx.strokeStyle = \"white\";\n ctx.lineWidth = 2.0;\n ctx.font = \"16px sans-serif\";\n ctx.fillStyle = \"white\";\n\n for (let i = 0; i < this.text2d.length; i ++){\n const {text,vec, withline } = this.text2d[i];\n let v2 = this.convertWorldToScreenXY(vec);\n if( withline){\n ctx.beginPath();\n ctx.moveTo(v2.x,v2.y); ctx.lineTo(v2.x+30, v2.y-30); ctx.lineTo(v2.x+30+ctx.measureText(text).width, v2.y-30);\n ctx.stroke();\n ctx.fillText(text, v2.x+30, v2.y-30-3);\n }else{\n ctx.fillText(text, v2.x-ctx.measureText(text).width/2, v2.y-3);\n }\n }\n }", "function dashedLine(x, y, x2, y2, start, graphics) {\n var dashArray = [10, 5];\n var dashCount = dashArray.length;\n var dashSize = 0;\n for (i = 0; i < dashCount; i++) dashSize += parseInt(dashArray[i]);\n var dx = (x2 - x),\n dy = (y2 - y);\n var slopex = (dy < dx);\n var slope = (slopex) ? dy / dx : dx / dy;\n var dashOffSet = dashSize * (1 - (start / 100))\n if (slopex) {\n if (dx < 0) {\n var xOffsetStep = -Math.sqrt(dashOffSet * dashOffSet / (1 + slope * slope));\n } else {\n var xOffsetStep = Math.sqrt(dashOffSet * dashOffSet / (1 + slope * slope));\n }\n x -= xOffsetStep;\n dx += xOffsetStep;\n y -= slope * xOffsetStep;\n dy += slope * xOffsetStep;\n } else {\n if (dy < 0) {\n var yOffsetStep = -Math.sqrt(dashOffSet * dashOffSet / (1 + slope * slope));\n } else {\n var yOffsetStep = Math.sqrt(dashOffSet * dashOffSet / (1 + slope * slope));\n }\n y -= yOffsetStep;\n dy += yOffsetStep;\n x -= slope * yOffsetStep;\n dx += slope * yOffsetStep;\n }\n graphics.moveTo(x, y);\n var distRemaining = Math.sqrt(dx * dx + dy * dy);\n var dashIndex = 0, draw = true;\n while (distRemaining >= 0.1 && dashIndex < 10000) {\n var dashLength = dashArray[dashIndex++ % dashCount];\n if (dashLength > distRemaining) dashLength = distRemaining;\n if (slopex) {\n if (dx <= 0) {\n var xStep = -Math.sqrt(dashLength * dashLength / (1 + slope * slope));\n } else {\n var xStep = Math.sqrt(dashLength * dashLength / (1 + slope * slope));\n }\n x += xStep\n y += slope * xStep;\n } else {\n if (dy <= 0) {\n var yStep = -Math.sqrt(dashLength * dashLength / (1 + slope * slope));\n } else {\n var yStep = Math.sqrt(dashLength * dashLength / (1 + slope * slope));\n }\n y += yStep\n x += slope * yStep;\n }\n if (dashOffSet > 0) {\n dashOffSet -= dashLength;\n graphics.moveTo(x, y);\n } else {\n graphics[draw ? 'lineTo' : 'moveTo'](x, y);\n }\n distRemaining -= dashLength;\n draw = !draw;\n }\n // Ensure that the last segment is closed for proper stroking\n graphics.moveTo(0, 0);\n }", "place_on_slope(xcord,zcord) {\n var px = xcord % this.grid_spacing;\n var pz = zcord % this.grid_spacing;\n var cell_x = Math.trunc(xcord / this.grid_spacing) % this.grid_size;\n var cell_z = Math.trunc(zcord / this.grid_spacing) % this.grid_size;\n var normal;\n if(px + pz < this.grid_spacing) { //lower triangle\n var l11_index = cell_x + (cell_z+1) * (this.grid_size+1);\n var l12_index = cell_x + cell_z*(this.grid_size+1);\n var l21_index = (cell_x + 1) + cell_z * (this.grid_size+1);\n var l22_index = l12_index;\n normal = vec3.normalize(vec3.cross([this.verts[l21_index*3] - this.verts[l22_index*3],\n this.verts[l21_index*3+1] - this.verts[l22_index*3+1],\n this.verts[l21_index*3+2] - this.verts[l22_index*3+2]],\n [this.verts[l11_index*3] - this.verts[l12_index*3],\n this.verts[l11_index*3+1] - this.verts[l12_index*3+1],\n this.verts[l11_index*3+2] - this.verts[l12_index*3+2]],\n\n new Float32Array(3)\n ), new Float32Array(3)\n )\n } else { //higher triagnle\n var l11_index = (cell_x+1) + cell_z * (this.grid_size+1);\n var l12_index = (cell_x+1) + (cell_z+1)*(this.grid_size+1);\n var l21_index = cell_x + (cell_z+1) * (this.grid_size+1);\n var l22_index = l12_index;\n normal = vec3.normalize(vec3.cross([this.verts[l21_index*3] - this.verts[l22_index*3],\n this.verts[l21_index*3+1] - this.verts[l22_index*3+1],\n this.verts[l21_index*3+2] - this.verts[l22_index*3+2]],\n [this.verts[l11_index*3] - this.verts[l12_index*3],\n this.verts[l11_index*3+1] - this.verts[l12_index*3+1],\n this.verts[l11_index*3+2] - this.verts[l12_index*3+2]],\n\n new Float32Array(3)\n ), new Float32Array(3)\n )\n }\n //don't place on walls\n if(normal[1] <= 0.5) {\n return;\n }\n //find elevation of terrain\n var index = (cell_x + 1) + cell_z * (this.grid_size + 1);\n var ycord = -(((xcord - this.verts[index*3]) * normal[0] +\n (zcord- this.verts[index*3+2]) * normal[2])\n / normal[1]) + this.verts[index*3+1];\n //do not place under water\n if(ycord < 0) {\n return;\n }\n\n //var position = new Float32Array([this.parent.position[0] + xcord,this.parent.position[1] + ycord,this.parent.position[2] + zcord,0]);\n var position = new Float32Array([xcord,ycord,zcord,0]);\n var rotation = quaternion.getRotaionBetweenVectors([0,1,0],normal,new Float32Array(4));\n var model = null;\n if(ycord < 0.5) { //TODO: move measurements to shared place\n model = this.weighted_choice(this.beach_models)\n } else if(ycord < 3.0) {\n model = this.weighted_choice(this.grass_models);\n } else {\n //place less things on hills\n if( Math.random() < 0.75 ) return;\n model = this.weighted_choice(this.hill_models);\n }\n if(model in this.bakers){\n this.bakers[model].addInstance(position, rotation);\n }else{\n var baker = new InstanceBaker(new Float32Array(this.parent.position), new Float32Array(this.parent.rotation),model);\n baker.addInstance(position, rotation);\n this.bakers[model] = baker;\n }\n }", "updateLastLine(line) { // this is used when drawing with the pen\r\n if (line.length < 2) return;\r\n var point1 = line.points[line.points.length - 1];\r\n var point2 = line.points[line.points.length - 2];\r\n point1 = this.worldPointToChunkScreenPoint(point1);\r\n point2 = this.worldPointToChunkScreenPoint(point2);\r\n this.ctx.beginPath();\r\n this.ctx.lineWidth = Main.Camera.getRelativeWidth(line.width);\r\n this.ctx.strokeStyle = line.style;\r\n this.ctx.lineTo(point1.x, point1.y);\r\n this.ctx.lineTo(point2.x, point2.y);\r\n this.ctx.stroke();\r\n }", "function renderAxisLine() {\n ctx.save();\n ctx.setLineDash(renderAttrs.lineDash || []);\n if( renderAttrs.orientation === 'horizontal') {\n drawLine( ctx, { x: renderMin, y: originCrossAxisCoord },\n { x: renderMax, y: originCrossAxisCoord });\n }\n else {\n drawLine( ctx, { x: originCrossAxisCoord, y: renderMin },\n { x: originCrossAxisCoord, y: renderMax });\n }\n ctx.restore();\n }", "normalize() {var m = this.magnitude();return new M.XY(this.x/m,this.y/m);}", "function pathTween_extline() {\n var interpolate = d3.scale.quantile()\n .domain([0,1])\n .range(d3.range(1, d2.length + 1));\n return function(t) {\n return line(d2.slice(0, interpolate(t)));\n };\n }", "static DistancePointToLine() {}", "function addTwo(dash){\n ctx.beginPath();\n if (dash){\n ctx.setLineDash([5]);\n }\n single();\n ctx.lineTo(0, height-(rows*step)-(step/2));\n ctx.stroke();\n ctx.setLineDash([]);\n }", "function getLineNormal (a, b) {\n const u = normalize(a[0] - b[0], a[1] - b[1]);\n return [-u[1], u[0]];\n}", "function getLineNormal (a, b) {\n const u = normalize(a[0] - b[0], a[1] - b[1]);\n return [-u[1], u[0]];\n}", "function breakUpLineOrth(line){\n \n var smallerLines = [];\n \n var xDiff = line.x2 - line.x1;\n var yDiff = line.y2 - line.y1;\n \n //Check to see if line is horizontal or vertical first\n //if a line is vertical, x will always be the same value\n //if the difference between y2 and y1 is greater than 1, the line is made up of many smaller lines\n if (line.x1 == line.x2){\n if ((line.y2 - line.y1) > 1) {\n for(var i = 0; i < (line.y2 - line.y1); i++){\n smallerLines[i] = new Line(line.x1, (line.y1 + i), line.x1, (line.y1 + i + 1));\n smallerLines[i].type = line.type;\n }\n }\n else {\n smallerLines[0] = line;\n smallerLines[0].type = line.type;\n }\n return smallerLines;\n }\n //if a line is horizontal, y will always be the same value\n //if the difference between x2 and x1 is greater than 1, the line is made up of many smaller lines\n if (line.y1 == line.y2){\n if ((line.x2 - line.x1) > 1) {\n for(var i = 0; i < (line.x2 - line.x1); i++){\n smallerLines[i] = new Line((line.x1 + i), line.y1, (line.x1 + i + 1), line.y1);\n smallerLines[i].type = line.type;\n }\n }\n else {\n smallerLines[0] = line;\n smallerLines[0].type = line.type;\n }\n return smallerLines;\n }\n \n //Diagonals\n \n //work out the gradient based upon whether xdiff or ydiff is higher\n //y can be negative so use the absolute value for testing\n var gradient;\n \n //Check to see whether the diagonal line doesn't need breaking up and return it if this is the case\n if(xDiff == 1 && Math.abs(yDiff) == 1){\n smallerLines[0] = line;\n smallerLines[0].type = line.type;\n }\n \n \n \n //x grows at the same rate as y\n else if (xDiff == Math.abs(yDiff)){\n //diagonal that slopes downwards\n if(yDiff > 0){\n for (var i = 0; i < xDiff; i++ ){\n smallerLines[i] = new Line((line.x1 + i), (line.y1 + i), (line.x1 + i + 1), (line.y1 + i + 1));\n smallerLines[i].type = line.type;\n }\n }\n else if(yDiff < 0){\n //diagonal that slopes upwards\n for (var i = 0; i < xDiff; i++ ){\n smallerLines[i] = new Line((line.x1 + i), (line.y1 - i), (line.x1 + i + 1), (line.y1 - i - 1));\n smallerLines[i].type = line.type;\n }\n }\n }\n //x grows faster than y\n else if (xDiff > Math.abs(yDiff)){\n gradient = ((line.x2 - line.x1)/(line.y2 - line.y1))\n //if gradient is a whole number then the line will cut across other dots and therefore need to be broken into smaller lines\n if (gradient % 1 === 0){\n \n if( gradient > 0){\n for (var i = 0; i < (xDiff / gradient); i++ ){\n smallerLines[i] = new Line((line.x1 + (i * gradient)), (line.y1 + i), (line.x1 + (i * gradient) + gradient), (line.y1 + i + 1)); \n smallerLines[i].type = line.type;\n }\n }\n //if gradient is negative then diagonal goes up to the right\n else if( gradient < 0){\n for (var i = 0; i < (xDiff / Math.abs(gradient)); i++ ){\n smallerLines[i] = new Line((line.x1 + (i * Math.abs(gradient))), (line.y1 - i), (line.x1 + (i * Math.abs(gradient)) + Math.abs(gradient)), (line.y1 - i - 1)); \n smallerLines[i].type = line.type;\n }\n }\n }\n //else if gradient is not a whole number\n else {\n smallerLines[0] = line;\n smallerLines[0].type = line.type;\n }\n \n \n }\n // y grows faster than x\n else if (xDiff < Math.abs(yDiff)){\n gradient = ((line.y2 - line.y1)/(line.x2 - line.x1))\n //if gradient is a whole number then the line will cut across other dots and therefore need to be broken into smaller lines\n if (gradient % 1 === 0){\n \n if( gradient > 0){\n for (var i = 0; i < (yDiff / gradient); i++ ){\n smallerLines[i] = new Line((line.x1 + i), (line.y1 + (i * gradient)), (line.x1 + i + 1), (line.y1 + (i * gradient) + gradient)); \n smallerLines[i].typed = line.typed;\n }\n }\n //if gradient is negative then diagonal goes up to the right\n else if( gradient < 0){\n for (var i = 0; i < (Math.abs(yDiff / gradient)); i++ ){\n smallerLines[i] = new Line((line.x1 + i), (line.y1 - (i * Math.abs(gradient))), (line.x1 + i + 1), (line.y1 - (i * Math.abs(gradient)) - Math.abs(gradient))); \n smallerLines[i].typed = line.typed;\n }\n }\n }\n //else if gradient is not a whole number\n else {\n smallerLines[0] = line;\n smallerLines[0].type = line.type;\n }\n \n }\n \n else {\n // smallerLines.add(line);\n }\n \n return smallerLines;\n}", "static _patchLineVerts(verts)\n {\n if (verts.length == 2)\n {\n let [p1,p2] = verts;\n var pt = new SATPoint(-(p2.y - p1.y), p2.x - p1.x);\n pt.magnitude = 0.000001;\n verts.push(pt);\n }\n }", "getLongerLine() {\n var x1 = this.point1.getX();\n var y1 = this.point1.getY();\n var x2 = this.point2.getX();\n var y2 = this.point2.getY();\n\n var nearestAngle = getAngleOfLineBetweenPoints(x1, y1, x2, y2);\n\n var lineLength = Math.hypot(x1 - x2, y1 - y2) / 2.0 + (GUIDE_LINE_LENGTH) / 2.0;\n\n var centerX = (x1 - x2) / 2 + x2;\n var centerY = (y1 - y2) / 2 + y2;\n\n var newX1 = centerX + lineLength * Math.cos(nearestAngle);\n var newY1 = centerY + lineLength * Math.sin(nearestAngle);\n\n var newX2 = centerX - lineLength * Math.cos(nearestAngle);\n var newY2 = centerY - lineLength * Math.sin(nearestAngle);\n\n return new Line2D({x1: newX1, y1: newY1, x2: newX2, y2: newY2});\n }", "dxdy_lines() {\r\n\t\t//Now add the lines and text underneath and on the side of the slope line so show d(x) and d(y)\r\n\t\tlet oldLines = this.dxdy.selectAll('line');\r\n\t\toldLines.remove();\r\n\t\tlet oldText = this.dxdy.selectAll('text');\r\n\t\toldText.remove();\r\n\t\t//Line for d(x)\r\n\t\tlet left = this.endPointA, right = this.endPointB;\r\n\t\tlet high = this.endPointA, low = this.endPointB;\r\n\t\tif(this.endPointB.x < this.endPointA.x) {\r\n\t\t\tleft = this.endPointB;\r\n\t\t\tright = this.endPointA;\r\n\t\t}\r\n\t\tif(this.endPointA.y > this.endPointB.y) {\r\n\t\t\tlow = this.endPointA;\r\n\t\t\thigh = this.endPointB;\r\n\t\t}\r\n\t\t//Dealing with the bottom d(x) lines and text\r\n\t\tthis.handle_distance.x = Number(Math.abs(left.x - right.x) * this.unit_per_square.x).toFixed(1);\r\n\t\tthis.dxdy.append('line') //Bottom Left x line\r\n\t\t\t.attr('x1', left.x * this.cell_size + this.offset.x)\r\n\t\t\t.attr('y1', low.y * this.cell_size + this.offset.y + this.cell_size / 3)\r\n\t\t\t.attr('x2', left.x * this.cell_size + this.offset.x)\r\n\t\t\t.attr('y2', low.y * this.cell_size + this.offset.y + this.cell_size / 3 * 2)\r\n\t\t\t.attr('stroke', '#595959');\r\n\t\tthis.dxdy.append('line') //Bottom Right x line\r\n\t\t\t.attr('x1', right.x * this.cell_size + this.offset.x)\r\n\t\t\t.attr('y1', low.y * this.cell_size + this.offset.y + this.cell_size / 3)\r\n\t\t\t.attr('x2', right.x * this.cell_size + this.offset.x)\r\n\t\t\t.attr('y2', low.y * this.cell_size + this.offset.y + this.cell_size / 3 * 2)\r\n\t\t\t.attr('stroke', '#595959');\r\n\t\tthis.dxdy.append('line') //Bottom x line\r\n\t\t\t.attr('x1', left.x * this.cell_size + this.offset.x)\r\n\t\t\t.attr('y1', low.y * this.cell_size + this.offset.y + this.cell_size / 2)\r\n\t\t\t.attr('x2', right.x * this.cell_size + this.offset.x)\r\n\t\t\t.attr('y2', low.y * this.cell_size + this.offset.y + this.cell_size / 2)\r\n\t\t\t.attr('stroke', '#595959');\r\n\t\tthis.dxdy.append('text')\r\n\t\t\t.attr('x', (left.x * this.cell_size + this.offset.x) + (right.x - left.x) * this.cell_size / 2 - 5)\r\n\t\t\t.attr('y', low.y * this.cell_size + this.offset.y + this.cell_size)\r\n\t\t\t.attr('font-family', 'sans-serif')\r\n\t\t\t.attr('font-size', this.text_sizes.normal)\r\n\t\t\t.text(this.handle_distance.x);\r\n\r\n\t\t//Dealing with the side d(y) lines and text\r\n\t\tlet side = left;\r\n\t\tlet side_multiplier = -1;\r\n\t\tif(left.y > right.y) { //Find out which side to draw this line on\r\n\t\t\tside = right;\r\n\t\t\tside_multiplier = 1;\r\n\t\t}\r\n\t\tthis.handle_distance.y = Number(Math.abs(low.y - high.y) * this.unit_per_square.y).toFixed(1);\r\n\t\tthis.dxdy.append('line') //Top Side y line\r\n\t\t\t.attr('x1', side.x * this.cell_size + this.offset.x + this.cell_size / 3 * 2 * side_multiplier)\r\n\t\t\t.attr('y1', high.y * this.cell_size + this.offset.y)\r\n\t\t\t.attr('x2', side.x * this.cell_size + this.offset.x + this.cell_size / 3 * side_multiplier)\r\n\t\t\t.attr('y2', high.y * this.cell_size + this.offset.y)\r\n\t\t\t.attr('stroke', '#595959');\r\n\t\tthis.dxdy.append('line') //Bottom Side y line\r\n\t\t\t.attr('x1', side.x * this.cell_size + this.offset.x + this.cell_size / 3 * 2 * side_multiplier)\r\n\t\t\t.attr('y1', low.y * this.cell_size + this.offset.y)\r\n\t\t\t.attr('x2', side.x * this.cell_size + this.offset.x + this.cell_size / 3 * side_multiplier)\r\n\t\t\t.attr('y2', low.y * this.cell_size + this.offset.y)\r\n\t\t\t.attr('stroke', '#595959');\r\n\t\tthis.dxdy.append('line') //Side y line\r\n\t\t\t.attr('x1', side.x * this.cell_size + this.offset.x + this.cell_size / 2 * side_multiplier)\r\n\t\t\t.attr('y1', high.y * this.cell_size + this.offset.y)\r\n\t\t\t.attr('x2', side.x * this.cell_size + this.offset.x + this.cell_size / 2 * side_multiplier)\r\n\t\t\t.attr('y2', low.y * this.cell_size + this.offset.y)\r\n\t\t\t.attr('stroke', '#595959');\r\n\t\tthis.dxdy.append('text')\r\n\t\t\t.attr('x', (side.x * this.cell_size + this.offset.x + this.cell_size * side_multiplier))\r\n\t\t\t.attr('y', (high.y * this.cell_size + this.offset.y) + (low.y - high.y) * this.cell_size / 2)\r\n\t\t\t.attr('font-family', 'sans-serif')\r\n\t\t\t.attr('font-size', this.text_sizes.normal)\r\n\t\t\t.text(this.handle_distance.y);\r\n\r\n\t\tthis.footer.change_question(this.x_units, this.y_units, this.handle_distance.x, this.handle_distance.y);\r\n\t}", "function addOneDash(){\n ctx.beginPath();\n ctx.moveTo(0, height-(rows*step));\n ctx.lineTo((width/2), height-((rows-1)*step));\n ctx.stroke();\n\n ctx.beginPath();\n ctx.setLineDash([5]);\n ctx.moveTo((width/2), height-((rows-1)*step));\n ctx.lineTo(width, height-(step*rows));\n ctx.stroke();\n ctx.setLineDash([]);\n }", "function getNormal(line) {\n\tlet [ax, ay, bx, by] = line;\n\tlet dx = bx - ax;\n\tlet dy = by - ay;\n\treturn [-dy, dx];\n}", "static DistancePointToLineSegment() {}", "static Normalized(x, y) {\n let vec = new Vec2(x, y);\n if (vec.Magnitude() === 0)\n return new Vec2(0);\n return vec.Divide(vec.Magnitude());\n }", "function generateBevelledPoint(pts, line_width) {\n if (pts === undefined || pts.length < 2) {\n return undefined;\n }\n let res = [];\n let start_vector = new THREE.Vector3();\n start_vector.subVectors(pts[1], pts[0]);\n let left_miter = new THREE.Vector3();\n left_miter.crossVectors(new THREE.Vector3(0, 0, 1), start_vector);\n left_miter.normalize();\n left_miter.multiplyScalar(line_width);\n let right_miter = left_miter.clone();\n right_miter.multiplyScalar(-1.0);\n let left_point = new THREE.Vector3();\n let right_point = new THREE.Vector3();\n left_point.addVectors(pts[0], left_miter);\n right_point.addVectors(pts[0], right_miter);\n for (let i = 1; i < pts.length - 1; i++) {\n let pre_point = pts[i - 1];\n let current_point = pts[i];\n let next_point = pts[i + 1];\n let pre_vec = new THREE.Vector3();\n let next_vec = new THREE.Vector3();\n pre_vec.subVectors(current_point, pre_point);\n next_vec.subVectors(next_point, current_point);\n let direct = new THREE.Vector3();\n direct.crossVectors(pre_vec, next_vec);\n // direct is negative stand for clock-wise\n\n\n next_vec.multiplyScalar(-1.0);\n pre_vec.normalize();\n next_vec.normalize();\n\n let semi_vec = new THREE.Vector3();\n semi_vec.addVectors(pre_vec, next_vec);\n\n semi_vec.normalize();\n let semi_width = -line_width / Math.abs(semi_vec.x * next_vec.y - semi_vec.y * next_vec.x);\n\n semi_vec.multiplyScalar(semi_width);\n\n\n let semi_point = new THREE.Vector3();\n let pre_vec_point = new THREE.Vector3();\n let next_vec_point = new THREE.Vector3();\n\n if (direct.z > 0) {\n\n next_vec.crossVectors(new THREE.Vector3(0, 0, 1), next_vec);\n pre_vec.crossVectors(new THREE.Vector3(0, 0, -1), pre_vec);\n } else if (direct.z < 0) {\n\n next_vec.crossVectors(new THREE.Vector3(0, 0, -1), next_vec);\n pre_vec.crossVectors(new THREE.Vector3(0, 0, 1), pre_vec);\n } else {\n console.log(\"Direct equals to zero\");\n return [];\n }\n\n pre_vec.multiplyScalar(line_width);\n next_vec.multiplyScalar(line_width);\n\n semi_point.addVectors(current_point, semi_vec);\n pre_vec_point.addVectors(current_point, next_vec);\n next_vec_point.addVectors(current_point, pre_vec);\n\n if (direct.z > 0) {\n\n res.push(left_point, right_point, next_vec_point);\n res.push(left_point, next_vec_point, semi_point);\n res.push(next_vec_point, semi_point, pre_vec_point);\n left_point = semi_point;\n right_point = pre_vec_point;\n\n } else if (direct.z < 0) {\n res.push(left_point, right_point, next_vec_point);\n res.push(right_point, semi_point, next_vec_point);\n res.push(next_vec_point, semi_point, pre_vec_point);\n left_point = pre_vec_point;\n right_point = semi_point;\n } else {\n console.log(\"Direct equals to zero\");\n return [];\n }\n\n }\n\n\n let end_index = pts.length - 1;\n\n let end_vector = new THREE.Vector3();\n end_vector.subVectors(pts[end_index], pts[end_index - 1]);\n let end_vector_miter = new THREE.Vector3();\n end_vector_miter.crossVectors(new THREE.Vector3(0, 0, 1), end_vector);\n end_vector_miter.normalize();\n end_vector_miter.multiplyScalar(line_width);\n\n let left_end_point = new THREE.Vector3();\n let right_end_point = new THREE.Vector3();\n\n left_end_point.addVectors(pts[end_index], end_vector_miter);\n end_vector_miter.multiplyScalar(-1.0);\n right_end_point.addVectors(pts[end_index], end_vector_miter);\n\n res.push(left_point, right_point, right_end_point);\n res.push(left_point, right_end_point, left_end_point);\n return res;\n}", "get normalized() {\n const [Q1, { x: Qx2, y: Qy2 }, { x: Qx, y: Qy }] = [\n { x: 0 + ((2 / 3) * (1 - 0)), y: 2 + ((2 / 3) * (0 - 2)) },\n { x: 2 + ((2 / 3) * (1 - 2)), y: 2 + ((2 / 3) * (0 - 2)) },\n { x: 2, y: 2 },\n ] // = commands.Q.normalized.points.slice(0, 3)\n const T1x2 = 4 > Qx ? 4 + (Qx - (4 - Qx2)) : 4 - (Qx - (4 - Qx2))\n const T1y2 = 2 > Qy ? 2 + (Qy - (4 - Qy2)) : 2 - (Qy - (4 - Qy2))\n const T2x2 = 6 + (4 - (8 - T1x2))\n const T2y2 = 2 - (2 - (4 - T1y2))\n\n return {\n points: [\n Q1, { x: Qx2, y: Qy2 }, { x: Qx, y: Qy },\n { x: 4 - Qx2, y: 4 - Qy2 }, { x: T1x2, y: T1y2 }, { x: 4, y: 2 },\n { x: 8 - T1x2, y: 4 - T1y2 }, { x: T2x2, y: T2y2 }, { x: 6, y: 2 },\n { x: 6, y: 2 }, { x: 0, y: 2 }, { x: 0, y: 2 },\n ],\n type: 'C',\n }\n }", "function addOnePerDash(){\n ctx.beginPath();\n ctx.setLineDash([5]);\n single();\n ctx.lineTo(width, height-(step*rows));\n ctx.stroke();\n ctx.setLineDash([]);\n }", "function tweenDash() {\n // get total length per line\n var length = this.getTotalLength();\n\n // get the starting and ending values within the total length\n var i = d3.interpolateString(\"0,\" + length, length + \",\" + length);\n\n // return values for Tween transition\n return function (t) {\n return i(t);\n };\n }", "static insertDashedLine(points, color) {\n if (points == null || points.length == 0)\n return null;\n\n var lineGeometry = new THREE.Geometry();\n var lineMaterial = new THREE.LineDashedMaterial({\n color: color,\n linewidth: 1\n });\n\n for (var i = 0; i < points.length; i++) {\n lineGeometry.vertices.push(points[i]);\n }\n lineGeometry.computeLineDistances();\n return new THREE.Line(lineGeometry, lineMaterial);\n }", "function draw_line(p1, p2) {\n var dist = Math.sqrt((p1.x - p2.x) * (p1.x - p2.x)\n + (p1.y - p2.y) * (p1.y - p2.y));\n var line = document.createElement(\"div\");\n line.className = \"line\";\n line.style.width = dist + \"px\";\n line.style.backgroundColor = \"#bbbbbb\";\n lines_div.appendChild(line);\n var m = (p1.y - p2.y) / (p1.x - p2.x);\n var ang = Math.atan(m);\n var ps = [p1, p2];\n var left = ps[0].x < ps[1].x ? 0 : 1;\n var top = ps[0].y < ps[1].y ? 0 : 1;\n if (left == top) {\n line.style.transformOrigin = \"top left\";\n line.style.left = ps[left].x + 2.5 + \"px\";\n line.style.top = ps[top].y + 2.5 + \"px\";\n line.style.transform = \"rotate(\" + ang + \"rad)\";\n }\n else {\n line.style.transformOrigin = \"bottom left\";\n line.style.left = ps[left].x + 2.5 + \"px\";\n line.style.top = ps[1 - top].y + 2.5 + \"px\";\n line.style.transform = \"rotate(\" + ang + \"rad)\";\n }\n}", "function FieldPath (name, yPoints, zPoints) {\n this.name = name;\n this.xPoints = []; // anterior-posterior\n this.yPoints = yPoints; // superior-inferior\n this.zPoints = zPoints; //lateral-medial\n\n this.side = \"right\";\n // Need to assert yPoints.length = zPoints.length\n this.numPoints = yPoints.length\n this.switchSide = switchSide;\n this.renderPath = renderPath;\n this.material = new THREE.LineBasicMaterial({\n linewidth: 3,\n linecap: \"round\",\n linejoin: \"round\",\n });\n this.changeToDash = changeToDash;\n\n // Initialise xPoints with integers from 0 to numLength\n for (var i=0; i<this.numPoints; i++) {\n this.xPoints.push(2*i);\n }\n\n function switchSide() {\n this.zPoints = this.zPoints.map(n => n * (-1));\n switch(this.side) {\n case \"right\":\n this.side = \"left\";\n break;\n case \"left\":\n this.side = \"right\";\n break;\n }\n }\n\n function renderPath(parent, color, zOffset) {\n // zOffset to show all lines without superimposition\n this.material.color.set(color)\n var zPointsOffset = this.zPoints.map(n => n + zOffset);\n var geometry = new THREE.Geometry();\n for (var i=0; i<this.numPoints; i++) {\n var xc = this.xPoints[i];\n var yc = this.yPoints[i];\n var zc = zPointsOffset[i];\n geometry.vertices.push(new THREE.Vector3(xc, yc, zc));\n }\n geometry.computeLineDistances();\n var line = new THREE.Line(geometry, this.material);\n parent.add(line);\n }\n\n function changeToDash() {\n this.material = new THREE.LineDashedMaterial({\n linewidth: 2,\n linecap: \"round\",\n linejoin: \"round\",\n dashSize: 0.2,\n gapSize: 0.05,\n })\n }\n\n}", "function normalizeLinear() {\n\n var normalizedPattern = new Array();\n newHeight = 256;\n newWidth = 256;\n xMin = 256;\n xMax = 0;\n yMin = 256;\n yMax = 0;\n // first determine drawn character width / length\n for(var i = 0;i<recordedPattern.length;i++) {\n var stroke_i = recordedPattern[i];\n for(var j = 0; j<stroke_i.length;j++) {\n x = stroke_i[j][0];\n y = stroke_i[j][1];\n if(x < xMin) {\n xMin = x;\n }\n if(x > xMax) {\n xMax = x;\n }\n if(y < yMin) {\n yMin = y;\n }\n if(y > yMax) {\n yMax = y;\n }\n }\n }\t\n oldHeight = Math.abs(yMax - yMin);\n oldWidth = Math.abs(xMax - xMin);\n\n for(var i = 0;i<recordedPattern.length;i++) {\n var stroke_i = recordedPattern[i];\n var normalized_stroke_i = new Array();\n for(var j = 0; j<stroke_i.length;j++) {\n x = stroke_i[j][0];\n y = stroke_i[j][1];\n xNorm = (x - xMin) * (newWidth / oldWidth) ;\n yNorm = (y - yMin) * (newHeight / oldHeight);\n normalized_stroke_i.push([xNorm, yNorm]);\n }\n normalizedPattern.push(normalized_stroke_i);\n }\n recordedPattern = normalizedPattern;\n redraw();\n }", "getLineLengthBetweenPoints (x, y, x0, y0){\n return Math.sqrt((x -= x0) * x + (y -= y0) * y);\n }", "line(...args) {\n let thickness = args[args.length-1];\n if (typeof thickness != \"number\") {\n thickness = 1;\n }\n let p1 = args[1];\n if (typeof p1 != \"object\") {\n p1 = [0, 0];\n }\n let p0 = args[0];\n if (typeof p0 != \"object\") {\n p0 = [0, 0];\n }\n ctx.lineWidth = thickness/ctxtransform[0];\n ctx.beginPath();\n ctx.moveTo(p0[0], p0[1]);\n ctx.lineTo(p1[0], p1[1]);\n ctx.stroke();\n\t}", "function linearTransform(timeline) {\n var events = timeline.events;\n\n // for each event in the timeline.events array, this block linearly interpolates \n // from the time the event occured relative to the start of the narrative to its\n // according pixel position on the timeline object and updates that objects' attributes\n for (var i = 0; i < events.length; i++) {\n var currStart = events[i].time[0];\n var offsetFromStart = lerp(timeline.range, timeline.absLen, timeline.start, currStart);\n\n var properties = {\n x: (timeline.xOffset - 30),\n y: (timeline.yOffset + offsetFromStart)\n }\n //If the event occurs over a range of time, modify the properites for that\n // representative path as well\n if (events[i].time.length > 1) {\n var currEnd = events[i].time[events[i].time.length - 1];\n var segmentLen = lerp(timeline.range, timeline.absLen, currStart, currEnd);\n properties.path = \"M\" + timeline.xOffset + \" \" + properties.y + \"V\" + (properties.y + segmentLen);\n }\n events[i].marker.data(\"y\", properties.y);\n events[i].marker.attr(properties);\n }\n }", "function norm2Dist(obj, obj2) {\n return Math.sqrt(\n Math.pow(obj.east - obj2.east, 2) +\n Math.pow(obj.north - obj2.north, 2)\n );\n}", "normalize() { \n\t\tlet m = Math.sqrt(this.x * this.x + this.y * this.y);\n\n\t\tthis.x /= m;\n\t\tthis.y /= m;\n\t\treturn this;\n\t}", "function wuLine(x1, y1, x2, y2) {\n var canvas = document.getElementById(\"canvas3\");\n var context = canvas.getContext(\"2d\");\n var steep = Math.abs(y2 - y1) > Math.abs(x2 - x1);\n if (steep) {\n x1 = [y1, y1 = x1][0];\n x2 = [y2, y2 = x2][0];\n }\n if (x1 > x2) {\n x1 = [x2, x2 = x1][0];\n y1 = [y2, y2 = y1][0];\n }\n draw(context, colorFigure, steep ? y1 : x1, steep ? x1 : y1);\n draw(context, colorFigure, steep ? y2 : x2, steep ? x2 : y2);\n var dx = x2 - x1;\n var dy = y2 - y1;\n var gradient = dy / dx;\n var y = y1 + gradient;\n for (var x = x1 + 1; x < x2 - 1; x++) {\n colorFigure.a = (1 - (y - Math.floor(y))) * 10000;\n draw(context, colorFigure, x, Math.floor(y));\n colorFigure.a = (y - Math.floor(y)) * 10000;\n draw(context, colorFigure, x, Math.floor(y));\n y += gradient;\n }\n}", "getNormalize() {\n let length = this.getLength();\n return new Vector2d(this.x/length, this.y/length);\n }", "function addZeroDash(){\n ctx.beginPath();\n ctx.setLineDash([5]);\n ctx.moveTo(0, height-(rows*step));\n ctx.lineTo((width/2), height-((rows-1)*step));\n ctx.stroke();\n ctx.setLineDash([]);\n\n ctx.beginPath();\n ctx.moveTo((width/2), height-((rows-1)*step));\n ctx.lineTo(width, height-(step*rows));\n ctx.stroke();\n }", "function normalNewell(p0, p1, p2) {\r\n\tvar verts = [p0, p1, p2, p0];\r\n\tvar normal = vec4(0, 0, 0, 0);\r\n\tfor (var i = 0; i < 3; i++) {\r\n\t\tnormal[0] += (verts[i][1] - verts[i + 1][1]) * (verts[i][2] + verts[i + 1][2]);\r\n\t\tnormal[1] += (verts[i][2] - verts[i + 1][2]) * (verts[i][0] + verts[i + 1][0]);\r\n\t\tnormal[2] += (verts[i][0] - verts[i + 1][0]) * (verts[i][1] + verts[i + 1][1]);\r\n\t}\r\n\treturn normalize(normal);\r\n}", "constructor(\n referenceLine, //** OBJECT REQUIRES ONLY A BEGIN POINT AND END POINT */\n perpendicularDistance = 0,\n linearDistance = 0\n ) {\n this.point = new PointObservable(referenceLine.beginPoint.xy)\n this.referenceLine = referenceLine\n this.referencePoint = this.referenceLine.beginPoint\n this.perpendicularDistance = perpendicularDistance\n this.linearDistance = linearDistance\n this.distancePoint = new PointObservable({\n x: 0,\n y: 0\n })\n this.colinearPoint = new PointObservable({\n x: 0,\n y: 0\n })\n\n this.coordinateDistanceValues = () => {\n const side = Public.getWhichSidePointToLine(this.point, this.referenceLine)\n this.colinearPoint.xy = Public.getPerpendicularPoint(this.referenceLine, this.point)\n const tempLineEndPoint = Public.getEndPoint(this.referencePoint, 100, this.lineAngle + 90)\n const tempLine = {\n beginPoint: tempLineEndPoint,\n endPoint: this.referencePoint,\n }\n const baseSide = Public.getWhichSidePointToLine(this.point, tempLine)\n this.distancePoint.xy = Public.getPerpendicularPoint(tempLine, this.point, true)\n this.perpendicularDistance = Public.getDistanceTwoPoints(this.point, this.colinearPoint)\n if (side === 'right') this.perpendicularDistance *= -1\n this.linearDistance = Public.getDistanceTwoPoints(this.referencePoint, this.colinearPoint)\n if (baseSide === 'right') this.linearDistance *= -1\n }\n \n const coordinateTrackPoints = () => {\n this.colinearPoint.xy = Public.getPerpendicularPoint(this.referenceLine, this.point)\n const tempLineEndPoint = Public.getEndPoint(this.referencePoint, 100, this.lineAngle + 90)\n const tempLine = {\n beginPoint: tempLineEndPoint,\n endPoint: this.referencePoint,\n }\n this.distancePoint.xy = Public.getPerpendicularPoint(tempLine, this.point, true)\n }\n\n //** FOR PURPOSES OF MANAGING DID SET FUNCTION, A UNIQUE INSTANCE OF SET-POINT-FUNCTION IS GENERATED */\n const generateSetPointFunction = (referncePoint) => {\n return {\n function: () => {\n const linearAngle = (this.linearDistance < 0 ? this.lineAngle + 180 : this.lineAngle) % 360\n const linePoint = this.linearDistance === 0 ?\n referncePoint :\n Public.getEndPoint(referncePoint, Math.abs(this.linearDistance), linearAngle)\n const perpAngle = (this.perpendicularDistance < 0 ? this.lineAngle + -90 : this.lineAngle + 90) % 360\n this.point.xy = Public.getEndPoint(linePoint, Math.abs(this.perpendicularDistance), perpAngle)\n coordinateTrackPoints()\n }\n }\n }\n\n let setPointFunction = generateSetPointFunction(this.referenceLine.beginPoint).function\n setPointFunction()\n this.referenceLine.beginPoint.appendDidSet(setPointFunction)\n this.referenceLine.endPoint.appendDidSet(setPointFunction)\n\n this.disassociateWithLine = () => {\n this.referenceLine.endPoint.removeDidSetFunction(setPointFunction)\n this.referenceLine.beginPoint.removeDidSetFunction(setPointFunction)\n this.referenceLine = null\n }\n\n let _mousePressPoint = null\n this.sendMousePress = (mousePressPoint) => {\n if (Public.getUserMouseClickOnPoint(mousePressPoint, 10, [this.point])) {\n _mousePressPoint = mousePressPoint\n return true\n }\n }\n this.sendMouseDrag = (mouseDragPoint) => {\n if (!_mousePressPoint) return\n this.point.xy = Public.getMovedPoints(_mousePressPoint, mouseDragPoint, [this.point.xy])[0]\n this.coordinateDistanceValues()\n\n }\n this.sendMouseRelease = () => {\n this.coordinateDistanceValues()\n _mousePressPoint = null\n }\n }", "function updateStyles() {\n\tconsole.log('updateStyles');\n\tvar zoom = rkGlobal.leafletMap.getZoom();\n\tfor(const key of Object.keys(rkGlobal.segments)) {\n\t\tconsole.log(key);\n\t\tvar properties = JSON.parse(key);\n\t\tvar showFull = zoom >= rkGlobal.priorityFullVisibleFromZoom[properties.priority];\n\t\tvar showMinimal = zoom < rkGlobal.priorityFullVisibleFromZoom[properties.priority] && zoom >= rkGlobal.priorityReducedVisibilityFromZoom[properties.priority];\n\n\t\tvar lineStyle;\n\t\tif(showFull) {\n\t\t\tlineStyle = getLineStyle(zoom, properties);\n\t\t} else if(showMinimal) {\n\t\t\tlineStyle = getLineStyleMinimal(properties);\n\t\t}\n\n\t\tvar lines = rkGlobal.segments[key].lines;\n\t\tif(showFull || showMinimal) {\n\t\t\tlines.setStyle(lineStyle);\n\t\t\trkGlobal.leafletMap.addLayer(lines);\n\t\t} else {\n\t\t\trkGlobal.leafletMap.removeLayer(lines);\n\t\t}\n\n\t\t// steep lines are drawn twice, once regular,\n\t\t// a second time as bristles (that's what this copy is for)\n\t\tvar steepLines = rkGlobal.segments[key].steepLines;\n\t\tif(steepLines !== undefined) {\n\t\t\tif(showFull || showMinimal) {\n\t\t\t\tvar steepLineStyle;\n\t\t\t\tif(showFull) {\n\t\t\t\t\tsteepLineStyle = getSteepLineStyle(zoom, properties);\n\t\t\t\t} else {\n\t\t\t\t\tsteepLineStyle = getSteepLineStyleMinimal(properties);\n\t\t\t\t}\n\t\t\t\tsteepLines.setStyle(steepLineStyle);\n\t\t\t\trkGlobal.leafletMap.addLayer(steepLines);\n\t\t\t} else {\n\t\t\t\trkGlobal.leafletMap.removeLayer(steepLines);\n\t\t\t}\n\t\t}\n\n\t\tvar decorators = rkGlobal.segments[key].decorators;\n\t\tif((showFull || showMinimal) && zoom >= rkGlobal.onewayIconThreshold && properties.oneway === 'yes') {\n\t\t\tdecorators.setPatterns(getOnewayArrowPatterns(zoom, properties, lineStyle.weight));\n\t\t\trkGlobal.leafletMap.addLayer(decorators);\n\t\t} else {\n\t\t\trkGlobal.leafletMap.removeLayer(decorators);\n\t\t}\n\t}\n\n\tif(zoom >= rkGlobal.iconZoomThresholds[1]) {\n\t\trkGlobal.leafletMap.removeLayer(rkGlobal.markerLayerLowZoom);\n\t\trkGlobal.leafletMap.addLayer(rkGlobal.markerLayerHighZoom);\n\t} else if(zoom >= rkGlobal.iconZoomThresholds[0]) {\n\t\trkGlobal.leafletMap.removeLayer(rkGlobal.markerLayerHighZoom);\n\t\trkGlobal.leafletMap.addLayer(rkGlobal.markerLayerLowZoom);\n\t} else {\n\t\trkGlobal.leafletMap.removeLayer(rkGlobal.markerLayerHighZoom);\n\t\trkGlobal.leafletMap.removeLayer(rkGlobal.markerLayerLowZoom);\n\t}\n}", "calculateNormals() {\r\n // MP2: Implement this function!\r\n \r\n }", "function lineLength(x, y, x0, y0){\n return Math.sqrt((x -= x0) * x + (y -= y0) * y);\n}", "function distanceWithLine(p1, p2) \n{\n\tvar dist,\n\t\tdx = p1.x - p2.x;\n\t\tdy = p1.y - p2.y;\n\t\n\tdist = Math.sqrt(dx*dx + dy*dy);\n\t\t\t\n\t// Draw the line when distance is smaller\n\t// then the minimum distance\n\tif(dist <= minDist) \n\t{\n\t\t\n\t\t// Draw the line\n\t\tctx.beginPath();\n\t\tctx.strokeStyle = \"rgba(255,255,255,\"+ (1.2-dist/minDist) +\")\";\n\t\tctx.moveTo(p1.x, p1.y);\n\t\tctx.lineTo(p2.x, p2.y);\n\t\tctx.stroke();\n\t\tctx.closePath();\n\t\t\n\t\t\n\t\t\n\t\t// Some acceleration for the partcles \n\t\t// depending upon their distance\n\t\tvar ax = (document.getElementById(\"textInputPress\").value)*Math.random()/50000,\n\t\t\tay = (document.getElementById(\"textInputPress\").value)*Math.random()/50000;\n\t\t\n\t\t// Apply the acceleration on the particles\n\t\tp1.vx -= ax;\n\t\tp1.vy -= ay;\n\t\t\n\t\tp2.vx += ax;\n\t\tp2.vy += ay;\n\t}\n}", "function normalize_path(){\n\n var x_diff = mouse_path[0].x;\n var y_diff = -1 * mouse_path[0].y;\n\n for( x in mouse_path){\n\tmouse_path[x].x = (mouse_path[x].x) - x_diff;\n\tmouse_path[x].y = (-1 * mouse_path[x].y) - y_diff;\n }\n\n\n}", "function normalize2d(x) {\n\tvar y = [x[0], x[1]];\n\tvar zero = [0, 0];\n\tvar mag = euclideanDist(zero, y);\n\tif (mag !== 0) {\n\t\ty[0] /= mag;\n\t\ty[1] /= mag;\n\t}\n\treturn y;\n}", "function distLineToPoint(a, b, p) {\n var n = vectDiff(b, a)\n n = vectScale(n, 1/Math.sqrt(n[0]*n[0]+n[1]*n[1]))\n \n var amp = vectDiff(a, p)\n var d = vectDiff(amp, vectScale(n,(dot(amp, n))))\n //return { d:d, a:amp, nn:n, n:dot(amp,n)}\n return Math.sqrt(d[0]*d[0]+d[1]*d[1])\n}", "function addDashedArrowLines(){\n extralines.selectAll(\".extralines\").remove();\n extralines.selectAll(\".extralines\")\n .data(graph.links.filter(function (d) {\n return \"edgemeta\" in d && d.edgemeta.includes(\"social\")\n && d.edgemeta.includes(\"transaction\");\n }))\n .enter().append(\"line\")\n .attr(\"class\", \"extralines\")\n .style(\"stroke\", \"darkblue\")\n .attr(\"stroke-width\", 2)\n .attr(\"z-index\", -5)\n .style(\"opacity\", function (d) {\n if (d.maxweight < strengthslider ||\n (strengthslider > 0 && d.maxweight == undefined)){\n return 0;\n }\n if (filtertype == \"tag\") {\n if (tag == \"all\" ||\n (d.source.type == \"tag\" && d.source.name == tag) ||\n (d.target.type == \"tag\" && d.target.name == tag)){\n return 1;\n }\n return 0.15;\n } \n else if (filtertype == \"network\") {\n if (tag == \"all\" ||\n (d.edgemeta != null && d.edgemeta.includes(tag))){\n return 1;\n }\n return 0.15;\n }\n return 1;\n })\n .attr(\"x1\", function (d) {return d.source.x;})\n .attr(\"y1\", function (d) {return d.source.y;})\n .attr(\"x2\", function (d) {return d.target.x;})\n .attr(\"y2\", function (d) {return d.target.y;}); \n}", "function tr(xy) {\n return [(xy[0]-extent[0])/(extent[2]-extent[0]) * size[0],\n (xy[1]-extent[3])/(extent[1]-extent[3]) * size[1]];\n }", "static drawBezierTangent(point1, point2) {\n\t\tlet curve = new THREE.LineCurve3(point1, point2);\n\t\tlet points = curve.getPoints(1);\n\t\tlet geometry = new THREE.BufferGeometry().setFromPoints(points);\n\t\tlet line = new THREE.Line(\n\t\t\tgeometry,\n\t\t\tnew THREE.LineBasicMaterial({ color: 0xff0000 })\n\t\t);\n\t\treturn line;\n\t}", "normalize() {\n let scale = 1.0 / this.length();\n this.xyz = this.xyz.multiplyScalar(scale);\n this.w *= scale;\n return this;\n }", "function breakUpLine(line){\n \n var smallerLines = [];\n var xDiff = line.x2 - line.x1;\n var yDiff = line.y2 - line.y1;\n \n //Check to see if line is horizontal or vertical first\n //if a line is vertical, x will always be the same value\n //if the difference between y2 and y1 is greater than 2, the line is made up of many smaller lines\n if (line.x1 == line.x2){\n if ((line.y2 - line.y1) > 2) {\n for(var i = 0; i < ((line.y2 - line.y1) / 2); i++){\n smallerLines[i] = new Line(line.x1, (line.y1 + (2 * i)), line.x1, (line.y1 + (2 * i) + 2));\n smallerLines[i].type = line.type;\n }\n }\n else {\n smallerLines[0] = line;\n smallerLines[0].type = line.type;\n }\n return smallerLines;\n }\n //if a line is horizontal, y will always be the same value\n //if the difference between x2 and x1 is greater than 2, the line is made up of many smaller lines\n if (line.y1 == line.y2){\n if ((line.x2 - line.x1) > 2) {\n for(var i = 0; i < ((line.x2 - line.x1) / 2); i++){\n smallerLines[i] = new Line((line.x1 + (2 * i)), line.y1, (line.x1 + (2 * i) + 2), line.y1);\n smallerLines[i].type = line.type;\n }\n }\n else {\n smallerLines[0] = line;\n smallerLines[0].type = line.type;\n }\n return smallerLines;\n }\n //Diagonals\n \n //work out the gradient based upon whether xdiff or ydiff is higher\n //y can be negative so use the absolute value for testing\n var gradient;\n //Check to see whether the diagonal line doesn't need breaking up and return it if this is the case\n if(xDiff == 1 && Math.abs(yDiff) == 1){\n smallerLines[0] = line;\n smallerLines[0].type = line.type;\n }\n //x grows at the same rate as y\n else if (xDiff == Math.abs(yDiff)){\n //diagonal that slopes downwards\n if(yDiff > 0){\n for (var i = 0; i < xDiff; i++ ){\n smallerLines[i] = new Line((line.x1 + i), (line.y1 + i), (line.x1 + i + 1), (line.y1 + i + 1));\n smallerLines[i].type = line.type;\n }\n }\n //diagonal that slopes upwards\n else if(yDiff < 0){\n for (var i = 0; i < xDiff; i++ ){\n smallerLines[i] = new Line((line.x1 + i), (line.y1 - i), (line.x1 + i + 1), (line.y1 - i - 1));\n smallerLines[i].type = line.type;\n }\n }\n }\n //x grows faster than y\n else if (xDiff > Math.abs(yDiff)){\n gradient = ((line.x2 - line.x1)/(line.y2 - line.y1))\n //if gradient is a whole number then the line will cut across other dots and therefore need to be broken into smaller lines\n if (gradient % 1 === 0){\n \n if( gradient > 0){\n for (var i = 0; i < (xDiff / gradient); i++ ){\n smallerLines[i] = new Line((line.x1 + (i * gradient)), (line.y1 + i), (line.x1 + (i * gradient) + gradient), (line.y1 + i + 1)); \n smallerLines[i].type = line.type;\n }\n }\n //if gradient is negative then diagonal goes up to the right\n else if( gradient < 0){\n for (var i = 0; i < (xDiff / Math.abs(gradient)); i++ ){\n smallerLines[i] = new Line((line.x1 + (i * Math.abs(gradient))), (line.y1 - i), (line.x1 + (i * Math.abs(gradient)) + Math.abs(gradient)), (line.y1 - i - 1));\n smallerLines[i].type = line.type;\n }\n }\n }\n //else if gradient is not a whole number\n else {\n smallerLines[0] = line;\n smallerLines[0].type = line.type;\n } \n }\n // y grows faster than x\n else if (xDiff < Math.abs(yDiff)){\n gradient = ((line.y2 - line.y1)/(line.x2 - line.x1))\n //if gradient is a whole number then the line will cut across other dots and therefore need to be broken into smaller lines\n if (gradient % 1 === 0){\n \n if( gradient > 0){\n for (var i = 0; i < (yDiff / gradient); i++ ){\n smallerLines[i] = new Line((line.x1 + i), (line.y1 + (i * gradient)), (line.x1 + i + 1), (line.y1 + (i * gradient) + gradient)); \n smallerLines[i].type = line.type;\n }\n }\n //if gradient is negative then diagonal goes up to the right\n else if( gradient < 0){\n for (var i = 0; i < (Math.abs(yDiff / gradient)); i++ ){\n smallerLines[i] = new Line((line.x1 + i), (line.y1 - (i * Math.abs(gradient))), (line.x1 + i + 1), (line.y1 - (i * Math.abs(gradient)) - Math.abs(gradient)));\n smallerLines[i].type = line.type;\n }\n }\n }\n //else if gradient is not a whole number\n else {\n smallerLines[0] = line;\n smallerLines[0].type = line.type;\n } \n }\n else {\n // smallerLines.add(line);\n }\n \n return smallerLines; \n}", "function posnormtriv( pos, norm, colors, o1, o2, o3, renderCallback ) {\n\n\t\tvar c = scope.count * 3;\n\n\t\t// positions\n\n\t\tscope.positionArray[ c + 0 ] = pos[ o1 ];\n\t\tscope.positionArray[ c + 1 ] = pos[ o1 + 1 ];\n\t\tscope.positionArray[ c + 2 ] = pos[ o1 + 2 ];\n\n\t\tscope.positionArray[ c + 3 ] = pos[ o2 ];\n\t\tscope.positionArray[ c + 4 ] = pos[ o2 + 1 ];\n\t\tscope.positionArray[ c + 5 ] = pos[ o2 + 2 ];\n\n\t\tscope.positionArray[ c + 6 ] = pos[ o3 ];\n\t\tscope.positionArray[ c + 7 ] = pos[ o3 + 1 ];\n\t\tscope.positionArray[ c + 8 ] = pos[ o3 + 2 ];\n\n\t\t// normals\n\n\t\tif ( scope.material.flatShading === true ) {\n\n\t\t\tvar nx = ( norm[ o1 + 0 ] + norm[ o2 + 0 ] + norm[ o3 + 0 ] ) / 3;\n\t\t\tvar ny = ( norm[ o1 + 1 ] + norm[ o2 + 1 ] + norm[ o3 + 1 ] ) / 3;\n\t\t\tvar nz = ( norm[ o1 + 2 ] + norm[ o2 + 2 ] + norm[ o3 + 2 ] ) / 3;\n\n\t\t\tscope.normalArray[ c + 0 ] = nx;\n\t\t\tscope.normalArray[ c + 1 ] = ny;\n\t\t\tscope.normalArray[ c + 2 ] = nz;\n\n\t\t\tscope.normalArray[ c + 3 ] = nx;\n\t\t\tscope.normalArray[ c + 4 ] = ny;\n\t\t\tscope.normalArray[ c + 5 ] = nz;\n\n\t\t\tscope.normalArray[ c + 6 ] = nx;\n\t\t\tscope.normalArray[ c + 7 ] = ny;\n\t\t\tscope.normalArray[ c + 8 ] = nz;\n\n\t\t} else {\n\n\t\t\tscope.normalArray[ c + 0 ] = norm[ o1 + 0 ];\n\t\t\tscope.normalArray[ c + 1 ] = norm[ o1 + 1 ];\n\t\t\tscope.normalArray[ c + 2 ] = norm[ o1 + 2 ];\n\n\t\t\tscope.normalArray[ c + 3 ] = norm[ o2 + 0 ];\n\t\t\tscope.normalArray[ c + 4 ] = norm[ o2 + 1 ];\n\t\t\tscope.normalArray[ c + 5 ] = norm[ o2 + 2 ];\n\n\t\t\tscope.normalArray[ c + 6 ] = norm[ o3 + 0 ];\n\t\t\tscope.normalArray[ c + 7 ] = norm[ o3 + 1 ];\n\t\t\tscope.normalArray[ c + 8 ] = norm[ o3 + 2 ];\n\n\t\t}\n\n\t\t// uvs\n\n\t\tif ( scope.enableUvs ) {\n\n\t\t\tvar d = scope.count * 2;\n\n\t\t\tscope.uvArray[ d + 0 ] = pos[ o1 + 0 ];\n\t\t\tscope.uvArray[ d + 1 ] = pos[ o1 + 2 ];\n\n\t\t\tscope.uvArray[ d + 2 ] = pos[ o2 + 0 ];\n\t\t\tscope.uvArray[ d + 3 ] = pos[ o2 + 2 ];\n\n\t\t\tscope.uvArray[ d + 4 ] = pos[ o3 + 0 ];\n\t\t\tscope.uvArray[ d + 5 ] = pos[ o3 + 2 ];\n\n\t\t}\n\n\t\t// colors\n\n\t\tif ( scope.enableColors ) {\n\n\t\t\tscope.colorArray[ c + 0 ] = colors[ o1 + 0 ];\n\t\t\tscope.colorArray[ c + 1 ] = colors[ o1 + 1 ];\n\t\t\tscope.colorArray[ c + 2 ] = colors[ o1 + 2 ];\n\n\t\t\tscope.colorArray[ c + 3 ] = colors[ o2 + 0 ];\n\t\t\tscope.colorArray[ c + 4 ] = colors[ o2 + 1 ];\n\t\t\tscope.colorArray[ c + 5 ] = colors[ o2 + 2 ];\n\n\t\t\tscope.colorArray[ c + 6 ] = colors[ o3 + 0 ];\n\t\t\tscope.colorArray[ c + 7 ] = colors[ o3 + 1 ];\n\t\t\tscope.colorArray[ c + 8 ] = colors[ o3 + 2 ];\n\n\t\t}\n\n\t\tscope.count += 3;\n\n\t\tif ( scope.count >= scope.maxCount - 3 ) {\n\n\t\t\tscope.hasPositions = true;\n\t\t\tscope.hasNormals = true;\n\n\t\t\tif ( scope.enableUvs ) {\n\n\t\t\t\tscope.hasUvs = true;\n\n\t\t\t}\n\n\t\t\tif ( scope.enableColors ) {\n\n\t\t\t\tscope.hasColors = true;\n\n\t\t\t}\n\n\t\t\trenderCallback( scope );\n\n\t\t}\n\n\t}", "function PointOnLine(v1, v2, t) {\n\n\t/*\n\tFor each direction, lerp compute a new value from the t normalized factor;\n\t*/\n\n\tlet x = THREE.Math.lerp(v1[\"x\"], v2[\"x\"], t);\n\tlet y = THREE.Math.lerp(v1[\"y\"], v2[\"y\"], t);\n\tlet z = THREE.Math.lerp(v1[\"z\"], v2[\"z\"], t);\n\n\treturn new THREE.Vector3(x, y, z);\n}", "function planeNormal(cords,origo){\r\n\tvar origo = getOrigo(cords);\r\n\treturn lineNormal(uToV(origo,cords[0]),uToV(origo,cords[1]));\r\n}", "function line_positions() {\n\n line_one_x = win_width * .7;\n line_one_y = win_height * .8;\n\n line_two_x = win_width * .75;\n line_two_y = -(line_two.getBBox().height / 2);\n\n line_three_x = win_width * .65;\n line_three_y = win_height * .6;\n\n line_one.attr({\n transform: 't' + line_one_x + ' ' + line_one_y\n });\n line_two.attr({\n transform: 't' + line_two_x + ' ' + line_two_y\n });\n line_three.attr({\n transform: 't' + line_three_x + ' ' + line_three_y\n })\n }", "function normalize(point) {\n var oneOverLen = 1 / ParticleUtils.length(point);\n point.x *= oneOverLen;\n point.y *= oneOverLen;\n }", "function add_extrusion_values() {\n // if(globals.open_line)\n var e = 0;\n var point_index = 0;\n \n for(var layer_index = 0; layer_index < array_line_3d.length; layer_index++ ) {\n // This feels first point of each layer with the last e value\n point_index = 0;\n // This is for closed paths, to have a first layer point with extrusion\n if (!globals.open_line && layer_index != 0) {\n var current_point = array_line_3d[layer_index-1][array_line_3d[layer_index].length - 1];\n var target_point = array_line_3d[layer_index][0];\n var delta_x = target_point[0] - current_point[0];\n var delta_y = target_point[1] - current_point[1];\n var delta_z = target_point[2] - current_point[2];\n var distance = Math.sqrt(Math.pow(delta_x,2) + Math.pow(delta_y,2) + Math.pow(delta_z,2));\n e += distance * parameters.nozzle_material_surfaces_ratio; \n array_line_3d[layer_index][point_index][3] = Math.round(10000 * e) / 10000; \n } else {\n array_line_3d[layer_index][point_index][3] = e;\n }\n for(point_index = 0; point_index < (array_line_3d[layer_index].length - 1); point_index++) {\n var current_point = array_line_3d[layer_index][point_index];\n var target_point = array_line_3d[layer_index][point_index+1];\n var delta_x = target_point[0] - current_point[0];\n var delta_y = target_point[1] - current_point[1];\n var delta_z = target_point[2] - current_point[2];\n var distance = Math.sqrt(Math.pow(delta_x,2) + Math.pow(delta_y,2) + Math.pow(delta_z,2));\n // console.log(\"delta x = \" + delta_x + \", delta_y = \" + delta_y + \" ,delta z = \" + delta_z); \n // Extruder displacement = distance * Sn / Sm\n e += distance * parameters.nozzle_material_surfaces_ratio; \n //console.log(\"Distance = \" + distance + \", extrusion = \" + e);\n e = array_line_3d[layer_index][point_index+1][3] = Math.round(10000 * e) / 10000;\n }\n }\n //array_line_3d[][][]\n}", "pdist2(coord1, coord2) {\n return this.pnorm2(coord1.offset(coord2));\n }", "visitLinePixels(visitor, line) {\n const vec = { dx: line.x1 - line.x0, dy: line.y1 - line.y0 }\n // If line is a point we're lazy (and eliminate some special cases)\n if (vec.dx === 0 && vec.dy === 0) {\n const x = Math.floor(line.x0);\n const y = Math.floor(line.y0);\n const idx = x + this.width * y;\n visitor(x, y, idx);\n return;\n }\n const len = Math.sqrt(Math.pow(vec.dx, 2) + Math.pow(vec.dy, 2));\n const unit = { dx: vec.dx / len, dy: vec.dy / len };\n const ortho = { dx: unit.dy, dy: -unit.dx };\n // Using a Set makes it easy to comply with the pixel uniqueness\n // requirement\n const indices = new Set();\n const addPixel = (x, y) => {\n x = Math.floor(x);\n y = Math.floor(y);\n if (x < 0 || x >= this.width)\n return\n if (y < 0 || y >= this.height)\n return;\n const idx = x + this.width * y;\n if (idx !== idx)\n throw new Error('Trying to add NaN as a line pixel index');\n indices.add(idx);\n };\n const pos = { x: line.x0, y: line.y0 };\n const sigX = line.x1 - line.x0;\n const sigY = line.y1 - line.y0;\n do {\n addPixel(pos.x, pos.y);\n for (let i = 0; i < this.strokeWidth; i++) {\n const xt = pos.x + .5 * ortho.dx;\n const yt = pos.y + .5 * ortho.dy;\n addPixel(xt, yt);\n const xb = pos.x - .5 * ortho.dx;\n const yb = pos.y - .5 * ortho.dy;\n addPixel(xb, yb);\n }\n pos.x += unit.dx;\n pos.y += unit.dy;\n } while((line.x1 - pos.x) * sigX > 0 || (line.y1 - pos.y) * sigY > 0);\n const iterator = indices.values();\n for (let i = 0; i < indices.size; i++) {\n const idx = iterator.next().value;\n const x = idx % this.width;\n const y = Math.floor(idx / this.width);\n if (x !== x || y !== y)\n throw new Error('Encountered line coordinates which are NaN');\n const res = visitor(x, y, idx);\n // Bailing mechanism\n if (res === false)\n break;\n }\n }", "updateGuidingLinePos(){\n if(this.guidingLine == undefined){\n return;\n }\n if(this.board.gameOverTriggered){\n return;\n }\n //guiding line will always go from the last node in the path\n var mousePos = this.board.game.input.activePointer;;\n var modMousePosX = this.board.game.input.activePointer.positionToCamera(this.board.game.cameras.main).x;\n var modMousePosY = this.board.game.input.activePointer.positionToCamera(this.board.game.cameras.main).y;\n this.guidingLineGraphics.clear();\n var lerpedPosX = Phaser.Math.Interpolation.Linear([this.guidingLine.x2, modMousePosX], 0.3);\n var lerpedPosY = Phaser.Math.Interpolation.Linear([this.guidingLine.y2, modMousePosY], 0.3);\n this.guidingLine.setTo(this.getTail().getOffSetPos().x,this.getTail().getOffSetPos().y, lerpedPosX, lerpedPosY);\n\n //helper to progamatically include as many segments of the animation for the leading line\n var lineLength = Phaser.Geom.Line.Length(this.guidingLine);\n var numSegments = Math.floor(lineLength/(64 * this.board.hexScale));\n if(numSegments > this.pointerPath.length){\n var newSegment = this.board.game.add.sprite(0,0, \"ph_pointerPath\");\n newSegment.anims.play(\"POINTERPATH_IDLE\");\n this.pointerPath.push(newSegment);\n newSegment.setOrigin(0,0.5);\n newSegment.setScale(this.board.hexScale);\n\n }\n if(numSegments < this.pointerPath.length){\n var pathToRemove = this.pointerPath.splice(this.pointerPath.length-1, 1);\n pathToRemove[0].destroy();\n\n }\n //draw out each segment for the leading line\n var angle = Phaser.Math.Angle.Between(this.guidingLine.x1, this.guidingLine.y1, this.guidingLine.x2, this.guidingLine.y2)\n for(var i = 0; i< this.pointerPath.length; i++){\n //var xPos = Phaser.Phaser.Math.Interpolation.Linear[]\n var xPos = this.getTail().getOffSetPos().x + Math.cos(angle) * (64*this.board.hexScale * i);\n var yPos = this.getTail().getOffSetPos().y + Math.sin(angle) * (64*this.board.hexScale * i);\n this.pointerPath[i].setAngle(angle * Phaser.Math.RAD_TO_DEG);\n this.pointerPath[i].setPosition(xPos,yPos);\n }\n this.pointerImage.setPosition(lerpedPosX, lerpedPosY);\n\n }", "addStrokeGuide(){\n var id = guid();\n var that = this;\n \n var firstPoint = JSON.parse(JSON.stringify(this.tempArrayStroke[0]))\n var arrayPoints = JSON.parse(JSON.stringify(this.tempArrayStroke));\n arrayPoints.forEach((d)=>{\n d[0] = d[0] - firstPoint[0];\n d[1] = d[1] - firstPoint[1]\n })\n\n\n arrayPoints = simplify(arrayPoints, 2)\n\n // var data = {\n // 'points': arrayPoints, \n // 'id': id,\n // 'paddingBetweenLines': 50, \n // 'width':100,\n // 'height':100,\n // 'placeHolder': [\n // {'id':'background', 'data': {'method': 'repeat'}, 'lines':[]}, \n // {'id':'topbackground', 'data': {'method': 'repeat'}, 'lines':[]}, \n // {'id':'leftbackground', 'data': {'method': 'repeat'}, 'lines':[]}, \n // {'id':'rightbackground', 'data': {'method': 'repeat'}, 'lines':[]}, \n // {'id':'bottombackground', 'data': {'method': 'repeat'}, 'lines':[]}, \n\n // {'id':'topLeftCorner', 'data': {}, 'lines':[]}, \n // {'id':'topRightCorner', 'data': {}, 'lines':[]}, \n // {'id':'bottomLeftCorner', 'data': {}, 'lines':[]}, \n // {'id':'bottomRightCorner', 'data': {}, 'lines':[]}, \n \n // {'id':'left', 'data': {}, 'lines':[]}, \n // {'id':'right', 'data': {}, 'lines':[]}, \n // {'id':'middle', 'data': {}, 'lines':[]}],\n // 'position': [firstPoint[0],firstPoint[1]],\n // 'textPosition': {'where': 'right', 'position': [25,20]},\n \n // }\n\n var data = {\n 'points': arrayPoints, \n 'id': id,\n 'paddingBetweenLines': 50, \n 'width':200,\n 'height':150,\n 'placeHolder': [\n {'id':'outerBackground', 'position':[0,0], 'lines':[]},\n {'id':'backgroundLine', 'position':[0,0], 'lines':[]},\n {'id':'backgroundText', 'position':[0,0], 'lines':[]}\n ],\n 'position': [firstPoint[0],firstPoint[1]]\n \n }\n\n this.props.addStickyLines(data);\n\n // console.log({'idLines':that.objectIn, 'class':['item-'+id]})\n //Add class to element\n \n // this.props.addLinesClass({'idLines':that.objectIn, 'class':['item-'+id]})\n // for (var i in this.objectIn){\n // d3.select('#item-'+that.objectIn[i]).classed('sticky-'+id, true);\n // }\n }", "add2dRenderText(text,vec3d, withline){\n let vvec = {text:text,vec:vec3d , withline:withline}\n this.text2d.push(vvec);\n }", "static DistanceToLine() {}", "function wavedLine(point1, point2, waveLength, waveHeight, tension, adjustWaveLength) {\n var x1 = point1.x;\n var y1 = point1.y;\n var x2 = point2.x;\n var y2 = point2.y;\n var distance = _utils_Math__WEBPACK_IMPORTED_MODULE_4__[\"getDistance\"](point1, point2);\n if (adjustWaveLength) {\n waveLength = distance / Math.round(distance / waveLength);\n }\n var d = _Registry__WEBPACK_IMPORTED_MODULE_0__[\"registry\"].getCache(_utils_Utils__WEBPACK_IMPORTED_MODULE_3__[\"stringify\"]([\"wavedLine\", point1.x, point2.x, point1.y, point2.y, waveLength, waveHeight]));\n if (!d) {\n if (distance > 0) {\n var angle = Math.atan2(y2 - y1, x2 - x1);\n var cos = Math.cos(angle);\n var sin = Math.sin(angle);\n var waveLengthX = waveLength * cos;\n var waveLengthY = waveLength * sin;\n if (waveLength <= 1 || waveHeight <= 1) {\n d = _Path__WEBPACK_IMPORTED_MODULE_1__[\"lineTo\"](point2);\n }\n else {\n var halfWaveCount = Math.round(2 * distance / waveLength);\n var points = [];\n var sign = 1;\n if (x2 < x1) {\n sign *= -1;\n }\n if (y2 < y1) {\n sign *= -1;\n }\n for (var i = 0; i <= halfWaveCount; i++) {\n sign *= -1;\n var x = x1 + i * waveLengthX / 2 + sign * waveHeight / 2 * sin;\n var y = y1 + i * waveLengthY / 2 - sign * waveHeight / 2 * cos;\n points.push({ x: x, y: y });\n }\n d = new Tension(tension, tension).smooth(points);\n }\n }\n else {\n d = \"\";\n }\n _Registry__WEBPACK_IMPORTED_MODULE_0__[\"registry\"].setCache(_utils_Utils__WEBPACK_IMPORTED_MODULE_3__[\"stringify\"]([\"wavedLine\", point1.x, point2.x, point1.y, point2.y, waveLength, waveHeight]), d);\n }\n return d;\n}", "addStep(closePoint, farPoint, edgePoint) {\n this.closePoints.push(closePoint);\n this.farPoints.push(farPoint);\n // this.edgePoints.push(edgePoint);\n \n let lastIndex = this.getCount() - 2;\n let currentIndex = this.getCount() - 1;\n if(lastIndex < 0) {lastIndex = 0;}\n \n let polygonDrawable = (new PolygonDrawable([this.farPoints[lastIndex], this.farPoints[currentIndex], this.closePoints[currentIndex], this.closePoints[lastIndex]])).setStyle(this.trailStyle.copy().setStep(this.trailStyle.getStep())).setLifespan(this.trailStyle.duration).setCamera(this.camera);\n \n // polygonDrawable.translate(Vector.subtraction(farPoint, closePoint).normalize(16));\n \n this.polygonDrawables.push(polygonDrawable);\n // this.edgePolygons.push((new PolygonDrawable([this.farPoints[lastIndex], this.farPoints[currentIndex], this.edgePoints[currentIndex], this.edgePoints[lastIndex]])).setStyle(ColorTransition.from(this.edgeStyle)).setLifespan(this.edgeStyle.duration).setCamera(this.camera));\n \n this.lifespan = Math.max(this.lifespan, this.trailStyle.duration, this.edgeStyle.duration);\n \n for(let i = 0; i < this.otherTrails.length; ++i) {\n let otherTrail = this.otherTrails[i];\n \n if(otherTrail.edgeWidth) {\n let vector = Vector.subtraction(farPoint, closePoint).normalize(otherTrail.edgeWidth);\n \n closePoint = farPoint;\n farPoint = vector.add(farPoint);\n \n if(otherTrail.edgeWidth < 0) {\n let x = closePoint;\n closePoint = farPoint;\n farPoint = x;\n }\n }\n \n otherTrail.addStep(closePoint, farPoint);\n }\n \n return this;\n }", "function renderNormal(_startPoint, normal, scale) {\n\n\t\tif(scale == undefined) {\n\t\t\tscale = 50.0;\n\t\t};\n\n\t\tvar colorBlack = data.colors[6];\n\n\t\tvar startPoint = vec3.create();\n\t\tvec3.set(_startPoint, startPoint);\n\t\tvar endPoint = vec3.create();\n\t\tvar scaledNormal = vec3.create();\n\t\tvec3.scale(normal, scale, scaledNormal);\n\n\t\tvec3.add(startPoint, scaledNormal, endPoint);\n\n\t\tmat4.multiplyVec3(viewportProjection, startPoint);\n\t\tmat4.multiplyVec3(viewportProjection, endPoint);\n\n\t\traster.calcPlaneEquationForStraightLine(startPoint, normal);\n\t\traster.drawLineBresenhamGivenStartEndPoint(ctx, startPoint, endPoint, colorBlack, false);\n\t}", "function DrawingLayerLineTo(index1, index2)\n{\n\tvar tmpPt = new Object();\n\tvar viewMat = fl.getDocumentDOM().viewMatrix;\n\ttmpPt.x = thetrapezium[index1][index2];\n\ttmpPt.y = thetrapezium[index1][index2+1];\n\ttransformPoint(tmpPt, viewMat);\n\tfl.drawingLayer.lineTo(tmpPt.x, tmpPt.y);\t\n}", "getStraightLines() {\n\n let points = [];\n\n points.push(this.getLine(-1, 0));\n points.push(this.getLine(1, 0));\n points.push(this.getLine(0, -1));\n points.push(this.getLine(0, 1));\n\n return points;\n\n }", "function updateTimeLine () {\n var meanCol = columnMean(parsedData.colBased)\n // set the domains for yScaleTLOri, xScaleTL\n timeLine.yScaleOri.domain(\n d3.extent(meanCol, function (d) {\n return d.val\n })\n )\n timeLine.xScale.domain(d3.extent(Object.keys(parsedData.colBased)))\n timeLine.xScale.domain(d3.extent(Array.from(Array(Object.keys(parsedData.colBased).length).keys())))\n\n // update yAxisTLOri and xAxisTL\n d3.select('#g-xAxisTL')\n .call(timeLine.xAxisTL)\n .selectAll('text')\n .attr('font-weight', 'normal')\n .style('text-anchor', 'end')\n .attr('dx', '.8em')\n .attr('dy', '.5em')\n .attr('transform', function (d) {\n return 'rotate(-30)'\n })\n d3.select('#g-yAxisTLOri')\n .call(timeLine.yAxisOri)\n\n // attach data to x&yaxis and draw the linear timeline of the orignal dataset\n d3.select('#pathTimelineOri')\n .datum(meanCol)\n .attr('fill', 'none')\n .attr('stroke', 'black')\n .attr('stroke-linejoin', 'round')\n .attr('stroke-linecap', 'round')\n .attr('stroke-width', 2)\n .attr('d', timeLine.lineOri)\n .attr('transform', 'translate(' + globalSettings.xpadding + ',' + -globalSettings.ypadding + ')')\n\n // draw points in the timeline\n d3.select('#g-TLPointsOri')\n .selectAll('rect').remove()\n d3.select('#g-TLPointsOri')\n .selectAll('rect')\n .data(meanCol)\n .enter()\n .append('rect')\n .attr('id', function (d) {\n return 'c' + d.col\n })\n .attr('x', function (d) {\n return timeLine.xScale(d.idx) - timeLine.wPoints / 2\n })\n .attr('y', function (d) {\n return timeLine.yScaleOri(d.val) - timeLine.hPoints / 2\n })\n .attr('height', timeLine.wPoints)\n .attr('width', timeLine.hPoints)\n .attr('stroke', 'black')\n .attr('stroke-width', 1)\n .attr('fill', 'black')\n .on('mouseover', mouseOverOri)\n .on('mouseout', mouseOutOri)\n}", "function normalize(distance) {\n return distance / (0.005 * r);\n}", "calcDirectionCoordsForTraitor(lat1, lon1, lat2, lon2) {\n //Line will be around 1000m long or something\n const multiplier = 1000 / this.calcDistance(lat1, lon1, lat2, lon2);\n return ([{\n latitude: lat2 + ((lat1 - lat2) * multiplier),\n longitude: lon2 + ((lon1 - lon2) * multiplier)\n },\n {\n latitude: lat2,\n longitude: lon2\n }]);\n }", "handleLineString3d(ls0) {\n if (this._geometry1 instanceof LineString3d_1.LineString3d) {\n const ls1 = this._geometry1;\n if (ls0.numPoints() === ls1.numPoints()) {\n const ls = LineString3d_1.LineString3d.create();\n const workPoint = Point3dVector3d_1.Point3d.create();\n const workPoint0 = Point3dVector3d_1.Point3d.create();\n const workPoint1 = Point3dVector3d_1.Point3d.create();\n for (let i = 0; i < ls0.numPoints(); i++) {\n ls0.pointAt(i, workPoint0);\n ls1.pointAt(i, workPoint1);\n workPoint0.interpolate(this._fraction, workPoint1, workPoint);\n ls.addPoint(workPoint);\n }\n return ls;\n }\n }\n return undefined;\n }", "setLineDash(...values) {\n this.ctx.setLineDash(values);\n }", "toLine() {\n return {\n x1: this[0][0],\n y1: this[0][1],\n x2: this[1][0],\n y2: this[1][1]\n };\n }", "function addThree(dash){\n ctx.beginPath();\n if (dash){\n ctx.setLineDash([5]);\n }\n single();\n ctx.lineTo(0, height-(rows*step)-(step/3));\n ctx.stroke();\n ctx.moveTo((width/2), height-((rows-1)*step));\n ctx.lineTo(0, height-(rows*step)-step*2/3);\n ctx.stroke();\n ctx.setLineDash([]);\n }", "function reconstructLineWidth(inBuffer, startIndex) {\n const xd = inBuffer[startIndex * 2 + 3] - inBuffer[startIndex * 2];\n const yd = inBuffer[startIndex * 2 + 3 + 1] - inBuffer[startIndex * 2 + 1];\n const zd = inBuffer[startIndex * 2 + 3 + 2] - inBuffer[startIndex * 2 + 2];\n return Math.sqrt(xd * xd + yd * yd + zd * zd) * 0.5;\n}", "function tr(xy) {\n return [(xy[0] - extent[0]) / (extent[2] - extent[0]) * size[0],\n (xy[1] - extent[3]) / (extent[1] - extent[3]) * size[1]\n ];\n }", "function drawALineOrth(ctx, line) { \n //check whether drawing dashed lines\n if (line.type == \"dashed\"){\n ctx.setLineDash([dashLineWidth, dashSpaceWidth]);\n }\n else{\n ctx.setLineDash([]);\n }\n \n ctx.beginPath();\n ctx.moveTo(findTrueXCoordOrth(line.x1), findTrueYCoordOrth(line.y1));\n ctx.lineWidth = lineWidth;\n ctx.lineTo(findTrueXCoordOrth(line.x2), findTrueYCoordOrth(line.y2));\n if (line.color == \"correct\"){\n ctx.strokeStyle = lineCorrectColor;\n }\n else if (line.color == \"incorrect\"){\n ctx.strokeStyle = lineIncorrectColor;\n }\n else {\n ctx.strokeStyle = lineColor;\n }\n ctx.stroke();\n}", "normalized()\n {\n let normalized = new Vector2(this.x, this.y);\n normalized.divide(normalized.getLength());\n return normalized;\n }", "update() {\r\n\t\t//Update the functions slope and y-axis intercept\r\n\t\tthis.formula.slope = -((this.endPointB.y - this.endPointA.y) * this.unit_per_square.y) / ((this.endPointB.x - this.endPointA.x) * this.unit_per_square.x); //Inverse the slope because 0,0 starts at top left, not bottom left\r\n\t\tthis.formula.y_intercept = -(this.formula.slope * this.endPointA.x - (this.numRows - this.endPointA.y)); //Inverse the slope because 0,0 starts at top left, not bottom left\r\n\t\tthis.formula.x_intercept = 0;\r\n\t\t//Update the line that connects the two points\r\n\t\tlet lines = this.slopeLine.selectAll('line');\r\n\t\tlines.remove();\r\n\t\tthis.slopeLine.append(\"line\")\r\n\t\t\t.attr('x1', this.endPointA.x * this.cell_size + this.offset.x)\r\n\t\t\t.attr('y1', this.endPointA.y * this.cell_size + this.offset.y)\r\n\t\t\t.attr('x2', this.endPointB.x * this.cell_size + this.offset.x)\r\n\t\t\t.attr('y2', this.endPointB.y * this.cell_size + this.offset.y)\r\n\t\t\t.attr('stroke', 'black');\r\n\r\n\r\n\t\t//Update the formula\r\n\t\tthis.updateFormulas();\r\n\r\n\t\tthis.dxdy_lines();\r\n\t}", "function lineDist(toPt, pt1, pt2) {\n var num = Math.abs((pt2.y - pt1.y) * toPt.x - (pt2.x - pt1.x) * toPt.y + pt2.x * pt1.y - pt2.y * pt1.x)\n var denom = Math.sqrt(Math.pow(pt2.y - pt1.y, 2) + Math.pow(pt2.x - pt1.x, 2))\n return num / denom;\n}", "normalizeCurve() {\n const center = this[Math.floor(this.length / 2)]\n const min = Math.min(...this) - center\n const max = Math.max(...this) - center\n\n const amp = Math.abs(max) > Math.abs(min) ? max : min\n for (let i = 0; i < this.length; i++) {\n const v = this[i]\n this[i] = (v - center) / amp\n }\n }", "toLine() {\n return {\n x1: this[0][0],\n y1: this[0][1],\n x2: this[1][0],\n y2: this[1][1]\n }\n }", "function computeHermiteSmoothedData (gd) {\n var smooth = this.renderer.smooth;\n var tension = this.renderer.tension;\n var dim = this.canvas.getWidth();\n var xp = this._xaxis.series_p2u;\n var yp = this._yaxis.series_p2u; \n var steps =null;\n var _steps = null;\n var a = null;\n var a1 = null;\n var a2 = null;\n var slope = null;\n var slope2 = null;\n var temp = null;\n var t, s, h1, h2, h3, h4;\n var TiX, TiY, Ti1X, Ti1Y;\n var pX, pY, p;\n var sd = [];\n var spd = [];\n var dist = gd.length/dim;\n var min, max, stretch, scale, shift;\n var _smoothedData = [];\n var _smoothedPlotData = [];\n if (!isNaN(parseFloat(smooth))) {\n steps = parseFloat(smooth);\n }\n else {\n steps = getSteps(dist, 0.5);\n }\n if (!isNaN(parseFloat(tension))) {\n tension = parseFloat(tension);\n }\n\n for (var i=0, l = gd.length-1; i < l; i++) {\n\n if (tension === null) {\n slope = Math.abs((gd[i+1][1] - gd[i][1]) / (gd[i+1][0] - gd[i][0]));\n\n min = 0.3;\n max = 0.6;\n stretch = (max - min)/2.0;\n scale = 2.5;\n shift = -1.4;\n\n temp = slope/scale + shift;\n\n a1 = stretch * tanh(temp) - stretch * tanh(shift) + min;\n\n // if have both left and right line segments, will use minimum tension. \n if (i > 0) {\n slope2 = Math.abs((gd[i][1] - gd[i-1][1]) / (gd[i][0] - gd[i-1][0]));\n }\n temp = slope2/scale + shift;\n\n a2 = stretch * tanh(temp) - stretch * tanh(shift) + min;\n\n a = (a1 + a2)/2.0;\n\n }\n else {\n a = tension;\n }\n for (t=0; t < steps; t++) {\n s = t / steps;\n h1 = (1 + 2*s)*Math.pow((1-s),2);\n h2 = s*Math.pow((1-s),2);\n h3 = Math.pow(s,2)*(3-2*s);\n h4 = Math.pow(s,2)*(s-1); \n \n if (gd[i-1]) { \n TiX = a * (gd[i+1][0] - gd[i-1][0]); \n TiY = a * (gd[i+1][1] - gd[i-1][1]);\n } else {\n TiX = a * (gd[i+1][0] - gd[i][0]); \n TiY = a * (gd[i+1][1] - gd[i][1]); \n }\n if (gd[i+2]) { \n Ti1X = a * (gd[i+2][0] - gd[i][0]); \n Ti1Y = a * (gd[i+2][1] - gd[i][1]);\n } else {\n Ti1X = a * (gd[i+1][0] - gd[i][0]); \n Ti1Y = a * (gd[i+1][1] - gd[i][1]); \n }\n \n pX = h1*gd[i][0] + h3*gd[i+1][0] + h2*TiX + h4*Ti1X;\n pY = h1*gd[i][1] + h3*gd[i+1][1] + h2*TiY + h4*Ti1Y;\n p = [pX, pY];\n\n _smoothedData.push(p);\n _smoothedPlotData.push([xp(pX), yp(pY)]);\n }\n }\n _smoothedData.push(gd[l]);\n _smoothedPlotData.push([xp(gd[l][0]), yp(gd[l][1])]);\n\n return [_smoothedData, _smoothedPlotData];\n }", "normalizeVec2(v, dest) {\n const f = 1.0 / math.lenVec2(v);\n return math.mulVec2Scalar(v, f, dest);\n }", "Normalize() {\n let vec = Vec2.Normalized(this);\n this.x = vec.x;\n this.y = vec.y;\n return this;\n }", "normalize() {\n\t\tlet m = this.getMagnitude();\n\t\tlet x = 0;\n\t\tlet y = 0\n\t\t\n\t\tif(m !== 0) {\n\t\t\tx = this.x / m;\n\t\t\ty = this.y / m;\n\t\t}\n\t\t\n\t\treturn new Vector(x, y);\n\t}", "createLineBetween2Points (p1, p2, more = false) {\n const line = BABYLON.MeshBuilder.CreatePlane('wire', {height: 0.05, width: 1, sideOrientation: BABYLON.Mesh.DOUBLESIDE}, this.scene)\n var dist = parseFloat(Number(BABYLON.Vector3.Distance(p1, p2)).toFixed(2))\n var rotAngle = Math.atan((p1.x - p2.x) / (p1.z - p2.z))\n \n line.position = BABYLON.Vector3.Center(p1, p2)\n line.position.y = 0.01\n line.rotation = new BABYLON.Vector3(Math.PI / 2, rotAngle + Math.PI / 2, 0)\n line.scaling.x = dist + ((more === true) ? 0.025 : -0.05)\n line.renderingGroupId = 1\n\n line.material = new BABYLON.StandardMaterial('mat', this.scene)\n line.material.emissiveColor = BABYLON.Color3.FromHexString('#00700b')\n\n if (more === true) {\n this.addActionOnWire(line)\n }\n\n return line\n }", "drawLineOnGrid(x1, y1, x2, y2) { \n\n let deltaX = x2 - x1;\n let deltaY = y2 - y1; \n \n // function to return one of \"-\" or \"X\" depending on line orientation\n let keyCharacter = this.getKeyCharacterForLine(deltaX, deltaY);\n \n // if the line has gradient < 1\n if (Math.abs(deltaY) <= Math.abs(deltaX)) { \n if (deltaX >= 0) {\n // line is drawn left to right\n this.drawShallowLine(x1, y1, x2, deltaX, deltaY, keyCharacter);\n } else {\n // line is drawn right to left\n this.drawShallowLine(x2, y2, x1, deltaX, deltaY, keyCharacter);\n } \n // if the line has gradient > 1 \n } else { \n if (deltaY >= 0) {\n // line is drawn downwards\n this.drawSteepLine(x1, y1, y2, deltaX, deltaY, keyCharacter)\n } else { \n // line is drawn upwards\n this.drawSteepLine(x2, y2, y1, deltaX, deltaY, keyCharacter)\n } \n }\n // log the end square so we can get the highlighting dimensions when required\n this.endSquare = this.filledSquares[this.filledSquares.length - 1];\n }", "function normalize(data, durationLinePos) {\n var noEmptyLine = _.filter(data.split('\\n'), function(line) { return line.trim().length !== 0; });\n noEmptyLine.splice(noEmptyLine.length - durationLinePos - 1, 1);\n return noEmptyLine.join('\\n');\n}", "function momentNormalize() {\n\t\t\t\n\t\tnewHeight = 256;\n\t\tnewWidth = 256;\n\t\txMin = 256;\n\t\txMax = 0;\n\t\tyMin = 256;\n\t\tyMax = 0;\n\t\t// first determine drawn character width / length\n\t\tfor(var i = 0;i<recordedPattern.length;i++) {\n\t\t var stroke_i = recordedPattern[i];\n\t\t for(var j = 0; j<stroke_i.length;j++) {\n\t\t\tx = stroke_i[j][0];\n\t\t\ty = stroke_i[j][1];\n\t\t\tif(x < xMin) {\n\t\t\t xMin = x;\n\t\t\t}\n\t\t\tif(x > xMax) {\n\t\t\t xMax = x;\n\t\t\t}\n\t\t\tif(y < yMin) {\n\t\t\t yMin = y;\n\t\t\t}\n\t\t\tif(y > yMax) {\n\t\t\t yMax = y;\n\t\t\t}\n\t\t }\n\t\t}\t\n\t\toldHeight = Math.abs(yMax - yMin);\n\t\toldWidth = Math.abs(xMax - xMin);\n\t\t\t\n\t\tvar r2 = aran(oldWidth, oldHeight);\n\t\t\n\t\tvar aranWidth = newWidth;\n\t\tvar aranHeight = newHeight;\n\t\t\n\t\tif(oldHeight > oldWidth) {\n\t\t\taranWidth = r2 * newWidth; \n\t\t} else {\n\t\t\taranHeight = r2 * newHeight;\n\t\t}\t\t\n\t\t\t\t\n\t\tvar xOffset = (newWidth - aranWidth)/2;\n\t\tvar yOffset = (newHeight - aranHeight)/2; \n\t\t\n\t\tvar m00_ = m00(recordedPattern);\n\t\tvar m01_ = m01(recordedPattern);\n\t\tvar m10_ = m10(recordedPattern);\n\t\t\t\t\n\t\tvar xc_ = (m10_/m00_);\n\t\tvar yc_ = (m01_/m00_);\n\t\t\t\t\n\t\tvar xc_half = aranWidth/2;\n\t\tvar yc_half = aranHeight/2;\n\t\t\n\t\tvar mu20_ = mu20(recordedPattern, xc_);\n\t\tvar mu02_ = mu02(recordedPattern, yc_);\n\n\t\tvar alpha = (aranWidth) / (4 * Math.sqrt(mu20_/m00_));\n\t\tvar beta = (aranHeight) / (4 * Math.sqrt(mu02_/m00_));\n\t\t\t\n\t\tvar nf = new Array();\n\t\tfor(var i=0;i<recordedPattern.length;i++) {\n\t\t\tvar si = recordedPattern[i];\n\t\t\tvar nsi = new Array();\n\t\t\tfor(var j=0;j<si.length;j++) {\n\t\t\t\t\n\t\t\t\tvar newX = (alpha * (si[j][0] - xc_) + xc_half);\n\t\t\t\tvar newY = (beta * (si[j][1] - yc_) + yc_half);\n\t\t\t\t\n\t\t\t\tnsi.push([newX,newY]);\n\t\t\t}\n\t\t\tnf.push(nsi);\n\t\t}\n\n\t\treturn transform(nf, xOffset, yOffset);\n\t}", "calcDirectionCoords(lat1, lon1, lat2, lon2) {\n //Line will be around 1000m long or something\n const multiplier = 1000 / this.calcDistance(lat1, lon1, lat2, lon2);\n return ([{\n latitude: lat1 + ((lat2 - lat1) * multiplier),\n longitude: lon1 + ((lon2 - lon1) * multiplier)\n },\n {\n latitude: lat1,\n longitude: lon1\n }]);\n }", "function tweenDash() {\n return function(t) {\n //total length of path (single value)\n var l = linePath.node().getTotalLength(); \n\n // this is creating a function called interpolate which takes\n // as input a single value 0-1. The function will interpolate\n // between the numbers embedded in a string. An example might\n // be interpolatString(\"0,500\", \"500,500\") in which case\n // the first number would interpolate through 0-500 and the\n // second number through 500-500 (always 500). So, then\n // if you used interpolate(0.5) you would get \"250, 500\"\n // when input into the attrTween above this means give me\n // a line of length 250 followed by a gap of 500. Since the\n // total line length, though is only 500 to begin with this\n // essentially says give me a line of 250px followed by a gap\n // of 250px.\n interpolate = d3.interpolateString(\"0,\" + l, l + \",\" + l);\n\n return interpolate(t);\n }\n }", "function DrawLine(x1, y1, x2, y2){\n let x, y, dx, dy, dx1, dy1, px, py, xe, ye, i;\n dx = x2 - x1;\n dy = y2 - y1;\n dx1 = Math.abs(dx);\n dy1 = Math.abs(dy);\n px = 2 * dy1 - dx1;\n py = 2 * dx1 - dy1;\n if (dy1 <= dx1) {\n if (dx >= 0) {\n x = x1; y = y1; xe = x2;\n } else {\n x = x2; y = y2; xe = x1;\n }\n if($('#'+y+'a'+x).attr('type') == 'tile')\n prev_pixels.push($('#'+y+'a'+x));\n for (i = 0; x < xe; i++) {\n x = x + 1;\n if (px < 0) {\n px = px + 2 * dy1;\n } else {\n if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0)) {\n y = y + 1;\n } else {\n y = y - 1;\n }\n px = px + 2 * (dy1 - dx1);\n }\n if($('#'+y+'a'+x).attr('type') == 'tile')\n prev_pixels.push($('#'+y+'a'+x));\n }\n } else {\n if (dy >= 0) {\n x = x1; y = y1; ye = y2;\n } else { \n x = x2; y = y2; ye = y1;\n }\n if($('#'+y+'a'+x).attr('type') == 'tile')\n prev_pixels.push($('#'+y+'a'+x));\n for (i = 0; y < ye; i++) {\n y = y + 1;\n if (py <= 0) {\n py = py + 2 * dx1;\n } else {\n if ((dx < 0 && dy<0) || (dx > 0 && dy > 0)) {\n x = x + 1;\n } else {\n x = x - 1;\n }\n py = py + 2 * (dx1 - dy1);\n }\n if($('#'+y+'a'+x).attr('type') == 'tile')\n prev_pixels.push($('#'+y+'a'+x));\n }\n }\n}", "function render_linePositief() {\n var plotLine = hgiLine().mapping(['meetmoment', 'opgewektheid', 'ontspanning']).yDomain([0, 100]).legend(['Opgewektheid', 'Ontspanning']).yTicks(5).xLabel('Meetmoment').yLabel('Positieve gevoelens');\n //plotLine.overlayScale(0.75).overlayOffset(11);\n d3.select('#linePositief').datum(data).call(plotLine);\n}", "function PatchLine() { }", "function draw_line(x1,y1,x2,y2,width) { \n pos1 = [x1,y1];\n pos2 = [x2,y2];\n \n direction = get_direction_vector(pos1,pos2);\n rot = rotate90(direction);\n\n x1 = pos1[0] + width/2 * rot[0];\n y1 = pos1[1] + width/2 * rot[1];\n\n x2 = pos2[0] + width/2 * rot[0];\n y2 = pos2[1] + width/2 * rot[1];\n\n x3 = pos2[0] - width/2 * rot[0];\n y3 = pos2[1] - width/2 * rot[1];\n\n x4 = pos1[0] - width/2 * rot[0];\n y4 = pos1[1] - width/2 * rot[1];\n\n var st = paper.path(\"M \" + x1 + \" \" + y1 + \" L \"\n\t\t\t+ x2 + \" \" + y2 + \" L \"\n\t\t\t+ x3 + \" \" + y3 + \" L \"\n\t\t\t+ x4 + \" \" + y4 + \" z\");\n st.attr(\"fill\", \"black\");\n return st;\n}" ]
[ "0.57762873", "0.55524695", "0.55094326", "0.54340774", "0.53997064", "0.5353648", "0.5349044", "0.5273151", "0.5259148", "0.52504265", "0.5246135", "0.524062", "0.52261645", "0.5208733", "0.52063787", "0.52063787", "0.5196581", "0.5195464", "0.5155396", "0.514865", "0.5131945", "0.5119035", "0.5111038", "0.51078856", "0.51002634", "0.50982636", "0.50940377", "0.50845987", "0.5080921", "0.50708413", "0.50630033", "0.5052654", "0.5047557", "0.503966", "0.502855", "0.50255257", "0.5024179", "0.5012378", "0.50074786", "0.5007386", "0.49931556", "0.49680078", "0.49601215", "0.4933052", "0.49107504", "0.49072105", "0.49047762", "0.48868704", "0.48866653", "0.4879264", "0.4878426", "0.48750252", "0.486861", "0.4868114", "0.48678118", "0.48476166", "0.48464307", "0.48449585", "0.48419806", "0.48401284", "0.48401144", "0.48356137", "0.48176908", "0.48145187", "0.48143858", "0.48142177", "0.47954208", "0.4790946", "0.47884774", "0.47860265", "0.47814682", "0.47803557", "0.47696745", "0.47681773", "0.47659206", "0.47639653", "0.47632936", "0.47621453", "0.47611797", "0.47588107", "0.475587", "0.475531", "0.4753397", "0.47484726", "0.47411546", "0.47406036", "0.47403982", "0.47323912", "0.47288528", "0.47283858", "0.47278064", "0.4726571", "0.47245806", "0.4723242", "0.47229958", "0.4720342", "0.4717657", "0.47132495", "0.47126648", "0.47112578" ]
0.6270585
0
recursive disposal for meshes not materials, since they are reused
function _disposeMesh (mesh) { if (mesh.children) { mesh.children.forEach(_disposeMesh); } if (mesh.geometry && mesh.geometry.dispose) { mesh.geometry.dispose(); } if (mesh.dispose) { mesh.dispose(); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "dispose() {\n\n\t\tconst materials = this.materials;\n\t\tconst children = this.children;\n\n\t\tfor ( let i = 0; i < materials.length; i ++ ) {\n\n\t\t\tmaterials[ i ].dispose();\n\n\t\t}\n\n\t\tfor ( let i = 0; i < children.length; i ++ ) {\n\n\t\t\tconst child = children[ i ];\n\n\t\t\tif ( child.isMesh ) child.geometry.dispose();\n\n\t\t}\n\n\t}", "dispose() {\n\n\t\tthis._dispose();\n\n\t\tif ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();\n\t\tif ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();\n\n\t}", "dispose() {\n\n\t\t\tthis._dispose();\n\n\t\t\tif ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();\n\t\t\tif ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();\n\n\t\t}", "function dispose(object) {\n if (object.material) {\n object.material.dispose();\n }\n if (object.geometry) {\n object.geometry.dispose();\n }\n object.children.forEach((child) => dispose(child));\n}", "dispose() {\n\n\t\t\tthis._blurMaterial.dispose();\n\n\t\t\tif ( this._cubemapShader !== null ) this._cubemapShader.dispose();\n\t\t\tif ( this._equirectShader !== null ) this._equirectShader.dispose();\n\n\t\t\tfor ( let i = 0; i < _lodPlanes.length; i ++ ) {\n\n\t\t\t\t_lodPlanes[ i ].dispose();\n\n\t\t\t}\n\n\t\t}", "destroy() {\n this.children.forEach(mesh => mesh.destroy());\n }", "destroy() {\n this._destroyed = true;\n\n if (typeof this.freeFromPool === 'function') {\n this.freeFromPool();\n }\n\n if (this.currentMap) {\n this.currentMap.removeObject(this);\n } else if (this.currentScene) {\n this.currentScene.removeObject(this);\n }\n\n this.children.forEach((child) => {\n child.destroy();\n });\n\n // triggers the wave end\n if (this.wave) {\n this.wave.remove(this);\n }\n }", "cleanupScene(groupOrScene = null) {\n if (groupOrScene === null) {\n groupOrScene = this.scene;\n }\n const items = [...groupOrScene.children];\n for (let item of items) {\n if (item.children && item.children.length > 0) {\n this.cleanupScene(item);\n }\n const { geometry, material, texture } = item;\n if (geometry) {\n geometry.dispose();\n }\n if (material) {\n material.dispose();\n }\n if (texture) {\n texture.dispose();\n }\n if (typeof item.dispose === 'function') {\n item.dispose();\n }\n groupOrScene.remove(item);\n }\n }", "__$destroy() {\n if (this.isResFree()) {\n //console.log(\"MeshBase::__$destroy()... this.m_attachCount: \"+this.m_attachCount);\n this.m_ivs = null;\n this.m_bufDataList = null;\n this.m_bufDataStepList = null;\n this.m_bufStatusList = null;\n this.trisNumber = 0;\n this.m_transMatrix = null;\n }\n }", "destroy() {\n this.meshes.forEach(mesh => {\n mesh.destroy();\n });\n this.meshes.clear();\n this.lights.clear();\n this.__deleted = true;\n }", "clearContainer(container) {\n if (container && container.children)\n while (container.children.length > 0) {\n let obj = container.children[0];\n if (obj && obj.children != null)\n for (let child in obj.children)\n this.clearContainer(obj.children[child]);\n //entfernt Geometry\n if (obj && obj.geometry) obj.geometry.dispose();\n //entfernt Material, egal ob Liste oder nur ein Material\n if (obj && obj.material) {\n if (Array.isArray(obj.material)) {\n for (let i = 0; i < obj.material.length; i++)\n this.disposeAllMaterialProperties(obj.material[i]);\n } else this.disposeAllMaterialProperties(obj.material);\n }\n //entfernt, nachdem alle Materialien und Geometrien entfernt wurden das Objekt aus der Liste\n container.remove(container.children[0]);\n }\n }", "disposeAllMaterialProperties(material) {\n if (material) {\n //in case of map, bumpMap, normalMap, envMap ...\n Object.keys(material).forEach(prop => {\n if (!material[prop])\n return;\n if (material[prop] !== null && typeof material[prop].dispose === 'function')\n material[prop].dispose();\n });\n material.dispose();\n }\n }", "disposeAll() {\n let tilesBlocks = this.scene.getMeshesByTags('tilesBlock');\n\n for (let index = 0; index < tilesBlocks.length; index++) {\n tilesBlocks[index].dispose();\n }\n }", "function disposeMaterial (material, system) {\n\t material.dispose();\n\t system.unregisterMaterial(material);\n\t}", "function cleanup3DObject(object){\r\n\tobject.geometry.dispose();\r\n\tobject.material.dispose();\r\n\tscene.remove(object);\r\n} // END - Cleanup function", "dispose() {\n Object.keys(this.weightMap)\n .forEach(key => this.weightMap[key].forEach(tensor => tensor.dispose()));\n }", "function disposeMaterial (material, system) {\n material.dispose();\n system.unregisterMaterial(material);\n}", "detach() {\n _commons__WEBPACK_IMPORTED_MODULE_0__[\"finalizeResources\"].call(this);\n }", "_cleanUp() {\n this.removeChildren();\n\n // Remove references to the old shapes to ensure that they're rerendered\n this._q2Box = null;\n this._q3Box = null;\n this._medianLine = null;\n this._outerBorderShape = null;\n this._innerBorderShape = null;\n }", "deinit() {\n Logger.debug(`Deinitializing renderer...`);\n\n for(let name of Object.keys(this.shaders)) {\n this.shaders[name].deinit();\n }\n\n this.shaders = {};\n\n for(let name of Object.keys(this.meshes)) {\n this.meshes[name].deinit();\n }\n\n this.meshes = {};\n }", "resetObjects()\n {\n //remove rectangles for collidable bodies\n this.buttons.forEach(this.deleteBody, this, true);\n this.spikes.forEach(this.deleteBody, this, true);\n\n this.startdoors.destroy();\n this.enddoors.destroy();\n this.buttons.destroy();\n this.spikes.destroy();\n this.checkpoints.destroy();\n this.doors.destroy();\n }", "onDestroy() {\n this.rotAnimations.forEach((anim) => {\n anim.complete();\n });\n if (this.timeouts[0]) clearTimeout(this.timeouts[0]);\n if (this.timeouts[1]) clearTimeout(this.timeouts[1]);\n this.rotatable1.destroy();\n this.rotatable2.destroy();\n if (this.followers[0]) this.followers[0].forEach((f) => f.destroy());\n if (this.followers[1]) this.followers[1].forEach((f) => f.destroy());\n this.followers = [];\n if ( this.paths[0]) this.paths[0].destroy();\n if ( this.paths[1]) this.paths[1].destroy();\n this.paths = [];\n this.toprg.destroy();\n this.botrg.destroy();\n if (this.emitters) {\n this.emitters.forEach((emitter) => {\n emitter.killAll();\n emitter.stop();\n });\n }\n\n }", "finishedReconstruction() {\n this.reconPack = null;\n this.buffers = [];\n }", "destroy() {\n this.texture = null;\n this.matrix = null;\n }", "dispose() {\n const { _context, _vertexBuffer, _indexBuffer } = this;\n\n if (!!_context) {\n if (!!_vertexBuffer) {\n _context.deleteBuffer(_vertexBuffer);\n }\n if (!!_indexBuffer) {\n _context.deleteBuffer(_indexBuffer);\n }\n }\n\n this._overrideUniforms.clear();\n this._overrideSamplers.clear();\n\n this._context = null;\n this._vertexBuffer = null;\n this._indexBuffer = null;\n this._shader = null;\n this._overrideUniforms = null;\n this._overrideSamplers = null;\n }", "finishedReconstruction() {\n this.reconPack = null;\n this.buffers = [];\n }", "destroy() {\n super.destroy();\n if (this.material) {\n this.material.destroy();\n }\n if (this.geometry) {\n this.geometry.destroy();\n }\n }", "finishedReconstruction() {\n this.reconPack = null;\n this.buffers = [];\n }", "finishedReconstruction() {\n this.reconPack = null;\n this.buffers = [];\n }", "finishedReconstruction() {\n this.reconPack = null;\n this.buffers = [];\n }", "destroy() {\n if (this.reconstructor) {\n this.reconstructor.finishedReconstruction();\n }\n }", "function destroyPlayer(){\n player.mesh.dispose();\n // then what?\n }", "dispose() {\n const { _context, _shaders, _textures, _renderTargets, _events } = this;\n\n this._stopAnimation();\n _context.clear(_context.COLOR_BUFFER_BIT);\n\n for (const shader of _shaders.keys()) {\n this.unregisterShader(shader);\n }\n for (const texture of _textures.keys()) {\n this.unregisterTexture(texture);\n }\n for (const renderTarget of _renderTargets.keys()) {\n this.unregisterRenderTarget(renderTarget);\n }\n\n _events.dispose();\n\n this._extensions = null;\n this._lastTimestamp = null;\n this._canvas = null;\n this._context = null;\n this._shaders = null;\n this._textures = null;\n this._renderTargets = null;\n this._renderTargetsStack = null;\n this._events = null;\n this._activeShader = null;\n this._activeRenderTarget = null;\n this._activeViewportSize = null;\n this._clearColor = null;\n this._projectionMatrix = null;\n this._viewMatrix = null;\n this._modelMatrix = null;\n this._blendingConstants = null;\n this._stats = null;\n this._shaderApplierOut = null;\n this._shaderApplierGetValue = null;\n this.__onFrame = null;\n }", "function dispose()\n {\n var scope = this;\n this.tiles.forEach( function(tile){ tile.eventEmitter.removeListener( Tile.ON_TILE_LOADED, scope.appendTile ); tile.valid = false; tile.dispose(); });\n this.loadedTiles.forEach( function(tile){ tile.dispose(); });\n\n this.tiles = [];\n this.loadedTiles = [];\n this.keys = [];\n\n }", "deleteMeshSelf(webGL_scene) {\r\n if (this.m_meshSelf != undefined) {\r\n webGL_scene.remove(this.m_meshSelf);\r\n this.m_meshSelf.geometry.dispose();\r\n this.m_meshSelf.material.dispose();\r\n delete this.m_meshSelf;\r\n }\r\n }", "clear() {\n {\n for ( let tensor of this.tensors.values() ) {\n tensor.dispose();\n }\n this.tensors.clear();\n }\n\n {\n for ( let numberImage of this.images.values() ) {\n numberImage.disposeResources_and_recycleToPool();\n }\n this.images.clear();\n }\n }", "clear(){\n\t\tif(this.disposed)\n\t\t\treturn;\n\t\tthis.disposables.clear();\n\t}", "cleanup() {\n this.physicsEngine.cleanup(this.toClean);\n const gameInstance = this;\n this.toClean.forEach(function (name) {\n if (typeof gameInstance.objects[name] !== 'undefined') {\n delete gameInstance.objects[name];\n }\n });\n this.physicsEngine.cleanup(this.toClean);\n }", "function dispose() {\n\t dimensionGroups.forEach(function(group) { group.dispose(); });\n\t var i = dataListeners.indexOf(preAdd);\n\t if (i >= 0) dataListeners.splice(i, 1);\n\t i = dataListeners.indexOf(postAdd);\n\t if (i >= 0) dataListeners.splice(i, 1);\n\t i = removeDataListeners.indexOf(removeData);\n\t if (i >= 0) removeDataListeners.splice(i, 1);\n\t m &= zero;\n\t return filterAll();\n\t }", "disposeOldTiles() {\n let lastTilesBlock = this.generatedTilesBlocksNumber - 1,\n tilesBlocks = this.scene.getMeshesByTags('tilesBlock' + lastTilesBlock);\n\n for (let index = 0; index < tilesBlocks.length; index++) {\n tilesBlocks[index].dispose();\n }\n }", "clear()\n {\n //this.object.geometry.dispose();\n //this.object.material.dispose();\n scene.remove(this.object);\n this.object = new THREE.Mesh();\n scene.add(this.object);\n\n this.points = new List();\n }", "clearAndClose() {\n this.tensorMap.forEach(value => value.dispose());\n this.tensorMap.clear();\n this.handle.dispose();\n }", "destroy () {\n\t\tthis.disposables.dispose()\n\t\tthis.classRanges.clear()\n\t\tthis.methodRanges.clear()\n\t\tthis.classMapping.clear()\n\t\tthis.methodMapping.clear()\n\t}", "disposeWall() {\n if (this.wall.parent !== null) {\n this.object.remove(this.wall);\n }\n this.wall.geometry.dispose();\n this.wall.material.dispose();\n this.emit('destroyed');\n }", "function scene::Destroy(system)\r\n{\r\n print(\"\\r\\nDestroy(system)\\r\\n\");\r\n loaded = false;\r\n delete bsp;\r\n delete splash;\r\n delete caption;\r\n delete menubar;\r\n //maps.resize(0);\r\n //menubar.resize(0);\r\n \r\n system.Stop(); \r\n}", "destroy() {\n for (var tileId in this._tiles) {\n if (this._tiles.hasOwnProperty(tileId)) {\n const tile = this._tiles[tileId];\n for (var i = 0, leni = tile.nodes.length; i < len; i++) {\n const node = tile.nodes[i];\n node._destroy();\n }\n putBatchingBuffer(tile.buffer);\n }\n }\n this.scene.camera.off(this._onCameraViewMatrix);\n for (var i = 0, len = this._layers.length; i < len; i++) {\n this._layers[i].destroy();\n }\n for (var i = 0, len = this._nodes.length; i < len; i++) {\n this._nodes[i]._destroy();\n }\n this.scene._aabbDirty = true;\n if (this._isModel) {\n this.scene._deregisterModel(this);\n }\n super.destroy();\n }", "destroy() {\n if (this.reconstructor) {\n this.reconstructor.finishedReconstruction();\n }\n }", "dispose() {\n this.workers.forEach(t => t.dispose());\n if (this.own) {\n this.terminal.dispose();\n }\n }", "destroy() {\n // unbind (texture) asset references\n for (const asset in this._assetReferences) {\n this._assetReferences[asset]._unbind();\n }\n this._assetReferences = null;\n\n super.destroy();\n }", "destroy() {\n if (this.reconstructor) {\n this.reconstructor.finishedReconstruction();\n }\n }", "destroy() {\n if (this.reconstructor) {\n this.reconstructor.finishedReconstruction();\n }\n }", "destroy() {\n if (this.reconstructor) {\n this.reconstructor.finishedReconstruction();\n }\n }", "recreatePhysicalShapes(component) {\n var entity = component.entity;\n var data = component.data;\n\n if (typeof Ammo !== 'undefined') {\n if (entity.trigger) {\n entity.trigger.destroy();\n delete entity.trigger;\n }\n\n if (data.shape) {\n if (component._compoundParent) {\n this.system._removeCompoundChild(component._compoundParent, data.shape);\n\n if (component._compoundParent.entity.rigidbody)\n component._compoundParent.entity.rigidbody.activate();\n }\n\n Ammo.destroy(data.shape);\n data.shape = null;\n }\n\n data.shape = this.createPhysicalShape(component.entity, data);\n\n var firstCompoundChild = ! component._compoundParent;\n\n if (data.type === 'compound' && (! component._compoundParent || component === component._compoundParent)) {\n component._compoundParent = component;\n\n entity.forEach(this._addEachDescendant, component);\n } else if (data.type !== 'compound') {\n if (component._compoundParent && component === component._compoundParent) {\n entity.forEach(this.system.implementations.compound._updateEachDescendant, component);\n }\n\n if (! component.rigidbody) {\n component._compoundParent = null;\n var parent = entity.parent;\n while (parent) {\n if (parent.collision && parent.collision.type === 'compound') {\n component._compoundParent = parent.collision;\n break;\n }\n parent = parent.parent;\n }\n }\n }\n\n if (component._compoundParent) {\n if (component !== component._compoundParent) {\n if (firstCompoundChild && component._compoundParent.shape.getNumChildShapes() === 0) {\n this.system.recreatePhysicalShapes(component._compoundParent);\n } else {\n this.system.updateCompoundChildTransform(entity);\n\n if (component._compoundParent.entity.rigidbody)\n component._compoundParent.entity.rigidbody.activate();\n }\n }\n }\n\n if (entity.rigidbody) {\n entity.rigidbody.disableSimulation();\n entity.rigidbody.createBody();\n\n if (entity.enabled && entity.rigidbody.enabled) {\n entity.rigidbody.enableSimulation();\n }\n } else if (! component._compoundParent) {\n if (! entity.trigger) {\n entity.trigger = new Trigger(this.system.app, component, data);\n } else {\n entity.trigger.initialize(data);\n }\n }\n }\n }", "reset() {\n\t\tvar objects = this._vptGData.vptBundle.objects;\n\t\twhile (objects.length !== 0) {\n\t\t\tvar object = objects.pop();\n\t\t\tobject.switchRenderModes(false);\n\t\t\tvar tex = object.material.maps[0];\n\t\t\tthis._glManager._textureManager.clearTexture(tex);\n\t\t\tif (object._volumeTexture)\n\t\t\t\tthis._gl.deleteTexture(object._volumeTexture);\n\t\t\tif (object._environmentTexture)\n\t\t\t\tthis._gl.deleteTexture(object._environmentTexture);\n\t\t}\n\t\tthis._vptGData.vptBundle.mccStatus = false;\n\t\tthis._vptGData.vptBundle.resetBuffers = true;\n\t\t//this._vptGData._updateUIsidebar();\n\t}", "function dispose() {\n delete filters[dimensionName];\n delete datasets[dimensionName];\n }", "destroy() {\n this.shape = null;\n this.holes.length = 0;\n this.holes = null;\n this.points.length = 0;\n this.points = null;\n this.lineStyle = null;\n this.fillStyle = null;\n }", "destroy () {\n\n this.particles.forEach((particle) => {\n\n this.emit('particle.destroy', particle)\n })\n\n this.recycleBin = []\n this.particles = []\n }", "cleanup() {\n debug(\"cleanup\");\n this.subs.forEach((subDestroy) => subDestroy());\n this.subs.length = 0;\n this.decoder.destroy();\n }", "cleanUp() {\n // clear activeEnemies\n this.activeEnemies.forEach(function(enemy) {\n enemy.cleanUp();\n });\n // clear active players\n this.activeObjects.forEach(function(object) {\n object.cleanUp();\n });\n // stop game loop\n this.animation.forEach(function(frame,index) {\n cancelAnimationFrame(frame);\n });\n }", "destroy() {\n super.destroy(); // xeokit.Object\n this._putDrawRenderers();\n this._putPickRenderers();\n this._putOcclusionRenderer();\n this.scene._renderer.putPickID(this._state.pickID); // TODO: somehow puch this down into xeokit framework?\n if (this._isObject) {\n this.scene._deregisterObject(this);\n if (this._visible) {\n this.scene._objectVisibilityUpdated(this, false);\n }\n if (this._xrayed) {\n this.scene._objectXRayedUpdated(this, false);\n }\n if (this._selected) {\n this.scene._objectSelectedUpdated(this, false);\n }\n if (this._highlighted) {\n this.scene._objectHighlightedUpdated(this, false);\n }\n }\n if (this._isModel) {\n this.scene._deregisterModel(this);\n }\n this.glRedraw();\n }", "cleanup() {\n debug(\"cleanup\");\n const subsLength = this.subs.length;\n for (let i = 0; i < subsLength; i++) {\n const sub = this.subs.shift();\n sub.destroy();\n }\n this.decoder.destroy();\n }", "cleanup() {\n this.subs.forEach((subDestroy) => subDestroy());\n this.subs.length = 0;\n this.decoder.destroy();\n }", "freeExternal(texture) {\n // Bitmap.removeFromCache(texture);\n // texture.destroy(texture.baseTexture != null);\n }", "cleanup() {\n debug(\"cleanup\");\n this.subs.forEach(subDestroy => subDestroy());\n this.subs.length = 0;\n this.decoder.destroy();\n }", "_dispose() {\n\n delete window.FlowUI['_loaders'][this.id];\n\n }", "function remove_reduction_objects_from_canvas() {\n var objects = canvas.getObjects()\n $.each(objects,function(i,v){\n if(v.type=='reduc_rect') {\n canvas.remove(objects[i]);\n }\n });\n \n }", "cleanup() {\n debug(\"cleanup\");\n this.subs.forEach((subDestroy) => subDestroy());\n this.subs.length = 0;\n this.decoder.destroy();\n }", "cleanup() {\n debug(\"cleanup\");\n this.subs.forEach((subDestroy) => subDestroy());\n this.subs.length = 0;\n this.decoder.destroy();\n }", "dispose() {\n this._isDisposed = true;\n for (const d of this._disposables) {\n d.dispose();\n }\n this._disposables.length = 0;\n }", "dispose() {\n if (this.iterations_ != null) {\n dispose(this.iterations_);\n }\n }", "dispose() {\n for (const child of this.children) {\n child.dispose();\n }\n\n // remove from parent\n this.parent.children._removeComponent(this);\n\n // also dispose on client\n return this._remoteInternal.dispose();\n }", "clearFromeScene()\r\n {\r\n for (var i=0;i<this.segMeshes.length;i++)\r\n {\r\n scene.remove(this.segMeshes[i]);\r\n }\r\n //alert(this.leafMeshes.length + \" \" +this.segMeshes.length);\r\n for (var i=0;i<this.leafMeshes.length;i++)\r\n {\r\n //alert(\"hm\");\r\n scene.remove(this.leafMeshes[i]);\r\n }\r\n }", "disposeLayerPrimitives_() {\n if (this.csContext) {\n // clean up layer listeners\n events.unlisten(this.layer, 'change:visible', this.onLayerVisibility_, this);\n events.unlisten(this.layer, 'change:opacity', this.onLayerOpacity_, this);\n events.unlisten(this.layer, EventType.PROPERTYCHANGE, this.onLayerPropertyChange_, this);\n\n // clean up source listeners\n events.unlisten(this.source, VectorEventType.CHANGEFEATURE, this.onChangeFeature_, this);\n events.unlisten(this.source, EventType.PROPERTYCHANGE, this.onSourcePropertyChange_, this);\n\n // sources don't listen to these events (see above)\n if (!(this.source instanceof VectorSource)) {\n events.unlisten(this.source, VectorEventType.ADDFEATURE, this.onAddFeature_, this);\n events.unlisten(this.source, VectorEventType.REMOVEFEATURE, this.onRemoveFeature_, this);\n events.unlisten(this.source, VectorEventType.CLEAR, this.clearFeatures_, this);\n }\n\n this.csContext.dispose();\n this.csContext = null;\n\n dispatcher.getInstance().dispatchEvent(MapEvent.GL_REPAINT);\n }\n }", "function finishedRenderingComponent_() {\n\trenderingComponents_.pop();\n\tif (renderingComponents_.length === 0) {\n\t\t(0, _unused.disposeUnused)();\n\t}\n}", "function end_explosion() {\n pac_explosion=false;\n m.render();\n}", "clear() {\n this.myScene.remove(this.threeObject);\n this.threeObject = null;\n }", "clearGeometry() {\n this.geometries = [];\n this.texGeometries = [];\n this.render();\n }", "destructor () {\n console.log('Solid sketch deleted!')\n }", "function didCleanupTree(env, morph, destroySelf) {}", "function deep_dispose() {\n if (instrument != undefined && instrument != null) {\n instrument.dispose()\n instrument = null\n }\n }", "finalize() {\n }", "finalize() {\n }", "finalize() {\n }", "finalize() {\n }", "run() {\n var tm = this.renderer.texture;\n var managedTextures = tm.managedTextures;\n var wasRemoved = false;\n for (var i = 0; i < managedTextures.length; i++) {\n var texture = managedTextures[i];\n // only supports non generated textures at the moment!\n if (!texture.framebuffer && this.count - texture.touched > this.maxIdle) {\n tm.destroyTexture(texture, true);\n managedTextures[i] = null;\n wasRemoved = true;\n }\n }\n if (wasRemoved) {\n var j = 0;\n for (var i$1 = 0; i$1 < managedTextures.length; i$1++) {\n if (managedTextures[i$1] !== null) {\n managedTextures[j++] = managedTextures[i$1];\n }\n }\n managedTextures.length = j;\n }\n }", "_cleanup() {\n this.readable = false;\n delete this._current;\n delete this._waiting;\n this._openQueue.die();\n\n this._queue.forEach((data) => {\n data.cleanup();\n });\n this._queue = [];\n }", "dispose() {}", "dispose() {}", "dispose() {}", "dispose() {}", "dispose() {}", "_destroy() {\n const stack = [];\n if (this._root) {\n stack.push(this._root);\n }\n while (stack.length > 0) {\n for (const child of tile.children) {\n stack.push(child);\n }\n const tile = stack.pop();\n\n // TODO - Use this._destroyTile(tile); ?\n tile.destroy();\n }\n this._root = null;\n }", "gc() {\n // clear all arrays\n this.animation=null;\n this.keys=null;\n // clear variables\n this.generate=null;\n this.move=null;\n }", "destroy(astID) {\n\t\t// Remove the asteroid from data.asteroidsData and the canvas\n\t\tif (astID >= 0 && data.asteroidsData.length > 0 && data.canvas.asteroids.length > 0) {\n\t\t\tdata.asteroidsData.splice(astID, 1)\n\t\t\tdata.canvas.asteroids.splice(astID, 1)\n\n\t\t\t//Also remove the relative laser, if it was mining\n\t\t\tfor (let i = 0; i < data.canvas.lasers.length; i++) {\n\t\t\t\tif (data.canvas.lasers[i].uniqueID == this.uniqueID) {\n\t\t\t\t\tdata.canvas.lasers = []\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t} else {\n\t\t\t//TODO Throw error\n\t\t}\n\n\n\t\t// Animate explosion TODO\n\t\t// ...\n\n\t\t// Remove all relative pointers so CG can clean the memory\n\t}", "function editorDestroyAllMapObjects() {\n edPlayerStart.destroy();\n edPlayerStart = null;\n edExit.destroy();\n edExit = null;\n edTiles.forEach(o => {\n o.forEach(s => s.destroy());\n });\n edTiles = [];\n edEnemies.forEach(o => { if (o) o.destroy(); });\n edEnemies = [];\n edPickups.forEach(o => { if (o) o.destroy(); });\n edPickups = [];\n edSigns.forEach(o => { if (o) o.destroy(); });\n edSigns = [];\n}", "dispose() {\n // this.disposeRunner.run(this, false);\n this.disposeRunner.run(this, false);\n }", "dispose() {\n // this.disposeRunner.run(this, false);\n this.disposeRunner.run(this, false);\n }", "function destroyTextures () {\n\t for (var i = 0; i < numTexUnits; ++i) {\n\t gl.activeTexture(GL_TEXTURE0 + i);\n\t gl.bindTexture(GL_TEXTURE_2D, null);\n\t textureUnits[i] = null;\n\t }\n\t values(textureSet).forEach(destroy);\n\t\n\t stats.cubeCount = 0;\n\t stats.textureCount = 0;\n\t }", "function willCleanupTree(env, morph, destroySelf) {}", "destroy()\n {\n this.#gameObject = null;\n }" ]
[ "0.78554034", "0.7314414", "0.72481173", "0.6943704", "0.69227177", "0.6670877", "0.65561336", "0.65320575", "0.64877605", "0.64852387", "0.6392635", "0.6387809", "0.6384026", "0.63688844", "0.6366915", "0.63023466", "0.6242657", "0.6163794", "0.6153872", "0.614207", "0.61085", "0.6082298", "0.6036332", "0.60137045", "0.6013055", "0.59972626", "0.5982777", "0.59791356", "0.59791356", "0.59791356", "0.5976909", "0.5976583", "0.5973474", "0.5970436", "0.59694093", "0.5960514", "0.59384084", "0.5929894", "0.5923146", "0.5923106", "0.5913387", "0.5910952", "0.5910307", "0.5889766", "0.5875221", "0.5871982", "0.5868943", "0.5865169", "0.58614177", "0.58612424", "0.58612424", "0.58612424", "0.58569974", "0.585423", "0.5832237", "0.5830702", "0.5818159", "0.5798825", "0.5794267", "0.5793519", "0.57611835", "0.5760465", "0.5741958", "0.5727302", "0.57225364", "0.57158566", "0.57111573", "0.57111573", "0.570422", "0.5699418", "0.5697259", "0.5690208", "0.568978", "0.5686217", "0.56833637", "0.56822854", "0.5680763", "0.5669292", "0.5655402", "0.565308", "0.5652339", "0.5652339", "0.5652339", "0.5652339", "0.56492496", "0.5633969", "0.5631165", "0.5631165", "0.5631165", "0.5631165", "0.5631165", "0.5628006", "0.56252444", "0.5624594", "0.5619979", "0.56130016", "0.56130016", "0.5611634", "0.56093866", "0.56091446" ]
0.7056994
3
TODO: layers; maintaining a seperate selection set is a pain, would much rather just store state changes on scene entities directly and either compound, override, or just sepeately maintain the set of static stuff and pending changes so that they could be more efficiently redrawn as changes occurred.
constructor ({ colorScheme = null, onAsyncLoadFinished } = {}) { this.scene = new Scene(); this.clearColor = defaultTheme.background; this.textureLoader = new TextureLoader(); this.sceneEntityMap = {}; this.maintainPointRefCounts = true; this.onAsyncLoadFinished = onAsyncLoadFinished ? onAsyncLoadFinished : () => {}; this._latestFloorState = null; this._latestCombinedFloorEntities = null; this._latestSelectionSet = null; this._numRemoves = 0; this._latestColorScheme = null; [this.materials, this.matLoadPromise] = generateMaterials(1); this._font = null; this._fontMaterial = null; this._idsPendingFontLoad = []; if (colorScheme) { this.syncColorScheme(colorScheme); } this._pointRadius = 4; this._lineThicknessDefaults = getLineThicknessDefaults(this.materials); this._pointRefCounts = {}; this.loadTextAssets(); this.matLoadPromise.then(() => this.onAsyncLoadFinished()); this._snapGuides = null; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "sync_vdata_selstate(ctx) {\r\n for (let k in this.vertex_animdata) {\r\n let vd = this.vertex_animdata[k];\r\n \r\n if (!vd) {\r\n continue;\r\n }\r\n \r\n vd.animflag &= ~VDAnimFlags.OWNER_IS_EDITABLE;\r\n }\r\n\r\n for (let i=0; i<2; i++) {\r\n let list = i ? this.spline.handles : this.spline.verts;\r\n\r\n for (let v of list.selected.editable(ctx)) {\r\n let vd = this.vertex_animdata[v.eid];\r\n \r\n if (!vd) {\r\n continue;\r\n }\r\n \r\n vd.animflag |= VDAnimFlags.OWNER_IS_EDITABLE;\r\n }\r\n }\r\n }", "updateSelectLocalEvent() {\n this.updateSelectLocal(this.menuView.loadView.existingSceneSelect);\n this.updateSelectLocal(this.menuView.saveView.existingSceneSelect);\n }", "function updateAdditionalHighlight() {\n let entsAdd = []; // list of entities units to be highlighted\n let entsRemove = [];\n let highlighted = g_Selection.toList();\n for (let ent in g_Selection.highlighted)\n highlighted.push(g_Selection.highlighted[ent]);\n\n if (g_ShowGuarding)\n // flag the guarding entities to add in this additional highlight\n for (let sel in g_Selection.selected) {\n let state = GetEntityState(g_Selection.selected[sel]);\n if (!state.guard || !state.guard.entities.length) continue;\n\n for (let ent of state.guard.entities)\n if (highlighted.indexOf(ent) == -1 && entsAdd.indexOf(ent) == -1)\n entsAdd.push(ent);\n }\n\n if (g_ShowGuarded)\n // flag the guarded entities to add in this additional highlight\n for (let sel in g_Selection.selected) {\n let state = GetEntityState(g_Selection.selected[sel]);\n if (!state.unitAI || !state.unitAI.isGuarding) continue;\n let ent = state.unitAI.isGuarding;\n if (highlighted.indexOf(ent) == -1 && entsAdd.indexOf(ent) == -1)\n entsAdd.push(ent);\n }\n\n // flag the entities to remove (from the previously added) from this additional highlight\n for (let ent of g_AdditionalHighlight)\n if (\n highlighted.indexOf(ent) == -1 &&\n entsAdd.indexOf(ent) == -1 &&\n entsRemove.indexOf(ent) == -1\n )\n entsRemove.push(ent);\n\n _setHighlight(entsAdd, g_HighlightedAlpha, true);\n _setHighlight(entsRemove, 0, false);\n g_AdditionalHighlight = entsAdd;\n}", "_updateSelections () {\n if (!this.ready || this.destroyed) return\n\n queueMicrotask(() => {\n this._gcSelections()\n })\n this._updateInterest()\n this._update()\n }", "_updateSelections () {\n if (!this.ready || this.destroyed) return\n\n process.nextTick(() => {\n this._gcSelections()\n })\n this._updateInterest()\n this._update()\n }", "_updateSelections () {\n if (!this.ready || this.destroyed) return\n\n process.nextTick(() => {\n this._gcSelections()\n })\n this._updateInterest()\n this._update()\n }", "sync_options_and_states(update_states) {\n var that = this;\n var current = that.current;\n var options = that.options;\n \n if (update_states) {\n current.pos = options.pos || current.pos;\n current.data_set = options.data_set || current.data_set;\n current.selection.low_pass_threshold = +options.low_pass || current.selection.low_pass_threshold;\n current.selection.threshold = +options.threshold || current.selection.threshold;\n current.source = options.source || current.source;\n\n var brush_string = options.brush;\n if (brush_string && brush_string.length > 0) {\n current.brush_extent = brush_string.split(',').map(d => +d);\n }\n\n var zero_padding = options.padding;\n if (zero_padding && zero_padding.length > 0) {\n var tmp = zero_padding.split(',').map(d => +d);\n current.zero_left = tmp[0];\n current.zero_right = tmp[1];\n }\n\n\n var cell_string = options.cells;\n if (cell_string && cell_string.length > 0) {\n current.selection.cells = cell_string.split(',').map(d => +d);\n\n }\n\n var ex_cell_string = options.ex_cell;\n if (ex_cell_string && ex_cell_string.length > 0) {\n that.current.selection.excluded_cells = ex_cell_string.split(',').map(d => +d)\n }\n\n\n } else {\n // TODO: maybe\n }\n\n }", "_initializeSelectionEffects() {\n // Calculate the geometry of the shapes used for the selection effects\n var outerBorderWidth = this.isSelected()\n ? DvtChartSelectableRectangularPolygon.OUTER_BORDER_WIDTH\n : DvtChartSelectableRectangularPolygon.OUTER_BORDER_WIDTH_HOVER;\n var outerChildPoints = this._createPointsArray(outerBorderWidth);\n var innerChildPoints = this._createPointsArray(\n outerBorderWidth + DvtChartSelectableRectangularPolygon.INNER_BORDER_WIDTH\n );\n\n // Just update the geometries if already initialized\n if (this.OuterChild) {\n this.OuterChild.setPoints(outerChildPoints);\n this.InnerChild.setPoints(innerChildPoints);\n return;\n }\n\n this.OuterChild = new dvt.Polygon(this.getCtx(), outerChildPoints);\n this.OuterChild.setInvisibleFill();\n this.OuterChild.setMouseEnabled(true);\n this.addChild(this.OuterChild);\n\n this.InnerChild = new dvt.Polygon(this.getCtx(), innerChildPoints);\n this.InnerChild.setInvisibleFill();\n this.InnerChild.setMouseEnabled(true);\n this.addChild(this.InnerChild);\n }", "function updateAllTheGeometry() {\n\n if (config.enableSelection) {\n\n toggleVisibility(HaloBranch,config.showPaths, 0.5);\n toggleVisibility(HaloSelect,config.showHalos, 0.05);\n } else{\n displayHaloData();\n }\n\n\n}", "changeByRange(f) {\n let sel = this.selection;\n let result1 = f(sel.ranges[0]);\n let changes = this.changes(result1.changes), ranges = [result1.range];\n let effects = asArray(result1.effects);\n for (let i = 1; i < sel.ranges.length; i++) {\n let result = f(sel.ranges[i]);\n let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes);\n for (let j = 0; j < i; j++)\n ranges[j] = ranges[j].map(newMapped);\n let mapBy = changes.mapDesc(newChanges, true);\n ranges.push(result.range.map(mapBy));\n changes = changes.compose(newMapped);\n effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray(result.effects), mapBy));\n }\n return {\n changes,\n selection: EditorSelection.create(ranges, sel.mainIndex),\n effects\n };\n }", "function updateLocalSelections(selectAll) {\n\t\tupdateGraphicsHelper(false, true, false);\n\t}", "componentDidUpdate() {\n switch (Actions.currentScene) {\n case (Actions.Frontpage.name):\n this.setState({ frontSelect: true, obsSelect: false });\n break;\n case (Actions.Observation.name):\n this.setState({ frontSelect: false, obsSelect: true });\n break;\n }\n }", "function sync_selected(evt) {\n\t\tvar nodes_selected = [];\n\t\tvar edges_selected = [];\n\t\tvar eles = g.elements(\"node:selected\");\n\t\t$(document).trigger(\"edit_mode\");\n\t\t$.each(eles, function(i, ele){\n\t\t\t// update the view information (position etc.)\n\t\t\tvar node_data = ele.data();\n\t\t\tvar pos = ele.renderedPosition();\n\t\t\tif (!node_data.view) {\n\t\t\t\tnode_data.view = {};\n\t\t\t}\n\t\t\tnode_data.view.position = pos;\n\t\t\tnodes_selected.push(node_data);\n\t\t});\n\t\t$('#node_editor').trigger(\"update_form\", [nodes_selected]);\n\t\t\n\t\t// next handle edges\n\t\teles = g.elements(\"edge:selected\");\n\t\t$.each(eles, function(i, ele){\n\t\t\tvar edge_data = ele.data();\n\t\t\tedges_selected.push(edge_data);\n\t\t});\n\t\t$(\"#edge_editor\").trigger(\"update_form\", [edges_selected]);\n\t}", "save() {\n // // Update the global selection before saving anything.\n this.surface.editor.selection.update();\n Object.assign(this.saved, this.state);\n }", "function SceneSelect (gameEngine) {\n this.ctx = gameEngine.ctx;\n this.gameEngine = gameEngine;\n var portrait0 = AM.getAsset(\"./sprites/background0/tmp-0.gif\");\n var portrait1 = AM.getAsset(\"./sprites/background1/tmp-0.gif\");\n var portrait2 = AM.getAsset(\"./sprites/background2/tmp-0.gif\");\n var portrait3 = AM.getAsset(\"./sprites/background3/tmp-0.gif\");\n this.player1Ready = false;\n this.portraitWidth = 90;\n this.titleHeight = 100;\n this.padding = 10;\n this.shadowBlur = 2;\n this.shadowUp = false;\n this.entities = [this];\n this.selections = [];\n this.selections.push({name: \"Sunset\", portrait: portrait0, x: 0, y:0});\n this.selections.push({name: \"Ruins\", portrait: portrait1, x: 0, y: 0});\n this.selections.push({name: \"Under the Sea\", portrait: portrait2, x: 0, y:0});\n this.selections.push({name: \"Dark Fortress\", portrait: portrait3, x: 0, y: 0});\n\n this.selector1 = {x: 0, y: 0, color: \"blue\", index: 0};\n\n for (var i = 0; i < this.selections.length; i++) {\n this.selections[i].x = 200 + (this.portraitWidth + this.padding)* i;\n this.selections[i].y = this.titleHeight + 200;\n }\n}", "_initializeSelectionEffects() {\n // Calculate the geometry of the shapes used for the selection effects\n var isRedwood = this.getCtx().getThemeBehavior() === 'redwood';\n var outerBorderWidth =\n this.isSelected() || isRedwood\n ? DvtChartSelectableWedge._OUTER_BORDER_WIDTH\n : DvtChartSelectableWedge._OUTER_BORDER_WIDTH_HOVER;\n var outerChildCmds = this._makeWedgePath(outerBorderWidth);\n var innerChildCmds = this._makeWedgePath(\n outerBorderWidth + DvtChartSelectableWedge._INNER_BORDER_WIDTH\n );\n\n // Just update the geometries if already initialized\n if (this.OuterChild) {\n this.OuterChild.setCmds(outerChildCmds);\n this.InnerChild.setCmds(innerChildCmds);\n return;\n }\n\n this.OuterChild = new dvt.Path(this.getCtx(), outerChildCmds);\n this.OuterChild.setInvisibleFill();\n this.OuterChild.setMouseEnabled(true);\n this.addChild(this.OuterChild);\n\n this.InnerChild = new dvt.Path(this.getCtx(), innerChildCmds);\n this.InnerChild.setInvisibleFill();\n this.InnerChild.setMouseEnabled(true);\n this.addChild(this.InnerChild);\n }", "function displaySelections(){\r\n //defaults\r\n Session.set('breaksOption','origOption');\r\n Session.set('highlightElement','line');\r\n Session.set('boldElement','boldLine');\r\n Session.set('syllablesVisible','true');\r\n Session.set('stressVisible', 'true');\r\n \r\n var selectionsCursor = Selections.find({poem_id:Session.get('currentPoem')});\r\n selectionsCursor.observe({\r\n //when something is added to the Selections Collection\r\n added: function (selection, beforeIndex) {\r\n var location = selection.location;\r\n var styleID = selection.style_id;\r\n var style = Styles.find({_id:styleID}).fetch();\r\n //used to catch errors\r\n if (style.length > 0){\r\n var layerNodeID = style[0].layer_id;\r\n var layerID = Layers.findOne({poem_id: Session.get('currentPoem'), id: layerNodeID})._id;\r\n //if selection is from highlighting style/layer\r\n if ((style[0].background_color !== null)&&(typeof style[0].background_color !== \"undefined\")) {\r\n var rgba = style[0].background_color;\r\n var lastIndex = rgba.lastIndexOf(\",\");\r\n var substring = rgba.substr(0, lastIndex+1);\r\n //check opacity of layer that made the selection\r\n var curRGBA = substring+' ';\r\n var op = Layers.findOne(layerID).opacity;\r\n var newRGBA = curRGBA+op+\")\";\r\n console.log(newRGBA);\r\n $(\".\"+location).css(\r\n {\r\n \"background\": newRGBA\r\n });\r\n }\r\n //if selection is from bolding style/layer\r\n if ((style[0].font_color !== null)&&(typeof style[0].font_color !== \"undefined\")) {\r\n var substring = style[0].font_color;\r\n $(\".\"+location).css(\r\n {\r\n \"color\": substring\r\n }\r\n );\r\n }\r\n //if selection is from bolding style/layer\r\n if ((style[0].bold !== null)&&(typeof style[0].bold !== \"undefined\")) {\r\n var substring = style[0].bold;\r\n if (substring){\r\n $(\".\"+location).css(\r\n {\r\n \"font-weight\": \"bold\"\r\n }\r\n );\r\n $(\".\"+location).addClass(\"bold\"+style[0].font_color);\r\n }\r\n }\r\n //if selection is from stressing style/layer\r\n if((style[0].verticalAlign !== null)&&(typeof style[0].verticalAlign !== \"undefined\")){\r\n location = location.substr(1);\r\n if (Session.get('stressVisible')==\"true\"){\r\n $('.'+location).css('vertical-align','super');\r\n }\r\n $('.'+location).addClass('stressStyle');\r\n }\r\n }\r\n },\r\n //when something is removed from the Selections Collection\r\n removed: function (selection, beforeIndex) {\r\n var location = selection.location;\r\n var styleID = selection.style_id;\r\n var curLayerNodeID = selection.layerNode_id;\r\n var style = Styles.find({_id:styleID}).fetch();\r\n console.log(style);\r\n //used to catch errors\r\n if (style.length > 0){\r\n //if removed is highlighting\r\n if ((style[0].background_color !== undefined)) {\r\n //must go through all selections that may have colored line/word/character to check and\r\n //see if after one background-color is turned off, there is another (from another layer)\r\n //still coloring that line/word/character\r\n var curRGBA = \"transparent\";\r\n var allSelections = Selections.find({poem_id: Session.get('currentPoem'), location: location}).fetch();\r\n console.log(allSelections);\r\n _.each(allSelections, function(sel){\r\n var piece = sel.style_id; \r\n var otherStyle = Styles.findOne({_id: piece});\r\n if ((otherStyle !== undefined)){\r\n if ((otherStyle.background_color !== undefined)){\r\n op = Layers.findOne({id:otherStyle.layer_id}).opacity;\r\n var rgba = otherStyle.background_color;\r\n var lastIndex = rgba.lastIndexOf(\",\");\r\n var substring = rgba.substr(0, lastIndex+1);\r\n //check opacity of layer that made the selection\r\n curRGBA = substring;\r\n var newRGBA = curRGBA+op+\")\";\r\n if (otherStyle.layer_id != curLayerNodeID){\r\n curRGBA = newRGBA;\r\n console.log(curRGBA);\r\n }\r\n }\r\n }\r\n });\r\n $(\".\"+location).css(\r\n {\r\n \"background-color\": curRGBA\r\n }\r\n );\r\n\r\n }\r\n //if removed selection is bolding\r\n if ((style[0].font_color !== null)&&(typeof style[0].font_color !== \"undefined\")) {\r\n $(\".\"+location).css(\r\n {\r\n \"color\": \"black\"\r\n }\r\n );\r\n $(\".\"+location).removeClass(\"bold\"+style[0].font_color);\r\n }\r\n //if removed selection is bolding\r\n if ((style[0].bold !== null)&&(typeof style[0].bold !== \"undefined\")) {\r\n //so that word can be bolded if line is bolded\r\n $(\".\"+location).css(\"font-weight\",\"\");\r\n $(\".\"+location).css(\"color\",\"\");\r\n }\r\n //if removed selection is stressing\r\n if((style[0].verticalAlign !== null)&&(typeof style[0].verticalAlign !== \"undefined\")){\r\n location = location.substr(1);\r\n $('.'+location).css('vertical-align','baseline');\r\n $('.'+location).removeClass('stressStyle');\r\n }\r\n }\r\n }\r\n });\r\n //handles additions/removals from SyllableMarkers Collection\r\n var syllablesCursor = SyllableMarkers.find({poem_id:Session.get('currentPoem')});\r\n syllablesCursor.observe({\r\n added: function (selection, beforeIndex) {\r\n var location = selection.location;\r\n if (Session.get('syllablesVisible')==\"true\"){\r\n $(\".\"+location).css(\r\n {\r\n \"border-left\": \"2px solid black\"\r\n });\r\n }\r\n $(\".\"+location).addClass('syllableStyle');\r\n //updates natural syllables\r\n var lineSpan = $('#'+location).closest('.line');\r\n var countSpan = $(lineSpan).find('.lineCount');\r\n var wordCount=$(lineSpan).find('.word').length;\r\n var sylCount=0;\r\n $(lineSpan).find('.letter').each(function(){\r\n if ($(this).hasClass(\"syllableStyle\")){\r\n sylCount++; \r\n }\r\n })\r\n $(countSpan).text(wordCount+sylCount);\r\n //updates other versions' syllable markers \r\n var lineSpanArray = $('.'+location).closest('.unnaturalLine');\r\n var countSpan1 = $(lineSpanArray[0]).find('.lineCount');\r\n var countSpan2 = $(lineSpanArray[1]).find('.lineCount');\r\n var wordArray1=$(lineSpanArray[0]).find('.word');\r\n var wordArray2=$(lineSpanArray[1]).find('.word');\r\n var wordCount1 = 0;\r\n var wordCount2 = 0;\r\n //don't count the awkward spaces created by new lines\r\n _.each(wordArray1, function(elem) {\r\n if ($(elem).text().trim() == \"\"){\r\n }\r\n else{\r\n wordCount1++;\r\n }\r\n });\r\n _.each(wordArray2, function(elem) {\r\n if ($(elem).text().trim() == \"\"){\r\n }\r\n else{\r\n wordCount2++;\r\n }\r\n });\r\n var sylCount1=0;\r\n var sylCount2=0; \r\n $(lineSpanArray[0]).find('.letter').each(function(){\r\n if ($(this).hasClass(\"syllableStyle\")){\r\n sylCount1++; \r\n }\r\n });\r\n $(lineSpanArray[1]).find('.letter').each(function(){\r\n if ($(this).hasClass(\"syllableStyle\")){\r\n sylCount2++; \r\n }\r\n });\r\n $(countSpan1).text(wordCount1+sylCount1);\r\n $(countSpan2).text(wordCount2+sylCount2);\r\n if ($('.syllablesGrid').data('gridded')===true){\r\n grid();\r\n grid();\r\n }\r\n },\r\n removed: function (selection, beforeIndex) {\r\n var location = selection.location;\r\n $(\".\"+location).css(\r\n {\r\n \"border-left\": \"none\"\r\n });\r\n $(\".\"+location).removeClass('syllableStyle');\r\n var lineSpan = $('#'+location).closest('.line');\r\n var countSpan = $(lineSpan).find('.lineCount');\r\n var wordCount=$(lineSpan).find('.word').length;\r\n var sylCount=0;\r\n $(lineSpan).find('.letter').each(function(){\r\n console.log($(this).css(\"border-left\"));\r\n if ($(this).hasClass(\"syllableStyle\")){\r\n sylCount++; \r\n }\r\n })\r\n $(countSpan).text(wordCount+sylCount);\r\n //updates other versions' syllable markers \r\n var lineSpanArray = $('.'+location).closest('.unnaturalLine');\r\n var countSpan1 = $(lineSpanArray[0]).find('.lineCount');\r\n var countSpan2 = $(lineSpanArray[1]).find('.lineCount');\r\n var wordArray1=$(lineSpanArray[0]).find('.word');\r\n var wordArray2=$(lineSpanArray[1]).find('.word');\r\n var wordCount1 = 0;\r\n var wordCount2 = 0;\r\n //don't count the awkward spaces created by new lines\r\n _.each(wordArray1, function(elem) {\r\n if ($(elem).text().trim() == \"\"){\r\n }\r\n else{\r\n wordCount1++;\r\n }\r\n });\r\n _.each(wordArray2, function(elem) {\r\n if ($(elem).text().trim() == \"\"){\r\n }\r\n else{\r\n wordCount2++;\r\n }\r\n });\r\n var sylCount1=0;\r\n var sylCount2=0; \r\n $(lineSpanArray[0]).find('.letter').each(function(){\r\n if ($(this).hasClass(\"syllableStyle\")){\r\n sylCount1++; \r\n }\r\n });\r\n $(lineSpanArray[1]).find('.letter').each(function(){\r\n if ($(this).hasClass(\"syllableStyle\")){\r\n sylCount2++; \r\n }\r\n });\r\n $(countSpan1).text(wordCount1+sylCount1);\r\n $(countSpan2).text(wordCount2+sylCount2);\r\n if ($('.syllablesGrid').data('gridded')===true){\r\n grid();\r\n grid();\r\n }\r\n },\r\n });\r\n //handles changes from Layers Collection\r\n var layersCursor = Layers.find({poem_id:Session.get('currentPoem')});\r\n layersCursor.observe({ \r\n added: function (selection, beforeIndex) {\r\n var sessionObj = Session.get(\"layersArray\");\r\n //if layer just created, user probably wants to use it, so default \"visible\"\r\n sessionObj[selection._id] = \"visible\";\r\n Session.set(\"layersArray\", sessionObj);\r\n },\r\n });\r\n\r\n}", "function changeStateForSelection(selection) {\n const temp = statesBody.select(\"#temp\");\n\n const $selected = $body.querySelector(\"div.selected\");\n const stateNew = +$selected.dataset.id;\n const color = pack.states[stateNew].color || \"#ffffff\";\n\n selection.forEach(function (i) {\n const exists = temp.select(\"polygon[data-cell='\" + i + \"']\");\n const stateOld = exists.size() ? +exists.attr(\"data-state\") : pack.cells.state[i];\n if (stateNew === stateOld) return;\n if (i === pack.states[stateOld].center) return;\n\n // change of append new element\n if (exists.size()) exists.attr(\"data-state\", stateNew).attr(\"fill\", color).attr(\"stroke\", color);\n else\n temp\n .append(\"polygon\")\n .attr(\"data-cell\", i)\n .attr(\"data-state\", stateNew)\n .attr(\"points\", getPackPolygon(i))\n .attr(\"fill\", color)\n .attr(\"stroke\", color);\n });\n}", "init() {\n let printSelection = (s) => {\n if (s.selection.length==0) {\n this._selection = \"nothing selected\";\n this._emptySelection = true;\n }\n else if (s.selection.length==1) {\n this._selection = \"1 item selected\";\n this._emptySelection = false; \n }\n else {\n this._selection = s.selection.length + \" items selected\";\n this._emptySelection = false;\n }\n let count = selectedTriangles(s);\n if (count) {\n this._selection += `, ${ count } triangles selected.`;\n }\n }\n\n app.render.Scene.Get().selectionManager.selectionChanged(\"statusBar\",(s) => {\n printSelection(s);\n this.notifyStatusChanged();\n });\n\n app.render.Scene.Get().sceneChanged(\"statusBar\",() => {\n printSelection(app.render.Scene.Get().selectionManager);\n this.notifyStatusChanged();\n });\n\n app.render.Scene.Get().selectionController.gizmoUpdated(\"statusBar\",() => {\n printSelection(app.render.Scene.Get().selectionManager);\n this.notifyStatusChanged();\n });\n\n app.ui.Log.Get().logChanged(\"statusBar\",() => {\n this.notifyStatusChanged();\n });\n }", "applyChanges() {\n if (this.renderMode !== 'svg') return;\n this.model.selection.view.applyChanges();\n this.model.focus.timeline.activeFrames.forEach(frame => {\n frame.view.applyChanges();\n });\n }", "_setDefEditors() {\n var last = LocalStore.getLast(), all = LocalStore.getAll(), ln = all.length, selected = {};\n for (let i = 0; i < ln; i++) {\n let item = all[i];\n if (item.checked) {\n selected[item.timestamp] = item;\n }\n }\n this.setState({mainBlock: last, selected: selected});\n }", "_applyPendingSelection() {\n if (this._model !== this._globalModel) {\n this._globalModel.updateSelection(this._model.selection, this);\n }\n }", "_selectHandler(params) {\n var id = params[0], state = params[1], selected = this.state.selected;\n\n if (state === true) {\n if (!selected[id]) selected[id] = LocalStore.getById(id);\n } else {\n if (selected[id]) delete selected[id];\n }\n this.setState({mainBlock: LocalStore.getLast(), selected: selected});\n }", "_autoLoadState(state) {\n const that = this,\n selectedIndexes = [];\n\n for (let i = 0; i < that._menuItemsGroupsToExpand.length; i++) {\n that._menuItemsGroupsToExpand[i].set('expanded', false);\n }\n\n that._menuItemsGroupsToExpand = [];\n\n for (let i = 0; i < state.expanded.length; i++) {\n const originallyExpandedItem = that.getItem(state.expanded[i]);\n\n if (originallyExpandedItem) {\n that._menuItemsGroupsToExpand.push(originallyExpandedItem);\n }\n }\n\n if (that.filterable && state.filter) {\n that._applyFilter(state.filter);\n that.$.filterInput.value = state.filter;\n }\n\n for (let i = 0; i < state.selected.length; i++) {\n const originallySelectedItem = that.getItem(state.selected[i]);\n\n if (originallySelectedItem) {\n selectedIndexes.push(originallySelectedItem.path);\n }\n }\n\n that.selectedIndexes = selectedIndexes;\n }", "_updateTrackedSelection(buildHighlight) {\n var trackedSelection = this._computeTrackedSelection(buildHighlight);\n\n this.setState({\n trackedSelection\n });\n }", "update() {\n // When this is called, the selection is always inside the surface.\n this.state.inside = true;\n\n var range = this.docsel.getRangeAt(0);\n\n // 0. Check if the selection is inside a node and not in-between\n var startDirty = (range.startContainer === this.surface.dom),\n endDirty = (range.endContainer === this.surface.dom);\n if(startDirty || endDirty) {\n // Dirty solution: we reset the selection\n console.log(\"Dirty selection!\");\n\n // We try to find the nearest node\n let nodePos;\n if(endDirty)\n nodePos = range.endOffset === 0 ? 0 : range.endOffset - 1;\n\n else if(startDirty)\n nodePos = range.endOffset === 0 ? 0 : range.endOffset - 1;\n\n this.set(nodePos, 0);\n this.surface.editor.selection.update();\n return;\n }\n\n // 1. Duplicate the `docsel.isCollapsed`.\n this.state.caret = this.docsel.isCollapsed;\n\n // 2. Find in which nodes are the selection's start and end points\n var sid, eid;\n for(var i = 0; i < this.surface.nodes.length; i++) {\n if(this.surface.nodes[i].contains(range.startContainer)) {\n sid = i;\n if(this.state.caret)\n eid = sid;\n }\n\n // Only check if the selection is a range: if not, anchor == focus\n if(!this.state.caret &&\n this.surface.nodes[i].contains(range.endContainer))\n eid = i;\n\n // Short-circuit the loop if everything we wanted was found\n if(sid && eid)\n break;\n }\n\n // 3. Get the offsets.\n var sOffset = this.surface.nodes[sid].boundaryPointToOffset(\n range.startContainer, range.startOffset\n );\n\n if(!this.state.caret) {\n var eOffset = this.surface.nodes[eid].boundaryPointToOffset(\n range.endContainer, range.endOffset\n );\n } else\n eOffset = sOffset;\n\n // 4. Store the values.\n this.state.startNodeIndex = sid;\n this.state.startOffset = sOffset;\n this.state.endNodeIndex = eid;\n this.state.endOffset = eOffset;\n\n // We re-compute this value because it is possible that even for a DOM\n // selection that is not collapsed, the resulting model offsets be the same.\n // In this case (which most of the time will be caused by an isolated node)\n // we want the model selection to be considered as collapsed.\n this.state.caret = (sOffset === eOffset && sid === eid);\n }", "updateState({oldProps, props, context, changeFlags}) {\n const attributeManager = this.getAttributeManager();\n if (changeFlags.dataChanged && attributeManager) {\n const {dataChanged} = changeFlags;\n if (Array.isArray(dataChanged)) {\n // is partial update\n for (const dataRange of dataChanged) {\n attributeManager.invalidateAll(dataRange);\n }\n } else {\n attributeManager.invalidateAll();\n }\n }\n\n const neededPickingBuffer = oldProps.highlightedObjectIndex >= 0 || oldProps.pickable;\n const needPickingBuffer = props.highlightedObjectIndex >= 0 || props.pickable;\n if (neededPickingBuffer !== needPickingBuffer && attributeManager) {\n const {pickingColors, instancePickingColors} = attributeManager.attributes;\n const pickingColorsAttribute = pickingColors || instancePickingColors;\n if (pickingColorsAttribute) {\n if (needPickingBuffer && pickingColorsAttribute.constant) {\n pickingColorsAttribute.constant = false;\n attributeManager.invalidate(pickingColorsAttribute.id);\n }\n if (!pickingColorsAttribute.value && !needPickingBuffer) {\n pickingColorsAttribute.constant = true;\n pickingColorsAttribute.value = [0, 0, 0];\n }\n }\n }\n }", "function SelectionChange() {}", "function SelectionChange() {}", "function SelectionChange() {}", "function SelectionChange() {}", "function updateSelectionState(piece) {\r\n // Coordinates of the piece and the rubberband in piece space:\r\n var rubbrX1P = rubberband.xP, rubbrY1P = rubberband.yP;\r\n var rubbrX2P = rubberband.xP + rubberband.widthP - 1;\r\n var rubbrY2P = rubberband.yP + rubberband.heightP - 1;\r\n var pieceX1P = piece.xP, pieceY1P = piece.yP;\r\n var pieceX2P = piece.xP + piece.widthP - 1;\r\n var pieceY2P = piece.yP + piece.heightP - 1;\r\n piece.selected =\r\n ((rubbrX1P <= pieceX1P && rubbrX2P >= pieceX1P) ||\r\n (rubbrX1P > pieceX1P && rubbrX1P <= pieceX2P)) &&\r\n ((rubbrY1P <= pieceY1P && rubbrY2P >= pieceY1P) ||\r\n (rubbrY1P > pieceY1P && rubbrY1P <= pieceY2P));\r\n }", "get newSelection() {\n return this.selection || this.startState.selection.map(this.changes);\n }", "_calculate_selection() {\n\n this.selection_model.geometry.vertices.forEach(v => v.z = 0);\n\n let bounding_box_height = 100; // FIXME: should be safe\n let bbox = new THREE.Box3().setFromObject(this.selection_model);\n\n // calculate all intersecting actors\n let hits = this.actors.filter(x => {\n\n let b = new THREE.Box3().setFromObject(x.mesh);\n\n // change the actors bounding boxes to go pretty high in the Z-axis\n // so the selection model will definitely intersect it\n b.expandByVector(new THREE.Vector3(0, 0, bounding_box_height));\n\n return bbox.isIntersectionBox(b);\n });\n\n this.emit(\"selection\", hits);\n\n }", "function datasetChangeHandler(evt){\n while(selections.list.length > 0) {\n selections.removeSelection(selections.list[0]);\n }\n selectedSets.forEach(function(d){d.active=false;});\n that.draw();\n }", "constructor() {\n this.state = null;\n this.selection = null;\n this.selectionContainer = null;\n }", "function updateSelection(editorState,selection,forceSelection){return EditorState.set(editorState,{selection:selection,forceSelection:forceSelection,nativelyRenderedContent:null,inlineStyleOverride:null});}", "function Basic_SetStates(theObject)\n{\n\t//get interface look\n\tvar interfaceLook = theObject.InterfaceLook;\n\t//need to recreate current state?\n\tif (!theObject.CurrentState)\n\t{\n\t\t//create it\n\t\ttheObject.CurrentState = {};\n\t}\n\t//create state arrays\n\ttheObject.BGColours = {};\n\ttheObject.FGColours = {};\n\ttheObject.BGImages = {};\n\ttheObject.BGImagesPos = {};\n\ttheObject.FGImages = {};\n\ttheObject.FGImagesPos = {};\n\ttheObject.GridImages = {};\n\t//set background colours\n\ttheObject.BGColours[__STATE_DEFAULT] = Get_Color(theObject.Properties[__NEMESIS_PROPERTY_BK_COLOR_DEFAULT], \"transparent\", interfaceLook);\n\ttheObject.BGColours[__STATE_SELECTED] = Get_Color(theObject.Properties[__NEMESIS_PROPERTY_BK_COLOR_SELECTED], \"#3399FF\", interfaceLook);\n\ttheObject.BGColours[__STATE_FOCUSED] = Get_Color(theObject.Properties[__NEMESIS_PROPERTY_BK_COLOR_FOCUSED], null, interfaceLook);\n\ttheObject.BGColours[__STATE_READONLY] = Get_Color(theObject.Properties[__NEMESIS_PROPERTY_BK_COLOR_READONLY], null, interfaceLook);\n\ttheObject.BGColours[__STATE_DISABLED] = Get_Color(theObject.Properties[__NEMESIS_PROPERTY_BK_COLOR_DISABLED], null, interfaceLook);\n\ttheObject.BGColours[__STATE_PRESSED] = Get_Color(theObject.Properties[__NEMESIS_PROPERTY_BK_COLOR_PRESSED], null, interfaceLook);\n\ttheObject.BGColours[__STATE_HOVERED] = Get_Color(theObject.Properties[__NEMESIS_PROPERTY_BK_COLOR_HOVERED], null, interfaceLook);\n\t//set foreground colours\n\ttheObject.FGColours[__STATE_DEFAULT] = Get_Color(theObject.Properties[__NEMESIS_PROPERTY_FG_COLOR_DEFAULT], \"black\", interfaceLook);\n\ttheObject.FGColours[__STATE_SELECTED] = Get_Color(theObject.Properties[__NEMESIS_PROPERTY_FG_COLOR_SELECTED], \"#FFFFFF\", interfaceLook);\n\ttheObject.FGColours[__STATE_FOCUSED] = Get_Color(theObject.Properties[__NEMESIS_PROPERTY_FG_COLOR_FOCUSED], null, interfaceLook);\n\ttheObject.FGColours[__STATE_READONLY] = Get_Color(theObject.Properties[__NEMESIS_PROPERTY_FG_COLOR_READONLY], null, interfaceLook);\n\ttheObject.FGColours[__STATE_DISABLED] = Get_Color(theObject.Properties[__NEMESIS_PROPERTY_FG_COLOR_DISABLED], null, interfaceLook);\n\ttheObject.FGColours[__STATE_PRESSED] = Get_Color(theObject.Properties[__NEMESIS_PROPERTY_FG_COLOR_PRESSED], null, interfaceLook);\n\ttheObject.FGColours[__STATE_HOVERED] = Get_Color(theObject.Properties[__NEMESIS_PROPERTY_FG_COLOR_HOVERED], null, interfaceLook);\n\t//set background images\n\ttheObject.BGImages[__STATE_DEFAULT] = Get_String(theObject.Properties[__NEMESIS_PROPERTY_BK_IMAGE_DEFAULT], null);\n\ttheObject.BGImages[__STATE_DISABLED] = Get_String(theObject.Properties[__NEMESIS_PROPERTY_BK_IMAGE_DISABLED], null);\n\ttheObject.BGImages[__STATE_FOCUSED] = Get_String(theObject.Properties[__NEMESIS_PROPERTY_BK_IMAGE_FOCUSED], null);\n\ttheObject.BGImages[__STATE_HOVERED] = Get_String(theObject.Properties[__NEMESIS_PROPERTY_BK_IMAGE_HOVERED], null);\n\ttheObject.BGImages[__STATE_PRESSED] = Get_String(theObject.Properties[__NEMESIS_PROPERTY_BK_IMAGE_PRESSED], null);\n\ttheObject.BGImages[__STATE_READONLY] = Get_String(theObject.Properties[__NEMESIS_PROPERTY_BK_IMAGE_READONLY], null);\n\t//and their positions\n\ttheObject.BGImagesPos[__STATE_DEFAULT] = Get_String(theObject.Properties[__NEMESIS_PROPERTY_BACKIMAGE_POS], null);\n\ttheObject.BGImagesPos[__STATE_DISABLED] = Get_String(theObject.Properties[__NEMESIS_PROPERTY_BACKIMAGE_DISABLED_POS], null);\n\ttheObject.BGImagesPos[__STATE_FOCUSED] = Get_String(theObject.Properties[__NEMESIS_PROPERTY_BACKIMAGE_FOCUSED_POS], null);\n\ttheObject.BGImagesPos[__STATE_HOVERED] = Get_String(theObject.Properties[__NEMESIS_PROPERTY_BACKIMAGE_HOVERED_POS], null);\n\ttheObject.BGImagesPos[__STATE_PRESSED] = Get_String(theObject.Properties[__NEMESIS_PROPERTY_BACKIMAGE_PRESSED_POS], null);\n\ttheObject.BGImagesPos[__STATE_READONLY] = Get_String(theObject.Properties[__NEMESIS_PROPERTY_BACKIMAGE_READONLY_POS], null);\n\t//set foreground images\n\ttheObject.FGImages[__STATE_DEFAULT] = Get_String(theObject.Properties[__NEMESIS_PROPERTY_IMAGE], null);\n\ttheObject.FGImages[__STATE_DISABLED] = Get_String(theObject.Properties[__NEMESIS_PROPERTY_IMAGE_DISABLED], null);\n\ttheObject.FGImages[__STATE_HOVERED] = Get_String(theObject.Properties[__NEMESIS_PROPERTY_IMAGE_HOVERED], null);\n\ttheObject.FGImages[__STATE_PRESSED] = Get_String(theObject.Properties[__NEMESIS_PROPERTY_IMAGE_PRESSED], null);\n\t//and their positions\n\ttheObject.FGImagesPos[__STATE_DEFAULT] = Get_String(theObject.Properties[__NEMESIS_PROPERTY_IMAGE_POS], null);\n\ttheObject.FGImagesPos[__STATE_DISABLED] = Get_String(theObject.Properties[__NEMESIS_PROPERTY_IMAGE_DISABLED_POS], null);\n\ttheObject.FGImagesPos[__STATE_HOVERED] = Get_String(theObject.Properties[__NEMESIS_PROPERTY_IMAGE_HOVERED_POS], null);\n\ttheObject.FGImagesPos[__STATE_PRESSED] = Get_String(theObject.Properties[__NEMESIS_PROPERTY_IMAGE_PRESSED_POS], null);\n\t//grid images\n\ttheObject.GridImages[__STATE_DEFAULT] = Get_String(theObject.Properties[__NEMESIS_PROPERTY_GRID_IMAGES], null);\n}", "updateHighlight() {\n var on = this.hover || this.selected;\n this.highlighted = on;\n if (on) {\n this.material.emissive = this.defaultEmissiveness;\n } else {\n this.material.emissive = this.defaultEmissiveness\n .clone()\n .multiplyScalar(this.brightness);\n this.material.needsUpdate = true;\n }\n }", "updateSelected(ids){\r\n d3.select(\"#breweryLayer\") // de-select everything, ignore filters\r\n .selectAll(\"circle\")\r\n .classed(\"selected\", false);\r\n\r\n if(ids == null){return; } // don't select anything new, on clear\r\n\r\n for(let i = 0; i < ids.length; i++){\r\n d3.select(`#br_${ids[i]}`)\r\n .classed(\"selected\", true);\r\n }\r\n }", "function SelectionChange() { }", "function SelectionChange() { }", "setInitialState() {\n if (FefStorage.isLocalStorageAvailable() && FefStorage.hasItem(STORAGE_KEY)) {\n let savedSelections = FefStorage.getItemJsonParsed(STORAGE_KEY);\n\n let selectedSourceURN = savedSelections[this.collectionURN];\n\n if (selectedSourceURN && this.connectsToCollection(selectedSourceURN)) {\n this.$element.hide();\n this.toggleCollections(selectedSourceURN);\n\n let $collection = $(this.$sourceCollections.toArray().find(c => $(c).data('urn') === selectedSourceURN));\n\n if ($collection) {\n $collection.addClass(SELECTED_COLLECTION_CLASS);\n return;\n }\n }\n }\n\n // none was selected: hide all collections, show selection element\n this.toggleCollections(false);\n this.$element.show();\n }", "drawCurrentState(){\n reset();\n drawPolygonLines(this.hull, \"red\"); \n drawLine(this.currentVertex, this.nextVertex, \"green\");\n drawLine(this.currentVertex,this.points[this.index]);\n for(let i=0;i<this.points.length;i++){\n this.points[i].draw();\n }\n\n for(let i=0;i<this.hull.length;i++){\n this.hull[i].draw(5,\"red\");\n }\n }", "getUpdatedSelection(){super.getUpdatedSelection();if(this.__breadcrumbs)this.__breadcrumbs.selection=this.selection}", "get _shouldUpdateSelection(){return this.selected!=null||this.selectedValues!=null&&this.selectedValues.length;}", "get selectionSet() {\n return (this.updated & UPDATED_SEL) > 0;\n }", "selectionChanged(selected) {\n const vizConf = this.visualConfig;\n this.selected = selected;\n if (selected) {\n this.label.tint = vizConf.ui.label.font.highlight;\n this.labelBgContainer.forEach((labelBg) => {\n labelBg.tint = vizConf.ui.label.background.highlight;\n });\n } else {\n this.label.tint = vizConf.ui.label.font.color;\n this.labelBgContainer.forEach((labelBg) => {\n labelBg.tint = vizConf.ui.label.background.color;\n });\n }\n }", "update() {\n if (this.showSelection && this.position) {\n // var screenPosition = this.computeScreenSpacePosition(this.position, screenPosition);\n var screenPosition = SceneTransforms.wgs84ToWindowCoordinates(this.scene, this.position);\n if (!screenPosition) {\n this._screenPositionX = offScreen;\n this._screenPositionY = offScreen;\n } else {\n var container = this._container;\n var containerWidth = container.clientWidth;\n var containerHeight = container.clientHeight;\n var indicatorSize = this._selectionIndicatorElement.clientWidth;\n var halfSize = indicatorSize * 0.5;\n screenPosition.x =\n Math.min(\n Math.max(screenPosition.x, -indicatorSize),\n containerWidth + indicatorSize\n ) - halfSize;\n screenPosition.y =\n Math.min(\n Math.max(screenPosition.y, -indicatorSize),\n containerHeight + indicatorSize\n ) - halfSize;\n this._screenPositionX = Math.floor(screenPosition.x + 0.25) + \"px\";\n this._screenPositionY = Math.floor(screenPosition.y + 0.25) + \"px\";\n }\n }\n }", "function selectAll() {\n\t\tvar newSelections = [];\n\t\tfor(var d = 0; d < 3; d++) {\n\t\t\tnewSelections.push([]);\n\t\t\tnewSelections[d].push({\"minVal\":0, \"maxVal\":dim[d] - 1});\n\t\t}\n\t\tselections = newSelections;\n\t\tdrawSelections();\n\t\tupdateLocalSelections(true);\n\t\tsaveSelectionsInSlot();\n\t}", "function setSelection ({entity}) {\n console.log('setting seletion')\n entity.meta.selected = !entity.meta.selected\n return entity\n}", "function updateSelection(){\n\t\t\tif(lastMousePos.pageX == null) return;\n\t\t\t\n\t\t\tsetSelectionPos(selection.second, lastMousePos);\n\t\t\tclearSelection();\n\t\t\t\n\t\t\tif(selectionIsSane()) drawSelection();\n\t\t}", "function setSelectedStates() {\n clearSelectedStates();\n var indexMap = createIndexMap(_scope.ugCustomSelect.dragData.startCell, _scope.ugCustomSelect.dragData.endCell);\n _scope.ugCustomSelect.selectedCells = getCellsWithIndexMap(indexMap);\n _scope.ugCustomSelect.cellMap = _scope.ugCustomSelect.selectedCells.reduce(function (map, obj) {\n if (map[obj.row.uid]) {\n map[obj.row.uid].push(obj.col.uid);\n } else {\n map[obj.row.uid] = [obj.col.uid];\n }\n return map;\n }, {});\n\n for (var i = 0; i < _scope.ugCustomSelect.selectedCells.length; i++) {\n var currentCell = _scope.ugCustomSelect.selectedCells[i];\n currentCell.elem.find('.ui-grid-cell-contents').addClass('ui-grid-custom-selected');\n }\n\n _scope.ugCustomSelect.copyData = createCopyData(_scope.ugCustomSelect.selectedCells, (indexMap.col.end - indexMap.col.start) + 1);\n }", "_gcSelections () {\n for (let i = 0; i < this._selections.length; ++i) {\n const s = this._selections[i]\n const oldOffset = s.offset\n\n // check for newly downloaded pieces in selection\n while (this.bitfield.get(s.from + s.offset) && s.from + s.offset < s.to) {\n s.offset += 1\n }\n\n if (oldOffset !== s.offset) s.notify()\n if (s.to !== s.from + s.offset) continue\n if (!this.bitfield.get(s.from + s.offset)) continue\n\n this._selections.splice(i, 1) // remove fully downloaded selection\n i -= 1 // decrement i to offset splice\n\n s.notify()\n this._updateInterest()\n }\n\n if (!this._selections.length) this.emit('idle')\n }", "_gcSelections () {\n for (let i = 0; i < this._selections.length; ++i) {\n const s = this._selections[i]\n const oldOffset = s.offset\n\n // check for newly downloaded pieces in selection\n while (this.bitfield.get(s.from + s.offset) && s.from + s.offset < s.to) {\n s.offset += 1\n }\n\n if (oldOffset !== s.offset) s.notify()\n if (s.to !== s.from + s.offset) continue\n if (!this.bitfield.get(s.from + s.offset)) continue\n\n this._selections.splice(i, 1) // remove fully downloaded selection\n i -= 1 // decrement i to offset splice\n\n s.notify()\n this._updateInterest()\n }\n\n if (!this._selections.length) this.emit('idle')\n }", "_gcSelections () {\n for (let i = 0; i < this._selections.length; ++i) {\n const s = this._selections[i]\n const oldOffset = s.offset\n\n // check for newly downloaded pieces in selection\n while (this.bitfield.get(s.from + s.offset) && s.from + s.offset < s.to) {\n s.offset += 1\n }\n\n if (oldOffset !== s.offset) s.notify()\n if (s.to !== s.from + s.offset) continue\n if (!this.bitfield.get(s.from + s.offset)) continue\n\n this._selections.splice(i, 1) // remove fully downloaded selection\n i -= 1 // decrement i to offset splice\n\n s.notify()\n this._updateInterest()\n }\n\n if (!this._selections.length) this.emit('idle')\n }", "function cloneSelectedEntity() {\n if (AFRAME.INSPECTOR.selectedEntity) {\n cloneEntity(AFRAME.INSPECTOR.selectedEntity);\n }\n}", "function drawItemSelection(x,y,w,h,id){\n\t\n\tif (numberSelected() == 1) { //Change to == numberRuleItems\n\t\tallowed = false;\n\t} else if (numberSelected() == 0) { // < numberRuleItems\n\t\tallowed = true;\n\t}\n\t\tconsole.log(ruleType, ruleNumber, ruleColor)\n\t\n\t//Depending on which item you draw... Do the following...\n\tvar img = borderImage2; // deselected\n\tif (id == \"hat\"){\n\t\tif (hatSelected == true){\n\t\t\timg = borderImage; // selected\n\t\t}\n\t\tuiObjects[2] = new uiObject(x, y, w, h, \n\t\t\tfunction (){\n\t\t\t\tif (hatSelected){\n\t\t\t\t\thatSelected = false; // Hat selected\n\t\t\t\t} else if (allowed==true) {hatSelected = true;}\n\t\t\t\tconsole.log(\"hat selected.\")\n\t\t}, null, function() {});\n\t}\n\n\tif (id == \"shirt\"){\n\t\tif (shirtSelected == true){\n\t\t\timg = borderImage; // selected\n\t\t}\n\t\tuiObjects[3] = new uiObject(x, y, w, h, \n\t\t\tfunction (){\n\t\t\t\tif (shirtSelected){\n\t\t\t\t\tshirtSelected = false; // shirt selected\n\t\t\t\t}else if (allowed==true) {shirtSelected = true;}\n\t\t\t\tconsole.log(\"shirt selected.\")\n\t\t}, null, function() {});\t\t\n\t}\n\n\tif (id == \"pants\"){\n\t\tif (pantsSelected == true){\n\t\t\timg = borderImage; // selected\t\t\n\t\t}\n\t\tuiObjects[4] = new uiObject(x, y, w, h, \n\t\t\tfunction (){\n\t\t\t\tif (pantsSelected){\n\t\t\t\t\tpantsSelected = false; // pants selected\n\t\t\t\t}else if (allowed==true) {pantsSelected = true;}\n\t\t\t\tconsole.log(\"pants selected.\")\n\t\t}, null, function() {});\n\t}\n\n\tif (id == \"shoes\"){\n\t\tif (shoesSelected == true){\n\t\t\timg = borderImage; // selected\t\t\n\t\t}\n\t\tuiObjects[5] = new uiObject(x, y, w, h, \n\t\t\tfunction (){\n\t\t\t\tif (shoesSelected){\n\t\t\t\t\tshoesSelected = false; // shoes selected\n\t\t\t\t}else if (allowed==true) {shoesSelected = true;}\n\t\t\t\tconsole.log(\"shoes selected.\")\n\t\t}, null, function() {});\n\t}\n\t\n\t\tif (id == \"itemFront\"){\n\t\tif (itemfSelected == true){\n\t\t\timg = borderImage; // selected\n\t\t}\n\t\tuiObjects[6] = new uiObject(x, y, w, h, \n\t\t\tfunction (){\n\t\t\t\tif (itemfSelected){\n\t\t\t\t\titemfSelected = false; // Hat selected\n\t\t\t\t}else if (allowed==true) {itemfSelected = true;}\n\t\t\t\tconsole.log(\"front item selected.\")\n\t\t}, null, function() {});\n\t}\n\t\n\t\tif (id == \"itemBack\"){\n\t\tif (itembSelected == true){\n\t\t\timg = borderImage; // selected\n\t\t}\n\t\tuiObjects[7] = new uiObject(x, y, w, h, \n\t\t\tfunction (){\n\t\t\t\tif (itembSelected){\n\t\t\t\t\titembSelected = false; // Hat selected\n\t\t\t\t}else if (allowed==true) {itembSelected = true;}\n\t\t\t\tconsole.log(\"back item selected.\")\n\t\t}, null, function() {});\n\t}\n\n\t//create a box around each item.\n\tctx.drawImage(img,x,y,w,h);\n}", "setSymbolArt(state, sa) {\n state.parts = sa.parts\n state.lastId = sa.lastId\n state.selected = {}\n state.requestUpdateColorLayers = {}\n state.requestUpdateVertLayers = {}\n state.equestUpdateTypeLayers = {}\n //start history from a fresh state\n state.undoStack = []\n state.redoStack = []\n }", "function updateSelection(editorState, selection, forceSelection) {\n\t return EditorState.set(editorState, {\n\t selection: selection,\n\t forceSelection: forceSelection,\n\t nativelyRenderedContent: null,\n\t inlineStyleOverride: null\n\t });\n\t}", "function level3State() {\n // +++++++++++++++++++++++++++++Update level 3 state scene+++++++++++++++++++++++++++++++++++\n sea.update();\n //updates for player object\n player.update();\n for (var count = 0; count < fences.length; count++) {\n fences[count].update();\n }\n for (var count = 0; count < crystals.length; count++) {\n crystals[count].update();\n }\n for (var count = 0; count < ghosts.length; count++) {\n ghosts[count].update();\n }\n //update all object\n ufo.update();\n //check collision of objects\n //+++ comment temporary\n collision.update();\n //update the score board\n scoreboard.update();\n //level label update\n levelLabel.update();\n // +++++++++++++++++++++++++++++End of Update level 3 state scene+++++++++++++++++++++++++++++++++++\n //check if player dead, if dead, go to game over state\n if (scoreboard.lives <= 0) {\n //remove everything from the stage first\n stage.removeChild(game);\n game.removeAllChildren();\n game.removeAllEventListeners();\n //create the other state screen --> game over state screen\n currentState = constants.GAME_OVER_STATE;\n changeState(currentState);\n }\n }", "ReselectNodes() {\n var selectedNodes = this._selectionHandler ? this._selectionHandler.getSelection() : [];\n for (var i = 0; i < selectedNodes.length; i++) {\n // Don't show selection effect for obscured nodes when isolate is being used\n if (this._isolatedNodes.length > 0) {\n var lastIsolated = this._isolatedNodes[this._isolatedNodes.length - 1];\n if (selectedNodes[i] === lastIsolated || selectedNodes[i].isDescendantOf(lastIsolated))\n selectedNodes[i].setSelected(true);\n } else selectedNodes[i].setSelected(true);\n }\n }", "_updateQuadtree() {\n this._quadtree.clear();\n //insert all entities into the tree again\n for (let i = 0; i < this._entities.length; i++) {\n const entity = this._entities[i];\n this._quadtree.insert(entity);\n }\n }", "function SelectState() {\n QueryState.apply(this, arguments);\n}", "function updateSelection(e) {\n diagram.model.selectedNodeData = null;\n var it = diagram.selection.iterator;\n while (it.next()) {\n var selnode = it.value;\n // ignore a selected link or a deleted node\n if (selnode instanceof go.Node && selnode.data !== null) {\n diagram.model.selectedNodeData = selnode.data;\n break;\n }\n }\n $scope.$apply();\n }", "enableObjectSelection() {\n const state = this.canvasStates[this.currentStateIndex];\n const scribbles = this.getFabricObjectsFromJson(state);\n\n this.rehydrateCanvas(scribbles, (scribble) => {\n if (scribble.type === 'i-text') {\n scribble.setControlsVisibility({\n bl: false,\n br: false,\n mb: false,\n ml: false,\n mr: false,\n mt: false,\n tl: false,\n tr: false,\n });\n }\n });\n }", "_updateState() {\n const currentProps = this.props;\n const currentViewport = this.context.viewport;\n const propsInTransition = this._updateUniformTransition();\n this.internalState.propsInTransition = propsInTransition;\n // Overwrite this.context.viewport during update to use the last activated viewport on this layer\n // In multi-view applications, a layer may only be drawn in one of the views\n // Which would make the \"active\" viewport different from the shared context\n this.context.viewport = this.internalState.viewport || currentViewport;\n // Overwrite this.props during update to use in-transition prop values\n this.props = propsInTransition;\n\n try {\n const updateParams = this._getUpdateParams();\n const oldModels = this.getModels();\n\n // Safely call subclass lifecycle methods\n if (this.context.gl) {\n this.updateState(updateParams);\n } else {\n try {\n this.updateState(updateParams);\n } catch (error) {\n // ignore error if gl context is missing\n }\n }\n // Execute extension updates\n for (const extension of this.props.extensions) {\n extension.updateState.call(this, updateParams, extension);\n }\n\n const modelChanged = this.getModels()[0] !== oldModels[0];\n this._updateModules(updateParams, modelChanged);\n // End subclass lifecycle methods\n\n if (this.isComposite) {\n // Render or update previously rendered sublayers\n this._renderLayers(updateParams);\n } else {\n this.setNeedsRedraw();\n // Add any subclass attributes\n this._updateAttributes(this.props);\n\n // Note: Automatic instance count update only works for single layers\n if (this.state.model) {\n this.state.model.setInstanceCount(this.getNumInstances());\n }\n }\n } finally {\n // Restore shared context\n this.context.viewport = currentViewport;\n this.props = currentProps;\n this.clearChangeFlags();\n this.internalState.needsUpdate = false;\n this.internalState.resetOldProps();\n }\n }", "_processInitialSelections() {\n if (this._selectionHandler && this._initialSelection) {\n var targets = DvtTreeUtils.getAllNodes(this._root);\n this._selectionHandler.processInitialSelections(this._initialSelection, targets);\n this._initialSelection = null;\n }\n }", "function Selection() {\n var boundingBox = this.ui = $('<div></div>');\n var sid = this.id = null;\n selectionObjects.push(this);\n boundingBox.css({\n 'background': '#e8e8e8',\n 'padding': '4px 4px 2px 4px',\n 'border-radius': '6px',\n 'margin-bottom': '3px',\n 'position': 'relative',\n 'width': '156px'\n });\n\n var header = $('<div></div>');\n boundingBox.append(header);\n var heading = $('<div></div>');\n var controls = $('<div></div>');\n\n header.append(heading, controls);\n heading.css({\n 'font-family': 'Arial',\n 'font-weight': 'bold',\n 'font-size': '12px',\n 'display': 'inline-block',\n 'width': '60px'\n });\n\n controls.css({\n 'display': 'inline-block'\n });\n\n header.hide();\n controls.editMode = false;\n\n var removeButton = new button(icons.minus, 16, { bfr: 0.5, backgroundColor: '#f06f6f', tooltip: 'Remove Selection' });\n var editButton = new button(icons.pencil, 16, { tooltip: 'Edit Selection' });\n var visibleButton = new button(icons.visible, 16, { tooltip: 'Show / Hide Selection' });\n\n controls.append(removeButton.ui)\n controls.append(editButton.ui);\n controls.append(visibleButton.ui);\n\n var parameters = $('<div></div>');\n boundingBox.append(parameters);\n\n var styleHolder = $('<div></div>');\n\n removeButton.ui.on('click', function () {\n stateManager.removeSelection(sid);\n boundingBox.detach();\n //delete this;\n });\n\n editButton.ui.on('click', function () {\n parameters.toggle();\n });\n\n var hidden = false;\n visibleButton.ui.on('click', () => {\n stateManager.toggleHide(sid);\n if (hidden) {\n hidden = false;\n visibleButton.setSVG(icons.visible);\n }\n else {\n hidden = true;\n visibleButton.setSVG(icons.invisible);\n }\n });\n\n var styleBox = new StyleBox();\n\n styleHolder.append(styleBox.ui);\n styleBox.ui.css({\n 'position': 'static',\n // 'left' : '0',\n 'width': 'px',\n 'border-radius': '4px'\n });\n\n styleBox.ui.hide();\n\n var allControl = this.allSelector = {\n key: 'Select All Atom',\n value: null,\n active: true\n }\n\n var allCheckBox = new $3Dmol.UI.Form.Checkbox(allControl);\n parameters.append(allCheckBox.ui);\n\n\n var selectionFormControl = this.selectionValue = {\n key: 'Selection Spec',\n value: null,\n active: true\n }\n\n var selectionSpecForm = new $3Dmol.UI.Form(validAtomSelectionSpecs, selectionFormControl);\n parameters.append(selectionSpecForm.ui);\n\n var submitControls = $('<div></div>');\n var submit = new button(icons.tick, 16, { backgroundColor: 'lightgreen', tooltip: 'Submit' });\n var cancel = new button(icons.cross, 16, { backgroundColor: 'lightcoral', tooltip: 'Cancel' });\n submitControls.append(submit.ui, cancel.ui);\n\n\n var alertBox = new AlertBox();\n parameters.append(alertBox.ui);\n\n parameters.append(submitControls);\n boundingBox.append(styleHolder);\n\n allCheckBox.update = function () {\n selectionSpecForm.ui.toggle();\n }\n\n function finalizeSelection(id) {\n header.show();\n controls.editMode = true;\n sid = this.id = id;\n heading.text('Sel#' + id);\n boundingBox.attr('data-id', id);\n parameters.hide();\n styleBox.setSid(id);\n styleBox.ui.show();\n }\n\n function checkAndAddSelection(sid = null) {\n var validate = selectionSpecForm.validate();\n if (validate) {\n selectionSpecForm.getValue();\n var checkAtoms = stateManager.checkAtoms(selectionFormControl.value);\n\n if (Object.keys(selectionFormControl.value).length == 0) {\n alertBox.error('Please enter some input');\n }\n else {\n if (checkAtoms) {\n var id = stateManager.addSelection(selectionFormControl.value, sid);\n finalizeSelection(id);\n if (sid == null) _editingForm = false;\n }\n else {\n alertBox.error('No atom selected');\n }\n }\n }\n else {\n alertBox.error('Invalid Input');\n }\n }\n\n function removeSelf() {\n\n // delete selectionToRemove;\n }\n\n submit.ui.on('click', () => {\n if (controls.editMode == false) {\n if (allControl.value) {\n let id = stateManager.addSelection({});\n finalizeSelection(id);\n _editingForm = false;\n }\n else {\n checkAndAddSelection();\n }\n\n }\n else {\n if (allControl.value) {\n let id = sid;\n stateManager.addSelection({}, id);\n finalizeSelection(id);\n }\n else {\n let id = sid;\n checkAndAddSelection(id);\n }\n }\n });\n\n var self = this;\n\n cancel.ui.on('click', () => {\n if (controls.editMode) {\n parameters.hide();\n }\n else {\n boundingBox.detach();\n removeSelf(self);\n _editingForm = false;\n }\n });\n\n\n boundingBox.on('keyup', (e) => {\n if (e.key == 'Enter') {\n submit.ui.trigger('click');\n }\n });\n\n /*\n * @function Selection#setProperty\n * @param {string} id Id of the selection created in StateManager \n * @param {Object} specs Defination of the selection that will be used to set default \n * values in the form\n */\n this.setProperty = function (id, specs) {\n // check for all selection\n if (Object.keys(specs).length == 0) {\n allCheckBox.setValue(true)\n } else {\n selectionSpecForm.setValue(specs);\n }\n\n // finalize the selection \n finalizeSelection(id);\n }\n\n /*\n * Adds style to the given selection \n * \n * @function Selection#addStyle \n * @param {String} selId Id of the selection to inititate the StyleBox\n * @param {String} styleId Id of the style that is created through StateManager\n * @param {AtomStyleSpecs} styleSpecs \n */\n this.addStyle = function (selId, styleId, styleSpecs) {\n styleBox.addStyle(selId, styleId, styleSpecs);\n }\n }", "function drawAcceptState(event)\n{\n //get mouse click x and y\n let arr = getMouseCoords(event);\n let x = arr[0]; \n let y = arr[1];\n\n canvas.off();\n\n var c1 = new fabric.Circle({\n\n strokeWidth: 5,\n radius: 40,\n fill: '#fff',\n stroke: 'black',\n left: x-40,\n top: y-40,\n \n });\n\n var c2 = new fabric.Circle({\n\n strokeWidth: 3,\n radius: 50,\n fill: '#fff',\n stroke: 'black',\n left: x-49,\n top: y-49,\n \n });\n\n var text = new fabric.Text('Q'+statenum, {\n left: c1.left+20,\n top: c1.top+20,\n fill: 'black'\n });\n\n //groups the text and the state together such that they move together\n var group = new fabric.Group([ c2, c1, text ], {\n left: c1.left,\n top: c1.top,\n })\n\n var state = {\n \"x\": c1.left,\n \"y\": c1.top,\n \"statenum\": statenum,\n \"acceptState\": true\n\n }\n\n statenum++;\n\n states.push(state);\n canvas.add(group);\n json = canvas.toJSON();\n\n for(i in states)\n {\n console.log(states[i]);\n }\n\n document.getElementById(\"addState\").disabled = false;\n document.getElementById(\"addAcceptState\").disabled = false;\n}", "changeManualSelection() {\n this.setState(state => {\n // Get manualSelection boolean option for selected group.\n let groupInfo = state.groups[state.selectedGroup];\n let newManualSelection = !groupInfo.manualSelection;\n\n // Erase any selection if filtering mode is now activated\n if (!newManualSelection) {\n groupInfo.selection = new Set();\n }\n\n // Change manualSelection to its oposite.\n groupInfo.manualSelection = newManualSelection;\n return state;\n });\n }", "function updateValuesAndStates() {\n [values, states] = generateDefaultStateArray(getItemCount());\n}", "updateAppliedTexture()\n {\n this.quadMaterial.setTexture(this.textures[this.selectedTexture]);\n }", "__applyModelChanges() {\n this.buildLookupTable();\n this._applyDefaultSelection();\n }", "_updateOverviewSelection() {\n if (this.overview) {\n var ovChart = this.overview.getBackgroundChart();\n ovChart.getOptions()['selection'] = DvtChartDataUtils.getCurrentSelection(this);\n ovChart.render(); // rerender because unselected markers were not rendered\n }\n }", "sendSelection() {\n\t\tlet hasAfterSelect = typeof this.props.afterSelect == 'function', hasGetSelection = typeof this.props.afterSelectGetSelection == 'function';\n\n\t\tif (hasAfterSelect || hasGetSelection) {\n\t\t\tlet selectionArray = [], selection = this.state.selection;\n\n\t\t\t// Parse the selection to return it as an array instead of a Set obj\n\t\t\tselection.forEach(item => {\n\t\t\t\tselectionArray.push(item.toString());\n\t\t\t});\n\n\t\t\tif (hasGetSelection) { // When you just need the selection but no data\n\t\t\t\tthis.props.afterSelectGetSelection.call(this, selectionArray, selection); // selection array / selection Set()\n\t\t\t}\n\n\t\t\tif (hasAfterSelect) {\n\t\t\t\tlet selectedData = [], properId = null, rowIndex = null, filteredData = null;\n\t\t\t\tlet {indexedData, initialData, rawData, data} = this.state;\n\t\t\t\tlet fields = new Set(_.keys(rawData.get(0).toJSON())), hasIdField = fields.has(this.state.idField) ? true : false;\n\n\t\t\t\tif (hasIdField) {\n\t\t\t\t\tselectedData = rawData.filter(element => {\n\t\t\t\t\t\treturn selection.has(element.get(this.state.idField).toString());\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\t// Get the data (initialData) that match with the selection\n\t\t\t\t\tfilteredData = initialData.filter(element => selection.has(element.get(this.state.idField)));\n\n\t\t\t\t\t// Then from the filtered data get the raw data that match with the selection\n\t\t\t\t\tselectedData = filteredData.map(row => {\n\t\t\t\t\t\tproperId = row.get(this.state.idField);\n\t\t\t\t\t\trowIndex = this.state.initialIndexed[properId]._rawDataIndex;\n\n\t\t\t\t\t\treturn rawData.get(rowIndex);\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tthis.props.afterSelect.call(this, selectedData.toJSON(), selectionArray);\n\t\t\t}\n\t\t}\n\t}", "function updateSelection (){\n //initially all subject are active\n // on click all subject become inactive\n self.clickFlag = true;\n\n\n //1) check if subject is already active\n console.log(this.id)\n var elm = this.id\n var clickedSubjectId = self.svg.selectAll('.subject-bar')\n .filter(function (d) {\n return d.key == elm\n }).attr('id');\n if (self.activeSubjects.indexOf(clickedSubjectId) <= -1 ){\n //2) if not add it to the active array\n self.activeSubjects.push(clickedSubjectId)\n self.svg.select(clickedSubjectId)\n .attr('class', 'subject-bar active')\n } else {\n //remove from the array\n self.activeSubjects.splice(self.activeSubjects.indexOf(clickedSubjectId) , 1)\n }\n\n // make unselected bars inactive\n self.svg.selectAll('.subject-bar')\n .filter(function (d) {\n return self.activeSubjects.indexOf(d.key) <= -1\n })\n .attr('class', 'subject-bar inactive')\n\n console.log(self.activeSubjects)\n // filter domain\n self.dimension.filter(function(d){\n return self.activeSubjects.indexOf(d) > -1\n })\n\n // update all charts\n self.dispatch.call('update')\n\n}", "function OnSpecialItemChanged(specialItem) {\n selectionsSpecialItem = specialItem;\n OnFilterCriteriaChanged();\n}", "function updateSelection_(e) {\n\t\t\t\tmyGuests.model.selectedNodeData = null;\n\t\t\t\tvar it = myGuests.selection.iterator;\n\t\t\t\twhile (it.next()) {\n\t\t\t\t\tvar selnode = it.value;\n\t\t\t\t\t// ignore a selected link or a deleted node\n\t\t\t\t\tif (selnode instanceof go.Node && selnode.data !== null) {\n\t\t\t\t\t\tmyGuests.model.selectedNodeData = selnode.data;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tscope.$apply();\n\t\t\t}", "get _shouldUpdateSelection(){return this.selected!=null;}", "function renderAfterDagreRender(){\n d3.selectAll('g.node').on(\"click\", function (n) {\n if(d3.select(this).classed('selected')){\n d3.selectAll('g.node').classed('selected', false);\n selectCommit(null);\n }else{\n d3.selectAll('g.node').classed('selected', false);\n d3.select(this).classed(\"selected\", true);\n selectCommit(gr.node(n).commitdata);\n }\n });\n\n\n d3.selectAll(\".commitcontainer\").attr(\"style\", \"min-width:\" + nodewidth + \"px\");\n\n //Append the visualizations of each commit\n // d3.selectAll(\".lineschanged\").append(\"span\").text(\"asdf\");\n let nodes = d3.selectAll('.lineschanged');\n nodes.each(function () {\n renderLinesChanged(d3.select(this),gr.node(this.id).commitdata, this.id); //I only need the commitdata #Mike\n });\n\n\n\n // https://groups.google.com/forum/#!topic/d3-js/fMh1Sr7QFEA\n\n\n d3.selectAll(\"foreignObject\").attr(\"width\", nodewidth).attr(\"height\", nodeheight);\n\n\n // let transx = -(nodewidth) / 6 + 4;\n // let transy = 8\n // d3.selectAll(\".node\").selectAll(\".label\").attr(\"transform\", \"translate(\" + transx + \",\" + transy + \")\");\n\n\n let transx = (-(nodewidth) / 6 + 4);\n let transy = 8;\n d3.selectAll(\".node\").selectAll(\"foreignObject\").attr(\"transform\", \"translate(\" + transx + \",\" + transy + \")\");\n}", "function drawSelected() {\n if (timer_draw) timer_draw.stop(); //Clear all the canvases\n\n clearCanvas([ctx_edges, ctx_nodes, ctx_hover, ctx_hidden]); //Draw the edges\n\n edges_selected.forEach(function (d) {\n //Make the selected edges more visually apparent\n drawEdges(ctx_edges, d, d.gradient_hover, getLineWidth(d));\n });\n\n if (nodes !== nodes_selected) {\n //First make all the nodes lightly drawn\n ctx_nodes.globalAlpha = node_fade_opacity;\n nodes.forEach(function (d) {\n d.opacity = node_fade_opacity;\n drawNodes(ctx_nodes, d, d.r);\n }); //And do the same for the labels inside\n\n renderNodeLabels(ctx_nodes, nodes);\n } //if\n //Draw the selected nodes in full\n\n\n ctx_nodes.globalAlpha = 1;\n nodes_selected.forEach(function (d) {\n d.opacity = 1;\n drawNodes(ctx_nodes, d, d.r);\n }); //Draw the labels of the selected nodes in full\n\n renderNodeLabels(ctx_nodes, nodes_selected); // community_count.forEach(d => {\n // ctx_nodes.fillStyle = node_color_interpolate(node_community_color(d.item))\n // ctx_nodes.beginPath()\n // ctx_nodes.arc(d.x, d.y, d.r, 0, pi2)\n // ctx_nodes.closePath()\n // ctx_nodes.fill()\n // })//forEach\n } //function drawSelected", "static async _RectangleSelection(event){\n\t\t\tconst tool = game.activeTool;\n\t\t\tif(tool !== \"select\") return;\n\t\t\tif($(document.getElementById(\"tokenAttacher\")).find(\".control-tool.select.active\").length <= 0 ) return;\n\t\t\t$(document.getElementById(\"tokenAttacher\")).find(\".control-tool.select\")[0].classList.toggle(\"active\");\t\n\t\t\t\n\t\t\tconst {coords, originalEvent} = event.data;\n\t\t\tconst {x, y, width, height, releaseOptions={}, controlOptions={}}=coords;\n\t\t\tlet selected = {};\t\n\t\t\tconst baseId= canvas.scene.getFlag(moduleName, \"attach_base\").element;\t\t\n\t\t\tconst token = canvas.tokens.get(baseId);\n\t\t\tfor (const type of [\"AmbientLight\", \"AmbientSound\", \"Drawing\", \"MeasuredTemplate\", \"Note\", \"Tile\", \"Token\", \"Wall\"]) {\n\t\t\t\tconst layer = canvas.getLayerByEmbeddedName(type);\n\t\t\t\t//if (layer.options.controllableObjects) {\n\t\t\t\t\t// Identify controllable objects\n\t\t\t\t\tconst controllable = layer.placeables.filter(obj => obj.visible && (obj.control instanceof Function));\n\t\t\t\t\tconst newSet = controllable.filter(obj => {\n\t\t\t\t\t\tlet c = obj.center;\n\t\t\t\t\t\t//filter base out\n\t\t\t\t\t\tif(obj.data._id === baseId) return;\n\t\t\t\t\t\t//Filter attached elements except when they are already attached to the base\n\t\t\t\t\t\tconst parent = obj.getFlag(moduleName, 'parent') || \"\";\n\t\t\t\t\t\tif(parent !== \"\" && parent !== baseId) return;\n\t\t\t\t\t\t//filter all inside selection\n\t\t\t\t\t\treturn Number.between(c.x, x, x+width) && Number.between(c.y, y, y+height);\n\t\t\t\t\t});\t\t\n\t\t\t\t\tselected[type] = newSet.map(a => a.data._id);\n\t\t\t\t\tif(selected[type].length <= 0) delete selected[type];\t\t\n\t\t\t\t//}\n\t\t\t}\n\t\t\tif(selected.length === 0) return;\n\t\t\tTokenAttacher._attachElementsToToken(selected, token, false);\n\t\t\tui.notifications.info(game.i18n.format(localizedStrings.info.ObjectsAttached));\n\t\t}", "function drawSelected() {\n if (timer_draw) timer_draw.stop(); //Clear all the canvases\n\n clearCanvas([ctx_edges, ctx_nodes, ctx_hover, ctx_hidden]); //Draw the edges\n\n edges_selected.forEach(function (d) {\n //Make the selected edges more visually apparent\n drawEdges(ctx_edges, d, d.gradient_hover, getLineWidth(d));\n });\n\n if (nodes !== nodes_selected) {\n //First make all the nodes lightly drawn\n ctx_nodes.globalAlpha = node_fade_opacity;\n nodes.forEach(function (d) {\n d.opacity = node_fade_opacity;\n drawNodes(ctx_nodes, d, d.r);\n }); //And do the same for the labels inside\n\n renderNodeLabels(ctx_nodes, nodes);\n } //if\n //Draw the selected nodes in full\n\n\n ctx_nodes.globalAlpha = 1;\n nodes_selected.forEach(function (d) {\n d.opacity = 1;\n drawNodes(ctx_nodes, d, d.r);\n }); //Draw the labels of the selected nodes in full\n\n renderNodeLabels(ctx_nodes, nodes_selected); // community_count.forEach(d => {\n // ctx_nodes.fillStyle = node_color_interpolate(node_biome_color(d.item))\n // ctx_nodes.beginPath()\n // ctx_nodes.arc(d.x, d.y, d.r, 0, pi2)\n // ctx_nodes.closePath()\n // ctx_nodes.fill()\n // })//forEach\n } //function drawSelected", "function updateHighlights() {\n\t// Highlight the selected species, if any\n\tif (!(selectedspecies==undefined)) {\n\tsvg.selectAll(\".focusrect\").classed(\"specieshighlighted\", function(thisd){\n\t\treturn (thisd[\"Genus\"]+thisd[\"Species\"]==selectedspecies[\"Genus\"]+selectedspecies[\"Species\"]);\n\t});\n\t}\n\tif (!(clickedspecies==undefined)) {\n\t// Highlight the clicked species, if any\n\tsvg.selectAll(\".focusrect\").classed(\"speciesclicked\", function(thisd){\n\t\tif (thisd[\"Genus\"]+thisd[\"Species\"]==clickedspecies[\"Genus\"]+clickedspecies[\"Species\"]) {\n\t\t\td3.select(this).moveToFront();\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t});\n\t}\n\t\n\t\n\t// Highlighted all the species in this family\n\tsvg.selectAll(\".focusrect\").classed(\"threatenedthighlighted\", function(thisd, thisi) {\n\t\tif (selectedfamily==undefined) {\n\t\t\treturn false;\n\t\t}\n\t\treturn (thisd[\"Family\"]==selectedfamily.familyname)&&(isThreatened(thisd));\n\t\t}).classed(\"healthyhighlighted\", function(thisd, thisi) {\n\t\tif (selectedfamily==undefined) {\n\t\t\treturn false;\n\t\t}\n\t\treturn (thisd[\"Family\"]==selectedfamily.familyname)&&(!isThreatened(thisd));\n\t\t});\n\t\t\n\t// Highlight the family\n\tsvg.selectAll(\".focusfamilyrect\").classed(\"threatenedthighlighted\", function(thisd, thisi) {\n\t\tif (selectedfamily==undefined) {\n\t\t\treturn false;\n\t\t}\n\t\treturn ((thisd.familyname==selectedfamily.familyname)&&(threatenedfamily(thisd)));\n\t}).classed(\"healthyhighlighted\", function(thisd, thisi) {\n\t\tif (selectedfamily==undefined) {\n\t\t\treturn false;\n\t\t}\n\t\treturn ((thisd.familyname==selectedfamily.familyname)&&(!threatenedfamily(thisd)));\n\t})\n\tupdateFamilyTooltip();\n\t\n\t// Highlight the order\n\tsvg.selectAll(\".focusorderlabel\").classed(\"focusorderlabelhighlighted\", function(thisd) {\n\t\tif (selectedorder==undefined) {\n\t\t\treturn false;\n\t\t}\n\t\treturn (thisd.ordername==selectedorder.ordername);\n\t})\n\tsvg.selectAll(\".focusordernumber\").classed(\"focusorderlabelhighlighted\", function(thisd) {\n\t\tif (selectedorder==undefined) {\n\t\t\treturn false;\n\t\t}\n\t\treturn (thisd.ordername==selectedorder.ordername);\n\t})\n\tsvg.selectAll(\".focusorderline\").classed(\"focusorderlinehighlighted\", function(thisd){\n\t\tif (selectedorder==undefined) {\n\t\t\treturn false;\n\t\t}\n\t\treturn (thisd.ordername==selectedorder.ordername);\n\t})\n\t\n}", "function tempSelected() {\n\ttempActive = true;\n\tlocationActive = false;\n\tradActive = false;\n\tco2Active = false;\n\tif (graphicActive) {\n\t\tdrawGraphic();\n\t} else if (tableActive) {\n\t\tdrawTable();\n\t}\n}", "function drawEntity() {\n if (sidebarOpen && mouseX < 220) return;\n if (menuVisible && mouseX < 220 && mouseY < 30) return;\n entities.push(createEntity(mouseX, mouseY, templates[selected], bMustMutate=false));\n}", "update(selectedStates, dataType, activeYear){\n\n let _this = this;\n this.activeYear = activeYear;\n\n // ******* TODO: PART V *******\n //Display the names of selected states in a list\n\n //******** TODO: PART VI*******\n //Use the shift data corresponding to the selected years and sketch a visualization\n //that encodes the shift information\n\n //******** TODO: EXTRA CREDIT I*******\n //Handle brush selection on the year chart and sketch a visualization\n //that encodes the shift informatiomation for all the states on selected years\n\n //******** TODO: EXTRA CREDIT II*******\n //Create a visualization to visualize the shift data\n //Update the visualization on brush events over the Year chart and Electoral Vote Chart\n console.log(selectedStates);\n let text = \"\";\n let span = d3.select(\"#stateList\");\n\n let yrSelection;\n let statesSelection;\n\n\n if(dataType == \"year\")\n {\n if(selectedStates == \"\"){\n _this.yearText = \"\", _this.yearSelection = \"\";\n if(_this.evText == \"\"){\n _this.statesSelection = \"\";\n }\n else{\n _this.yearSelection = \"\";\n if(_this.statesSelection)\n _this.chartViz(_this, _this.statesSelection);\n }\n }\n else {\n _this.yearSelection = selectedStates;\n text += \"<ul>\";\n selectedStates.forEach((row)=>{\n if(row)\n text += \"<li>\" + row + \"</li>\";\n });\n text += \"</ul>\";\n _this.yearText = text;\n\n yrSelection = _this.yearSelection;\n if(_this.evText) {\n if(yrSelection)\n _this.chartViz(_this, _this.statesSelection, yrSelection);\n else\n _this.chartViz(_this, _this.statesSelection);\n }\n }\n }\n else if(dataType == \"ev\")\n {\n if(selectedStates == \"\")\n _this.evText = \"\", _this.selectedStates = \"\";\n else {\n _this.statesSelection = selectedStates;\n text += \"<ul>\"\n selectedStates.forEach((row)=>{\n if(row.State)\n text += \"<li>\" + row.State + \"</li>\"\n });\n text += \"</ul>\";\n _this.evText = text;\n yrSelection = _this.yearSelection;\n statesSelection = _this.statesSelection;\n if(yrSelection)\n _this.chartViz(_this, _this.statesSelection, yrSelection);\n else\n _this.chartViz(_this, _this.statesSelection);\n\n }\n }\n\n yrSelection = _this.yearText ? _this.yearText : \"\";\n statesSelection = _this.evText ? _this.evText : \"\";\n span.html(yrSelection + statesSelection);\n\n\n }", "putTransitiveSelection (originator, dataPoints, color, id) {\n // originator - the originating view for the selection\n // dataPoints - a list containing coordinate {'x': , 'y': } tuples\n // color - an RGB colour used to display this selection\n // id - the selection id in the plot data description\n 'use strict';\n color = typeof color !== 'undefined' ? color : 0x772222;\n let activeSelection = {'originator': originator,\n 'dataPoints': dataPoints,\n 'color': color,\n 'selectionId': id};\n // add the selection\n this.notify({'type':'dyna', 'op':'transitive', 'sel': activeSelection, 'id': id});\n }", "function update(){\n\tvar el=document.getElementById('content');\n\tvar savedSel = saveSelection(el);\n\tdocument.getElementById(\"content\").innerHTML=''+wave.getState().get(\"content\");\n\trestoreSelection(el, savedSel);\n}", "function animateEntities() {\n Object.keys(entities).map(function(uuid) {\n var entity = entities[uuid]\n if (entity.update && entity.state === 'active') {\n triggerEntityUpdate(entity)\n }\n })\n setTimeout(animateEntities,500)\n }", "_nodeStateChange(type) {\n if (this._renderData) {\n this.markForUpdateRenderData();\n }\n\n for (const child of this.node.children) {\n const renderComp = child.getComponent(UIRenderable);\n\n if (renderComp) {\n renderComp.markForUpdateRenderData();\n }\n }\n }", "function setScene2() {\n\n // swap scales\n xScales.domain(xOverview);\n yScales.domain(yS2); // number too large for individual products\n\n d3.selectAll(\".slide-info\")\n .attr(\"class\", \"slide-info inactive\");\n\n d3.selectAll(\"#slide2-1\")\n .attr(\"class\", \"slide-info\");\n\n d3.selectAll(\"#slide2-2\")\n .attr(\"class\", \"slide-info\");\n\n d3.selectAll(\".scene1\")\n .transition()\n .duration(800)\n .style(\"opacity\", 0)\n .transition()\n .style(\"visibility\", \"hidden\");\n\n d3.selectAll(\".scene3\")\n .transition()\n .duration(800)\n .style(\"opacity\", 0)\n .transition()\n .style(\"visibility\", \"hidden\");\n\n\n d3.selectAll(\".scene2\")\n .transition()\n .style(\"visibility\", \"visible\")\n .transition()\n .style(\"opacity\", 1)\n .duration(800);\n\n\n d3.selectAll(\".scene2\").selectAll(\".line.imports\")\n .transition()\n .duration(800)\n .attr('d', importsLine);\n\n d3.selectAll(\".scene2\").selectAll(\".line.exports\")\n .transition()\n .duration(800)\n .attr('d', exportsLine);\n\n\n\n d3.select(\"#selectButton\")\n .style(\"visibility\", \"visible\");\n\n}", "change_properties() {\n\t\t// The currently selected object:\n\n\t\tthis.currently_selected_entity.collision_box.x = parseInt(EZGUI.components.entity_change_x_value.text);\n\t\tthis.currently_selected_entity.collision_box.y = parseInt(EZGUI.components.entity_change_y_value.text);\n\t\tvar given_width = parseInt(EZGUI.components.entity_change_width_value.text);\n\t\tvar given_height = parseInt(EZGUI.components.entity_change_height_value.text); \n\t\tthis.currently_selected_entity.collision_box.width = given_width;\n\t\tthis.currently_selected_entity.collision_box.height = given_height;\n\t\tthis.currently_selected_entity.id = EZGUI.components.entity_change_id_value.text;\n\n\t\t// modify the sprite scaling based on this:\n\n\t\t// have they changed the image?\n\t\tvar selected_path =EZGUI.components.entity_change_sprite_path_value.text;\n\t\tvar sprite = this.currently_selected_entity.sprite;\n\t\tvar platform_sprite;\n\t\tvar scale_x, scale_y;\n\t\tif ( this.currently_selected_entity.image_path === EZGUI.components.entity_change_sprite_path_value.text)\n\t\t{\n\t\t\tscale_x = given_width / sprite.texture.width;\n\t\t\tscale_y = given_height / sprite.texture.height;\n\t\t} \n\t\telse \n\t\t{\n\t\t\t// they changed the image\n\t\t\tsprite = new PIXI.Sprite( PIXI.loader.resources[selected_path].texture);\n\t\t\tthis.currently_selected_entity.sprite = sprite;\t\n\t\t\tthis.currently_selected_entity.image_path = selected_path;\t\n\t\t\tscale_x = given_width / sprite.texture.width;\n\t\t\tscale_y = given_height / sprite.texture.height;\n\t\t}\n\n\t\t// find the proportions necessary to scale the sprite to the given widht/height\n\t\tsprite.scale.set(scale_x, scale_y);\n\n\n\t}", "function toggleHighlighted() {\n if (scene.config.layers.justice_locations.highlightedIcons.visible == true) {\n //show all others and hide highlighted\n scene.config.layers.justice_locations.legalIcons.visible = true;\n scene.config.layers.justice_locations.enforcementIcons.visible = true;\n scene.config.layers.justice_locations.courtsIcons.visible = true;\n scene.config.layers.justice_locations.confinementIcons.visible = true;\n scene.config.layers.justice_locations.alternativesIcons.visible = true;\n scene.config.layers.justice_locations.supportIcons.visible = true;\n scene.config.layers.justice_locations.highlightedIcons.visible = false;\n\n } else {\n // hide all else and show highlighted\n scene.config.layers.justice_locations.legalIcons.visible = false;\n scene.config.layers.justice_locations.enforcementIcons.visible = false;\n scene.config.layers.justice_locations.courtsIcons.visible = false;\n scene.config.layers.justice_locations.confinementIcons.visible = false;\n scene.config.layers.justice_locations.alternativesIcons.visible = false;\n scene.config.layers.justice_locations.supportIcons.visible = false;\n scene.config.layers.justice_locations.highlightedIcons.visible = true;\n\n }\n scene.updateConfig();\n}", "function upObj() {\n\t\t\tvar selectOb = canvas.getActiveObject();\n\t\t\tcanvas.bringForward(selectOb).renderAll();\t\n\t\t}", "computeVariant (draw) {\n // Factors that determine a unique mesh rendering variant\n const selection = (draw.interactive ? 1 : 0); // whether feature has interactivity\n const normal = (draw.extrude != null ? 1 : 0); // whether feature has extrusion (need per-vertex normals)\n const texcoords = (this.texcoords ? 1 : 0); // whether feature has texture UVs\n const blend_order = this.getBlendOrderForDraw(draw);\n const key = [selection, normal, texcoords, blend_order].join('/');\n draw.variant = key;\n\n if (this.variants[key] == null) {\n this.variants[key] = {\n key,\n blend_order,\n mesh_order: 0,\n selection,\n normal,\n texcoords\n };\n }\n }", "draw(givenStage){\n\n //old code for textures\n /* noFill();\n noStroke();\n textureWrap(CLAMP);\n if(this.getSelected()){\n texture(VERTEX_TEXTURE_SEL);\n }\n else{\n texture(VERTEX_TEXTURE);\n } */\n\n push();\n translate(this.getX(), this.getY()); //go to the position\n\n noFill();\n\n if(this.getSelected()){\n stroke(VERT_YELLOW); //yellow\n }\n else if((this.burned != null) && this.burned[givenStage]){ //this is reserved for the burning stage!\n stroke(VERT_RED); //red\n }\n else{\n stroke(VERT_GREEN); //green\n }\n\n strokeWeight(VERTEX_WEIGHT);\n\n ellipse(CENTER,CENTER,VERT_RAD);\n pop();\n }", "function setSelectionsFromSlotValue() {\n\t\t//$log.log(preDebugMsg + \"setSelectionsFromSlotValue\");\n\t\tvar slotSelections = $scope.gimme(\"InternalSelections\");\n\t\tif(typeof slotSelections === 'string') {\n\t\t\tslotSelections = JSON.parse(slotSelections);\n\t\t}\n\n\t\tif(JSON.stringify(slotSelections) == JSON.stringify(internalSelectionsInternallySetTo)) {\n\t\t\t// $log.log(preDebugMsg + \"setSelectionsFromSlotValue got identical value\");\n\t\t\treturn;\n\t\t}\n\n\t\tif(slotSelections && slotSelections.length >= 3) {\n\t\t\tvar newSelections = [];\n\t\t\tfor(var d = 0; d < 3; d++) {\n\t\t\t\tnewSelections.push([]);\n\t\t\t}\n\n\t\t\tfor(var d = 0; d < 3; d++) {\n\t\t\t\tfor(var sel = 0; sel < slotSelections[d].selections.length; sel++) {\n\t\t\t\t\tvar newSel = slotSelections[d].selections[sel];\n\t\t\t\t\tnewSelections[slotSelections[d].dim].push(newSel);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor(var d = 0; d < 3; d++) {\n\t\t\t\tif(newSelections[d].length <= 0) {\n\t\t\t\t\tnewSelections[d].push({\"minVal\":0, \"maxVal\":dim[d] - 1});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(newSelections.length <= 0) {\n\t\t\t\tselectAll();\n\t\t\t} else {\n\t\t\t\tselections = newSelections;\n\t\t\t\tupdateLocalSelections(false);\n\t\t\t\tdrawSelections();\n\t\t\t}\n\t\t}\n\n\t\tsaveSelectionsInSlot();\n\t}", "function updateSelection(editorState, selection, forceSelection) {\n return EditorState.set(editorState, {\n selection: selection,\n forceSelection: forceSelection,\n nativelyRenderedContent: null,\n inlineStyleOverride: null\n });\n}", "function updateSelection(editorState, selection, forceSelection) {\n return EditorState.set(editorState, {\n selection: selection,\n forceSelection: forceSelection,\n nativelyRenderedContent: null,\n inlineStyleOverride: null\n });\n}" ]
[ "0.6264448", "0.6035584", "0.6006884", "0.5998101", "0.59950674", "0.59950674", "0.5933034", "0.5927648", "0.58956325", "0.58551466", "0.58531266", "0.58335435", "0.5807125", "0.57960033", "0.5748867", "0.5742959", "0.5739818", "0.5736569", "0.5704179", "0.5704048", "0.570345", "0.5702642", "0.5652264", "0.56438714", "0.561828", "0.5617281", "0.5587729", "0.5571915", "0.5571915", "0.5571915", "0.5571915", "0.5565058", "0.555605", "0.55545825", "0.5537491", "0.5536677", "0.55274117", "0.5518405", "0.5508223", "0.5484907", "0.5482573", "0.5482573", "0.54757535", "0.5465156", "0.54598105", "0.54440403", "0.5442896", "0.54288054", "0.5427109", "0.54254985", "0.54249525", "0.54108477", "0.5398484", "0.53960264", "0.53960264", "0.53960264", "0.53897697", "0.5387381", "0.5380818", "0.5371991", "0.5361707", "0.53457654", "0.534397", "0.53316784", "0.5322785", "0.5317562", "0.53170294", "0.53122634", "0.53118354", "0.5310711", "0.5309411", "0.5308138", "0.530768", "0.53071374", "0.5300845", "0.52889115", "0.5287355", "0.52866787", "0.5272355", "0.52615976", "0.52600765", "0.5259024", "0.52520305", "0.525014", "0.5248894", "0.5241217", "0.524006", "0.52355826", "0.5232338", "0.5232102", "0.522672", "0.52245384", "0.5199629", "0.51973045", "0.51948094", "0.51907414", "0.5188286", "0.5187468", "0.5184736", "0.5183625", "0.5183625" ]
0.0
-1
define our controller actions (functions) AKA router middleware
function index(req, res) { res.render('index'); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function set_routes() {\n\n // Check your current user and roles\n app.get( '/status/:id', function( request, response ) {\n acl.userRoles( request.params.id || false, function( error, roles ){\n response.json( {'User': request.user ,\"Roles\": roles });\n });\n });\n\n // Only for users and higher\n app.all( '/secret', [ acl.middleware( 1, get_user_id) ],function( request, response ) {\n\n response.send( 'Welcome Sir!' +request.params.id);\n }\n );\n\tapp.use('/user',require('./routers/userR.js'));\n app.use('/event',require('./routers/eventR.js'));\n //accept error\n app.use(acl.middleware.errorHandler('json')); \n \n}", "defineAction(middleware) {\n this.action = middleware;\n }", "defineRoutes() {\n super.defineRoutes();\n this._router.post(this._resourceName + '/login', (req, res, next) => this.login(req, res, next));\n }", "function Controller() {\n // route data members\n this.middlewares = [];\n this.userTypes = [];\n this.permissions = [];\n this.isPublic = false;\n this.accepts = {};\n this.config = {};\n}", "function initController(app) {\n app.use(\n router((_) => {\n _.get('/', indexController.actionIndex);\n _.get('/api/getBooksList', apiController.actionBooksList);\n _.get('/books/list', booksController.actionBooksList);\n _.get('/books/create', booksController.actionBooksCreate);\n // app.use(router.routes()).use(router.allowedMethods());\n })\n );\n}", "function middleware(request, response, next) {}", "rest(...args) {\n if (!_.isString(args[0])) {\n throw new Error('first argument of router.rest must be string');\n } \n const url = args[0];\n const controllers = args[args.length - 1];\n if (!_.isObject(controllers)) {\n throw new Error('need rest controllers');\n }\n const middlewares = args.slice(1, args.length - 1);\n if (controllers.list) {\n this.get(url, ...middlewares.map(m => _.isObject(m) ? m.list : m).filter(m => !!m).concat(controllers.list));\n }\n if (controllers.create) {\n this.post(url, ...middlewares.map(m => _.isObject(m) ? m.create : m).filter(m => !!m).concat(controllers.create));\t\t\t\n }\n if (controllers.update) {\n this.put(path.join(url, ':id'), ...middlewares.map(m => _.isObject(m) ? m.update : m).filter(m => !!m).concat(controllers.update));\n }\n if (controllers.remove) {\n this.del(path.join(url, ':id'), ...middlewares.map(m => _.isObject(m) ? m.remove : m).filter(m => !!m).concat(controllers.remove));\t\t\t\n }\n if (controllers.view) {\n this.get(path.join(url, ':id'), ...middlewares.map(m => _.isObject(m) ? m.view : m).filter(m => !!m).concat(controllers.view));\t\t\t\t\t\t\n }\n return this;\n }", "function index(req, res) {\n \n}", "routes() {\n let router = express.Router();\n //palceholder route handler\n router.get('/', (req, res, next) => {\n res.json({\n message: 'Hello World!'\n });\n });\n this.express.use('/', router);\n }", "function dispatch(req, res, next) {\n console.log(util.format('Request received from %s: %s, %s',\n req.ip, req.method, req.url));\n if (argv.a == 'basic') {\n var isAuthorized = (typeof req.headers['authorization'] != 'undefined') && \n check_authorization(req.headers['authorization'].split(' ')[1]);\n console.log('isAuthorized=' + isAuthorized);\n if (!isAuthorized) {\n res.writeHead(401 , {'WWW-Authenticate': 'Basic realm=\"FLM\"'});\n res.end();\n return;\n }\n }\n switch(req.method) {\n case \"GET\":\n if (req.url == '/') {\n req_GetFacList(req, res, next);\n } else\n req_GetFac(req, res, next);\n break;\n case \"POST\":\n if (req.url == '/') {\n req_AddUpdate(req, res, next);\n } else {\n res.type('application/xml');\n res.status(405).send(gen_error('MethodNotAllowed', 'Method not allowed').toString());\n }\n break;\n case \"DELETE\":\n req_Delete(req, res, next);\n break;\n default:\n res.type('application/xml');\n res.status(405).send(gen_error('MethodNotAllowed', 'Method not allowed').toString());\n break;\n }\n}", "routes() {\n this.app.use('/images', express.static('uploads'));\n this.app.use('/users/', userRoutes);\n this.app.use('/tokens/', tokenRoutes);\n this.app.use('/shop/', shopRoutes);\n this.app.use('/products/', productRoutes);\n this.app.use('/order/', orderRoutes);\n this.app.use('/address/', addressRoutes);\n this.app.use(\"/creditCard/\", creditCardRoutes)\n }", "setupRoute(route) {\n let controller = this.controllers[route.controller];\n let action = controller[route.action] || this.defaultAction;\n let authMethod = (req, res, next) => {\n return next();\n };\n if (route.authentication && route.authentication.controller && route.authentication.action) {\n authMethod = this.controllers[route.authentication.controller][route.authentication.action]();\n }\n this.router[route.method](route.url, authMethod, (req, res) => {\n let values = route.method === 'get' ? req.query : req.body;\n const validator = new Validator_1.default(route.params, Object.assign({}, values, req.files));\n validator.addCustomTypes(this.customTypes);\n try {\n if (validator.isValid() === false) {\n const errorMessage = `This request failed validation, please check the documentation for ${route.method.toUpperCase()} ${route.url}`;\n const err = new ErrorResponse_1.ErrorResponse({ req, res, errorMessage, errors: validator.getErrors(), status: 400 });\n return err.send();\n }\n }\n catch (e) {\n const errorMessage = e.message;\n const errors = [\n `Invalid route definition for ${route.method.toUpperCase()} ${route.url}`\n ];\n const err = new ErrorResponse_1.ErrorResponse({ req, res, errorMessage, errors, status: 501 });\n return err.send();\n }\n values = Object.assign(validator.values, req.params);\n let routeHandler;\n // streaming route\n if (route.streaming === true) {\n routeHandler = new StreamingRouteHandler_1.StreamingRouteHandler(values, action, req, res);\n }\n else {\n routeHandler = new DefaultRouteHandler_1.DefaultRouteHandler(values, action, req, res);\n }\n // handle route\n routeHandler.handle();\n });\n }", "run (req, res, next) {}", "function addRoutes(app) {\n\n app.all('*', (req, res, next) => {\n console.log(req.method + ' ' + req.url);\n next();\n });\n\n //register users\n /*\n param 1: api endpong\n param 2: middleware that uses a controller function \n */\n app.post('/api/register', authController.register);\n\n //login users\n /*\n param 1: api endpoint\n param 2: middleware that uses a controller function \n */\n app.post('/api/login', authController.login);\n\n app.post('/api/account-activate', authController.accountActivate);\n app.post('/api/resend-activation-link', authController.resendActivationLink);\n app.post('/api/reset-password-link', authController.resetPasswordLink);\n app.post('/api/reset-password', authController.resetPassword);\n\n //authorize your user - check that the user sending requests to server is authorized to view this route\n\n /*\n summary of this route:\n 1. call route\n 2. run first middleware, checkAuth \n - checkAuth uses the jwtAuth strategy defined in lib/passport.js\n - remember that this jwt auth strategy compares the JWT token saved to the client, \n either stored in a cookie or sent via an Authorization Header, \n with the JWT token that was created when the user logged in.\n - checkAuth, if successful, returns the user object from the DB\n 3. run second middleware, authController.testAuth\n - returns a {isLoggedIn: true/false} based on whether or not previous middleware\n successfully returned a user object\n */\n app.get('/api/test-auth', checkAuth, authController.testAuth);\n //if you ahve other protected routes, you can use the same middleware,\n //e.g: app.get('/api/protected-route', checkAuth, authController.testAuth);\n //e.g: app.get('/api/another-protected-route', checkAuth, authController.testAuth);\n\n}", "get routes(){\n\t\treturn {\n\t\t\t'get /': [actionFilter, 'index'],\n\t\t\t'get /home/about': 'about'\n\t\t}\n\t}", "init() {\n this.router.post('/generate', (request, response, next) => {\n this.generateKeys(request, response, next);\n });\n this.router.get('/keys/:platform', (request, response, next) => {\n this.getKeys(request, response, next);\n });\n this.router.get('/validate', (request, response, next) => {\n this.validate(request, response, next);\n });\n this.router.get('/platforms', (request, response, next) => {\n this.getStatus(request, response, next);\n });\n // TODO: chenge post to delete\n this.router.delete('/delete', (request, response, next) => {\n this.deleteKey(request, response, next);\n });\n this.router.put('/status', (request, response, next) => {\n this.updateStatus(request, response, next);\n });\n }", "applyMiddleware() {\n //Allows the server to parse json\n this.expressApp.use(bodyParser.json())\n\n //Registers the routes used by the app\n new Routes(this.expressApp)\n }", "init(): void {\n this.router.post('/progress/:taskUUID/:progress', this.dispatchProgress);\n this.router.post('/message/:taskUUID', this.dispatchMessages);\n this.router.post('/prompt/:taskUUID/:type', this.dispatchWithResponsePrompt);\n this.router.post('/manageTasks/:taskUUID', this.dispatchManageTasks);\n }", "routing () {\n const notConnected = this.app.session.notConnected.bind(this.app.session)\n const connected = this.app.session.connected.bind(this.app.session)\n const connectedOrBuilder = this.app.session.connectedOrBuilder.bind(this.app.session)\n const admin = this.app.session.admin.bind(this.app.session)\n\n this.app.express.use('/api', express.Router()\n .post('/auth/login', notConnected, this.app.action.auth.login.routes)\n .post('/auth/forgot', notConnected, this.app.action.auth.forgotPassword.routes)\n .put('/auth/reset', notConnected, this.app.action.auth.resetPassword.routes)\n\n .delete('/auth/logout', connected, this.app.action.auth.logout.routes)\n\n .use('/invite', express.Router()\n .post('/', connected, admin, this.app.action.invitation.create.routes)\n )\n .use('/user', express.Router()\n .post('/', notConnected, this.app.action.user.create.routes)\n .get('/:id', connected, this.app.action.user.get.routes)\n .get('/', connected, this.app.action.user.list.routes)\n )\n .use('/manifest', express.Router()\n .post('/', connected, this.app.action.manifest.create.routes)\n .put('/:id', connected, this.app.action.manifest.update.routes)\n .put('/:id/maintainer', connected, admin, this.app.action.manifest.updateMaintainer.routes)\n .get('/:id', connectedOrBuilder, this.app.action.manifest.get.routes)\n .get('/', connected, this.app.action.manifest.list.routes)\n )\n .use('/build', express.Router()\n .post('/', connected, this.app.action.build.create.routes)\n .use('/:id', express.Router({ mergeParams: true })\n .get('/', connected, this.app.action.build.get.routes)\n\n // Middleware to authorize only builder\n .use('/', this.app.action.build.authorization.routes)\n // Empty endpoint for a client to verify his access\n .put('/', (req, res, next) => { res.json({}) })\n .put('/start', this.app.action.build.start.routes)\n .put('/stdout', this.app.action.build.stdout.routes)\n .put('/stderr', this.app.action.build.stderr.routes)\n .put('/end', this.app.action.build.end.routes)\n .put('/packages', this.app.action.build.packages.routes)\n )\n .get('/', connected, this.app.action.build.list.routes)\n )\n )\n\n this.app.express.use(this.errorHandler.bind(this))\n }", "dispatcher(req, res)\n {\n this.runPreDispatchHooks(req, res);\n\n // TODO: run middlewares arranged by priorities\n // TODO: instantiate request and response singletones\n // TODO: check what URL and other request information\n // TODO: find Bundle-Controller-Action situated for request\n // TODO: if not found Bundle-Controller-Action then show 404 page\n res.statusCode = 200;\n res.setHeader('Content-Type', 'text/plain');\n res.end('Hello World\\n');\n\n // TODO: post-dispatch hook\n }", "indexAction(req, res) {\n this.jsonResponse(res, 200, { 'message': 'Default API route!' });\n }", "doRoute() {\n let routename = 'HTTP:' + this.request.method + ':' + this.url.pathname;\n this.run(routename, this.restnio.routes, \n Parser.parseFullHttpParams, this.request, this.url);\n }", "init() {\n this.router.get(\"/\", (req, res, next) => {\n res.status(200).json(this._service.defaultMethod());\n });\n }", "function main() {\n\t\n\tdbconnection();\n var app = express(); // Export app for other routes to use\n \n var port = process.env.PORT || 8000;\n app.use(bodyParser.urlencoded({\n extended: true\n }));\n app.use(bodyParser.json());\n // Routes & Handlers\n app.post('/login', Auth);\n\tapp.get('/getCategory/',middleware.checkToken,Category);\n\tapp.get('/deleteCategory/:id',middleware.checkToken,Category);\n\tapp.get('/getParentcategory/:id',middleware.checkToken,Category);\n\tapp.post('/addCategory',middleware.checkToken,Category);\n\t\n\n app.listen(port, function () { return console.log(\"Server is listening on port: \" + port); });\n}", "api () {\r\n const router = new Router()\r\n // READ\r\n router.get('/',\r\n (req, res) => {\r\n this\r\n .getAll(req.query)\r\n .then(this.ok(res))\r\n .then(null, this.fail(res))\r\n })\r\n router.get('/:key',\r\n (req, res) => {\r\n this\r\n .get(req.params.key, req.query)\r\n .then(this.ok(res))\r\n .then(null, this.fail(res))\r\n })\r\n // CREATE\r\n router.post('/',\r\n this.requiretmobileid,\r\n (req, res, next) => this.logUserAction(req, res, next, this.name, 'POST'),\r\n (req, res) => {\r\n this\r\n .post(req.body, req.query)\r\n .then(this.ok(res))\r\n .then(null, this.fail(res))\r\n })\r\n // UPDATE\r\n router.patch('/:key',\r\n this.requiretmobileid,\r\n (req, res, next) => this.logUserAction(req, res, next, this.name, 'PATCH'),\r\n (req, res) => {\r\n this\r\n .patch(req.params.key, req.body, req.query) // query?\r\n .then(this.ok(res))\r\n .then(null, this.fail(res))\r\n })\r\n // DELETE\r\n router.delete('/:key',\r\n this.requiretmobileid,\r\n (req, res, next) => this.logUserAction(req, res, next, this.name, 'DELETE'),\r\n (req, res) => {\r\n this\r\n .delete(req.params.key, req.query)\r\n .then(this.ok(res))\r\n .then(null, this.fail(res))\r\n })\r\n\r\n return router\r\n }", "function pagesController(app) {\n\n //Express routes\n app.get('/pages/my-page', function(req, res) {\n res.send('Got my-page successfully');\n });\n\n}", "function Middleware(app, middleware, action){\n var args;\n action = action || \"invoke\";\n \n if (typeof middleware === 'function')\n {\n switch(middleware.length)\n {\n //fn() with this=app and fn.invoke(next) with this = context\n case 0:\n middleware.call(app);\n return function (context, next) {return middleware.invoke.call(context, next);};\n break;\n \n //fn(next) or fn(app) and fn.invoke(context, next) \n case 1:\n args =private_getParamNames(middleware);\n if (arrayEqual(args,[\"next\"]))\n return function (context, next) { return middleware.call(context, next);}; \n \n else\n {\n var mw = Object.create(middleware.prototype); \n middleware.call(mw, app);\n \n return mw.invoke.bind(mw);\n \n if (typeof mw[action] === 'function')\n return mw[action].bind(mw);\n else\n throw(\"no \" + action +\" function exists on middleware \" + middleware.toString());\n \n }\n \n //fn(req,res) or fn(context, next)\n case 2: \n args =private_getParamNames(middleware);\n if (arrayEqual(args,[\"req\",\"res\"]))\n {\n throw(\"must require 'iopa-connect' to use Connect/Express style middleware\");\n } else\n {\n return middleware;\n }\n \n //fn(req,res,next)\n case 3:\n throw(\"must require 'iopa-connect' to use Connect/Express style middleware\");\n \n //fn(err,req,res,next)\n case 4:\n throw(\"must require 'iopa-connect' to use Connect/Express style middleware\");\n \n default:\n throw(\"unknown middleware\");\n \n }\n }\n else\n {\n app.log.error(\"middleware must be a function\");\n throw(\"middleware must be called on a function\");\n }\n \n}", "middlewares() {\n //directorio publico\n this.app.use(express.static('public'));\n\n //convertir los datos que llegan en json\n this.app.use(express.json());\n }", "connectRouter(router) {\n // Get all objects\n router.get('/', (req, res) => {\n this.getAll(req, res);\n });\n\n // Post new object\n router.post('/', (req, res) => {\n this.createOne(req, res);\n });\n\n // Get specific object\n router.get(`/:id(${this.validationRegex})`, (req, res) => {\n this.getOne(req, res);\n });\n\n // Edit specific object\n router.put(`/:id(${this.validationRegex})`, (req, res) => {\n this.updateOne(req, res);\n });\n\n // Delete specific object\n router.delete(`/:id(${this.validationRegex})`, (req, res) => {\n this.deleteOne(req, res);\n });\n }", "middleware(req, res, next) {\n this.tokens.push({ method: req.method, at: Date.now() });\n this.handleLimiting(req, res, next, this.tokens);\n }", "routes() {\n this.app.use(index_routes_1.default);\n this.app.use('/api/photos', photos_routes_1.default);\n this.app.use('/api/users', users_routes_1.default);\n }", "function my_middleware(req, res, next){\n\tconsole.log('Hello Middleware');\n\tnext();\n}", "protect(callback) {\n // if the callback isn't defined default to one which just makes sure \n // someone is logged in.\n let middleware = callback ? callback : (request, response, next) => {\n if (!request.isAuthenticated())\n return response.redirect('/login');\n \n return next();\n }\n // get local this because of fucked up scope.\n let that = this;\n return {\n get(path, method) {\n that.router.get(path, method, middleware);\n },\n post(path, method) {\n that.router.post(path, method, middleware);\n },\n put(path, method) {\n that.router.put(path, method, middleware);\n },\n delete(path, method) {\n that.router.delete(path, method, middleware);\n }\n }\n }", "init() {\n this.router.post('/', this.extract);\n this.router.post('/verify', this.verify);\n }", "setupAppMiddleware() {\n\t\t// small security protections by adjusting request headers\n\t\tthis.app.use(helmet());\n\n\t\t// adding the request's client ip\n\t\tthis.app.use(requestIp.mw());\n\n\t\tif(Config.isDev) {\n\t\t\t// Log requests in the console in dev mode\n\t\t\tthis.app.use(morgan('dev'));\n\t\t}\n\t\telse {\n\t\t\t// Compress responses in prod mode\n\t\t\tthis.app.use(compression());\n\t\t}\n\n\t\t// decode json-body requests\n\t\tthis.app.use(bodyParser.json());\n\n\t\t// TODO: Move mongo sanitation to save actions\n\t\t// sanitizing request data for mongo-injection attacks\n\t\tthis.app.use(mongoSanitize());\n\n\t\t// any internal data that is needed to be attached to the request must be attached to the \"internalAppVars\" object\n\t\tthis.app.use((req, res, next) => {\n\t\t\treq.internalAppVars = {};\n\t\t\tnext();\n\t\t});\n\t}", "initRoutes() {\n this.app.get(\n `${this.apiBasePath}/person/:personId/appearances`,\n (req, res, next) => {\n personController.getAppearances(req, res, next);\n },\n );\n\n this.app.get(\n `${this.apiBasePath}/person/:personId/movies`,\n (req, res, next) => {\n personController.getMovieAppearances(req, res, next);\n },\n );\n\n this.app.get(\n `${this.apiBasePath}/person/:personId/tv`,\n (req, res, next) => {\n personController.getTvAppearances(req, res, next);\n },\n );\n }", "function UserController() {}", "constructor() {\n this.router = express.Router();\n this.initControllers();\n }", "static requestHandler() {\n\n var driver = config.Driver.make(this);\n\n driver.parseRoutes();\n return driver.requestHandler();\n }", "function middleware(req, res, next) {\n\tns.run(() => next());\n}", "function dummyController(req, res) {\n res.send(taqueria);\n}", "function userRoutes() {\n return (open, closed) => {\n closed.route('/get-meta-data/module/:moduleName/screen/:screenName').get(\n joiGetSpecifications, // joi validation\n ctrl.getFileDynamically // controller function \n );\n };\n}", "constructor(pluginHandler) {\n this.jwtAlg = \"HS256\";\n this.passwordLengthMin = 8;\n this.pagination = 30;\n this.userEditors = [\n 'superAdmin',\n 'admin',\n ];\n\n this.userViewers = [\n 'superAdmin',\n 'admin',\n 'editor',\n ];\n\n if (pluginHandler instanceof PluginHandler) {\n this.pluginHandler = pluginHandler;\n } else {\n this.pluginHandler = new PluginHandler();\n }\n\n const additionalUserRoles = {};\n\n this.pluginHandler.runLifecycleHook(\"additionalUserRoles\", {\n additionalUserRoles,\n });\n\n this.additionalUserRoles = additionalUserRoles;\n\n this.router = router;\n\n // We don't pass the methods as variables because we still need to access the variables of\n // the UserController object. If we were to pass the methods as variables, the scope would\n // change and the UserController variables would be inaccessible.\n this.router.post('/login', (req, res) => { this.authenticateUserCredentials(req, res); });\n this.router.post('/add-user', errorIfTokenDoesNotExist, (req, res, next) => { this.addUser(req, res, next); });\n this.router.post('/edit-user', errorIfTokenDoesNotExist, (req, res, next) => { this.editUser(req, res, next); });\n this.router.post('/delete-user', errorIfTokenDoesNotExist, (req, res, next) => { this.deleteUser(req, res, next); });\n\n this.router.get('/get-user/:id', errorIfTokenDoesNotExist, (req, res, next) => { this.getUser(req, res, next); });\n this.router.get('/all-users/:page*?', errorIfTokenDoesNotExist, (req, res, next) => { this.getAllUsers(req, res, next); });\n this.router.get('/get-user-types', errorIfTokenDoesNotExist, (req, res, next) => { this.getUserTypes(req, res, next); });\n }", "viewRoute() {\n\n this.router.use(auth.isLoggedIn());\n \n this.router.get('/signup', signup);\n this.router.get('/login', login);\n this.router.get('/forgot-password', forgotPassword);\n this.router.get('/reset-password', resetPassword);\n this.router.get('/forgot-password/success', forgotPasswordSuccess);\n this.router.get('/team', team);\n this.router.get('/volunteer', volunteer);\n this.router.get('/', home);\n this.router.get('/about-us', about);\n this.router.post('/', (req, res, next) => (req.page='home', next()), home);\n\n \n this.router.get(\n '/donor',\n auth.authenticateApp(),\n auth.authorizeApp('donor'),\n (req, res, next) => res.redirect('/donor/dashboard')\n );\n \n this.router\n .get(\n '/donor/dashboard',\n auth.authenticateApp(),\n auth.authorizeApp('donor'),\n (req, res, next) => ((req.page = 'dashboard'), next()),\n donorDashboard\n );\n \n this.router\n .get(\n '/donor/donations',\n auth.authenticateApp(),\n auth.authorizeApp('donor'),\n (req, res, next) => ((req.page = 'donations'), next()),\n donorDashboard\n );\n \n this.router\n .get(\n '/donor/donations/verify',\n auth.authenticateApp(),\n auth.authorizeApp('donor'),\n verifyMonetaryDonation\n )\n \n return this.router;\n}", "handleActions(action) {\n // it is check by a switch and will have a type that id it\n switch(action.type) {\n // call a function\n case 'GET_ALL': {\n this.getAll();\n }\n }\n }", "function AuthController() {\n\n /*\n * get the user id for given token\n */\n this.getId = function (token, res, callback) {\n return queryManager.callFileManagerQuery({\n type: queryManager.callingType.select,\n statement: 'CALL `spGetUserToken` ( \"' + token + '\" ,@userID , @role); Select @userID as user_id, @user_role as user_role'\n }, function (response) {\n if(response.status == 500) {\n return unSuccess(res);\n }\n return callback(response[1][0]);\n })\n }\n\n /*\n * Access denied message\n */\n this.AccessDeniedMessage = function (res) {\n res.write(JSON.stringify({\n status: 401,\n message: 'Access denied. Invalid Token'\n }));\n res.send();\n }\n\n /*\n * Unauthorized access\n */\n this.unAuthorizedAccess = function (res) {\n res.writeHead(401, {\"Content-Type\": \"application/json\"});\n res.write(JSON.stringify({\n status: 401,\n message: 'Unauthorized',\n }));\n res.send();\n }\n\n /*\n * not available resources in file manager\n */\n this.notAvailable = function (res) {\n res.write(JSON.stringify({\n status: 401,\n message: 'Access denied or invalid resource id'\n }));\n res.send();\n }\n\n /*\n * upload file sucessfully\n */\n this.Success = function (res) {\n res.write(JSON.stringify({\n status: 200,\n message: 'Successfully uploaded'\n }));\n res.send();\n }\n\n /*\n * upload file unsucessfull\n */\n function unSuccess(res) {\n res.write(JSON.stringify({\n status: 500,\n message: 'Server error'\n }));\n res.send();\n }\n\n /*\n * invalid file format or not found\n */\n\n this.invalidFormat = function (res) {\n res.write(JSON.stringify({\n status: 402,\n message: 'File format is invalid or file not selected'\n }));\n res.send();\n }\n\n /*\n * data not found\n */\n this.nullData = function (res) {\n res.write(JSON.stringify({\n status: 404,\n message: 'Data cannot be found'\n }));\n res.send();\n }\n}", "constructor() {\n this.app = express();\n this.setupControllers();\n this.middleware();\n }", "setupRoutes() {\n let expressRouter = express.Router();\n\n for (let route of this.router) {\n let methods;\n let middleware;\n if (typeof route[1] === 'string') {\n methods = route[1].toLowerCase().split(',');\n middleware = route.slice(2);\n } else {\n methods = ['get'];\n middleware = route.slice(1);\n }\n for (let method of methods) {\n expressRouter[method.trim()](route[0], middleware.map(this.errorWrapper));\n }\n }\n this.app.use(this.config.mountPoint, expressRouter);\n }", "route() {\n this.router\n .route('/:id/accounts')\n .get(validateToken, verifyIsClient, this.userController.getAccounts)\n .post(\n validateToken,\n verifyIsClient,\n createAccountValidator,\n validate,\n this.userController.createAccount,\n );\n\n this.router\n .route('/:id/accounts/:accountNumber/transactions')\n .get(validateToken, verifyIsClient, this.userController.accountHistory);\n\n this.router\n .route('/:id/transactions/:transId')\n .get(validateToken, verifyIsClient, this.userController.specificTranHist);\n\n this.router\n .route('/:id/accounts/:accountNumber')\n .get(validateToken, verifyIsClient, this.userController.specAcctDetails);\n\n this.router\n .route('/:id/confirmEmail/:token')\n .get(\n setHeadersparams2,\n validateToken,\n verifyIsClient,\n this.userController.confirmEmail,\n );\n\n this.router\n .route('/:id/changePassword')\n .patch(\n validateToken,\n verifyIsClient,\n changePasswordValidator,\n validate,\n this.userController.changePassword,\n );\n\n this.router\n .route('/:id/transactions/:accountNumber/transfer')\n .post(\n validateToken,\n verifyIsClient,\n transferFundValidator,\n validate,\n this.userController.transferFunds,\n );\n\n this.router\n .route('/:id/transactions/:accountNumber/airtime')\n .post(\n validateToken,\n verifyIsClient,\n airtimeValidator,\n validate,\n this.userController.buyAirtime,\n this.staffController.debitAccount,\n );\n\n this.router\n .route('/:id/upload')\n .post(upload.single('passport'), this.userController.uploadPassport);\n\n return this.router;\n }", "executeMiddlewares(ctx, route) {\n this.MiddlewareHandler._executeMiddlewares(ctx, route)\n }", "defaultAction(req, res, callback) {\n return callback(\"Invalid action\");\n }", "handle(...args) {\n if (args.length < 3) {\n return new Response('internal server error', { status: 500 })\n }\n\n const method = args.shift();\n const pathRegexp = args.shift();\n let handler = args.pop();\n\n this.routes.push({\n method,\n pathRegexp,\n handler\n })\n\n return this\n }", "init() {\n this.router.post('/general', this.updateGeneralSettings);\n this.router.get('/general', this.getGeneralSettings);\n this.router.get('/version', this.getVersion);\n }", "function create(){\n \n var routes = {};\n \n function addRoute(name, method, pattern, handler) {\n if (typeof pattern === 'string') {\n pattern = new RegExp(\"^\" + pattern + \"$\");\n }\n \n var route = {\n name: name, \n method: method,\n pattern: pattern,\n handler: handler,\n plugins:{before:[], after:[]},\n //helpers :{} // delete TODO\n };\n \n routes[name] = route;\n return route;\n }\n \n // get the roote and save the match in response object\n function doRoute(req, context) {\n var uri = url_parse(req.url);\n var path = uri.pathname;\n for (var routeName in routes) {\n var route = routes[routeName];\n if (req.method === route.method) {\n var match = path.match(route.pattern);\n if (match && match[0].length > 0) {\n // TODO named properties params in response como query string\n context.response.matches = match;\n return route;\n }\n }\n }\n \n return false;\n }\n\n // add plugin to handler\n function addPlugin (){\n var args = Array.prototype.slice.call(arguments);\n var firstArg = args.shift(); \n if (typeof firstArg === 'string') {\n var route = routes[firstArg];\n } else {\n var route = firstArg; // Object\n }\n \n var hook = 'before';\n \n var last = args[args.length-1];\n if (typeof last === 'string'){\n args.pop();\n if(last === 'after' ){\n hook = 'after';\n }\n } \n \n if (hook === 'after'){\n Array.prototype.push.apply(route.plugins.after, args);\n } else {\n Array.prototype.push.apply(route.plugins.before, args);\n } \n }\n \n // application (router) Scope\n var modulePrototypesContainer = {\n modules : []\n }\n\n function addModule(rte, module){\n //var args = Array.prototype.slice.call(arguments);\n if (typeof rte === 'string') {\n var rte = routes[rte];\n }\n // plugins\n Array.prototype.push.apply(rte.plugins.after, module.after);\n Array.prototype.push.apply(rte.plugins.before, module.before);\n // helpers\n addHelpers(module, modulePrototypesContainer);\n }\n\n function createContext(req, res){\n var context = {};\n modulePrototypesContainer.modules.forEach(function(moduleName){\n var obj = Object.create(modulePrototypesContainer[moduleName]);\n obj.request = req;\n obj.response = res;\n context[moduleName] = obj;\n });\n\n context.request = req;\n context.response = res;\n return context;\n }\n\n function createChain(route){\n var beforeFuncs = route.plugins.before || [];\n var afterFuncs = route.plugins.after || [];\n var beforeAllFuncs = routes[ALLROUTES_CHAIN].plugins.before || [];\n var afterAllFuncs = routes[ALLROUTES_CHAIN].plugins.after || [];\n return [].concat(beforeAllFuncs, beforeFuncs, route.handler, afterFuncs, afterAllFuncs);\n \n }\n \n return {\n routes : routes,\n addRoute: addRoute,\n doRoute: doRoute,\n addPlugin: addPlugin,\n addModule: addModule,\n createChain: createChain,\n createContext: createContext,\n modulePrototypesContainer: modulePrototypesContainer,\n ALLROUTES_CHAIN : ALLROUTES_CHAIN\n\n };\n}", "function onRequest() {\n\n // sets the actually resolved action, as it is also set by notfound\n req.data.action = req.action;\n \n if (req.action != 'notfound') {\n // let soft-coded actions override\n var idempotentAction = req.action +'_'+ req.method.toLowerCase();\n var action = (this.actions[idempotentAction] || this.actions[req.action]);\n \n if (action) {\n action.call(this);\n res.stop();\n }\n }\n}", "routes() {\n this.app.use('/api/usuarios', require('../routes/usuarios'));\n }", "routes() {\n this.app.use('/api/usuarios', require('../routes/usuarios'));\n }", "serve() {\n return function (req, res, next) {\n next();\n };\n }", "function log(req,res,next){\n\n // console.log('hello osho middleware function is running');\n next();// next function helps to change in req,res cycle\n}", "function setPrivateRoutes() {\n\n // PUT routes\n _app.put('/user-admin', UserAdminCtrl.handleRequest);\n}", "getMiddleware() {\n const router = express.Router();\n router.options(this.path, (request, response, next) => {\n if (!this.handleAbuseProtectionRequests(request, response)) {\n next();\n }\n });\n router.post(this.path, (request, response, next) => __awaiter(this, void 0, void 0, function* () {\n try {\n if (!(yield this._cloudEventsHandler.processRequest(request, response))) {\n next();\n }\n }\n catch (err) {\n next(err);\n }\n }));\n return router;\n }", "function setupRoutes(app, passport) {\n var loginWithLinkedIn = require('./routes/login/login-linkedin');\n var loginWithLGoogle = require('./routes/login/login-google');\n var loginWithLMicrosoft = require('./routes/login/login-microsoft');\n var loginWithPassword = require('./routes/login/login-with-password');\n var getCurrentUser = require('./routes/get-current-user');\n app.use('/login/linkedin', loginWithLinkedIn);\n app.use('/login/google', loginWithLGoogle);\n app.use('/login/microsoft', loginWithLMicrosoft);\n app.use('/technician/login', loginWithPassword);\n app.use('/getCurrentUser', getCurrentUser);\n /* router.get('/', function(req, res, next) {\n res.send('respond with a resource');\n }); */\n\n\n}", "static actionHandler(closure) {\n\n config.actionHandler = closure;\n }", "function Router() {\n return {\n /**\n * navigateToCart - navigate to cart in checkout\n *\n * @param {Object} info - optional info\n * @return {Deferred} promise\n * @api public\n */\n navigateToCart : function(info) {\n info = _.extend({\n route : 'cart'\n }, info);\n return handleAppRoute(info);\n },\n\n /**\n * navigateToCustomer - navigate to customer views\n *\n * @param {Object} info - optional info\n * @return {Deferred} promise\n * @api public\n */\n navigateToCustomer : function(info) {\n info = _.extend({\n route : 'customer'\n }, info);\n return handleAppRoute(info);\n },\n\n /**\n * navigateToCustomerSearchResult - navigate to customer search results\n *\n * @param {Object} info - optional info\n * @return {Deferred} promise\n * @api public\n */\n navigateToCustomerSearchResult : function(info) {\n info = _.extend({\n route : 'customer_search_result'\n }, info);\n return handleAppRoute(info);\n },\n\n /**\n * customerLogout - log out a customer\n *\n * @param {Object} info - optional info\n * @return {Deferred} promise\n * @api public\n */\n customerLogout : function(info) {\n info = _.extend({\n route : 'customer_logout'\n }, info);\n return handleAppRoute(info);\n },\n\n /**\n * presentChangeStorePasswordDrawer - change the store password\n *\n * @param {Object} info - optional info\n * @return {Deferred} promise\n * @api public\n */\n presentChangeStorePasswordDrawer : function(info) {\n info = _.extend({\n route : 'change_store_password'\n }, info);\n return handleAppRoute(info);\n },\n\n /**\n * navigateToHome - navigate to Home\n *\n * @param {Object} info - optional info\n * @return {Deferred} promise\n * @api public\n */\n navigateToHome : function(info) {\n info = _.extend({\n route : 'home'\n }, info);\n\n return handleAppRoute(info);\n },\n\n /**\n * navigateToCategory - navigate to category\n *\n * @param {Object} info - optional info\n * @return {Deferred} promise\n * @api public\n */\n navigateToCategory : function(info) {\n info = _.extend({\n route : 'product_search_result',\n query : ''\n }, info);\n\n return handleAppRoute(info);\n },\n\n /**\n * navigateToProduct - navigate to a product (PDP)\n *\n * @param {Object} info - optional info\n * @return {Deferred} promise\n * @api public\n */\n navigateToProduct : function(info) {\n info = _.extend({\n route : 'product_detail'\n }, info);\n\n return handleAppRoute(info);\n },\n\n /**\n * navigateToProductSearch - navigate to product search results\n *\n * @param {Object} info - optional info\n * @return {Deferred} promise\n * @api public\n */\n navigateToProductSearch : function(info) {\n info = _.extend({\n route : 'product_search_result'\n }, info);\n\n return handleAppRoute(info);\n },\n\n /**\n * navigateToOrderSearchResult - navigate to order search results\n *\n * @param {Object} info - optional info\n * @return {Deferred} promise\n * @api public\n */\n navigateToOrderSearchResult : function(info) {\n info = _.extend({\n route : 'order_search_result'\n }, info);\n\n return handleAppRoute(info);\n },\n\n /**\n * presentAssociateLogin - present associate login\n *\n * @param {Object} info - optional info\n * @return {Deferred} promise\n * @api public\n */\n presentAssociateLogin : function(info) {\n info = _.extend({\n route : 'associate_login'\n }, info);\n return handleAppRoute(info);\n },\n\n /**\n * presentCustomerSearchDrawer - present customer search dialog\n *\n * @param {Object} info - optional info\n * @return {Deferred} promise\n * @api public\n */\n presentCustomerSearchDrawer : function(info) {\n info = _.extend({\n route : 'customer_search'\n }, info);\n return handleAppRoute(info);\n },\n\n /**\n * presentOrderSearchDrawer - present order search dialog\n *\n * @param {Object} info - optional info\n * @return {Deferred} promise\n * @api public\n */\n presentOrderSearchDrawer : function(info) {\n info = _.extend({\n route : 'order_search'\n }, info);\n return handleAppRoute(info);\n },\n\n /**\n * presentProductSearchDrawer - present product search dialog\n *\n * @param {Object} info - optional info\n * @return {Deferred} promise\n * @api public\n */\n presentProductSearchDrawer : function(info) {\n info = _.extend({\n route : 'product_search'\n }, info);\n return handleAppRoute(info);\n },\n\n /**\n * presentPrinterChooserDrawer - present printer chooser dialog\n *\n * @param {Object} info - optional info\n * @return {Deferred} promise\n * @api public\n */\n presentPrinterChooserDrawer : function(info) {\n info = _.extend({\n route : 'printer_chooser'\n }, info);\n return handleAppRoute(info);\n },\n\n /**\n * associateLogout - perform associate logout\n *\n * @param {Object} info - optional info\n * @return {Deferred} promise\n * @api public\n */\n associateLogout : function(info) {\n info = _.extend({\n route : 'associate_logout'\n }, info);\n return handleAppRoute(info);\n },\n\n /**\n * presentCreateAccountDrawer - present create account dialog\n *\n * @param {Object} info - optional info\n * @return {Deferred} promise\n * @api public\n */\n presentCreateAccountDrawer : function(info) {\n info = _.extend({\n route : 'create_account'\n }, info);\n return handleAppRoute(info);\n },\n\n /**\n * checkPaymentDevice - check status of payment device\n *\n * @param {Boolean} verified - if verified\n * @return {Deferred} promise\n * @api public\n */\n checkPaymentDevice : function(verified) {\n return checkPaymentDevice(verified);\n },\n\n /**\n * paymentDeviceConnectionChecked - update device status\n *\n * @param {Boolean} connected - if connected\n * @api public\n */\n paymentDeviceConnectionChecked : function(connected) {\n if (connected != paymentDeviceConnected) {\n paymentDeviceConnected = connected;\n $.header.updateDeviceStatus(false, connected);\n if ($.no_payment_terminal) {\n $.no_payment_terminal.updateDeviceStatus(connected);\n }\n }\n },\n\n /**\n * startup - restart the application\n *\n * @api public\n */\n startup : function() {\n Alloy.eventDispatcher.trigger('app:startup', {\n login : true\n });\n },\n\n /**\n * showActivityIndicator - shows activity indicator until deferred is complete\n *\n * @param {Deferred} deferred\n * @api public\n */\n showActivityIndicator : function(deferred) {\n showActivityIndicator(deferred);\n },\n\n /**\n * showHideHamburgerMenu - show the hamburger menu popover\n *\n * @api public\n */\n showHideHamburgerMenu : function() {\n $.hamburger_menu.showHideHamburgerMenu();\n },\n\n /**\n * hideHamburgerMenu - hide the hamburger menu popover\n *\n * @api public\n */\n hideHamburgerMenu : function() {\n $.hamburger_menu.hideHamburgerMenu();\n },\n\n /**\n * navigate - dynamic routing based on info passed in\n *\n * @param {Object} info - optional info\n * @return {Deferred} promise\n * @api public\n */\n navigate : function(info) {\n // for dynamic routing\n return handleAppRoute(info);\n }\n };\n}", "config() {\n this.router.get('/', domiciliosController_1.domiciliosController.list);\n this.router.get('/:id', domiciliosController_1.domiciliosController.getOne);\n this.router.post('/', domiciliosController_1.domiciliosController.create);\n this.router.delete('/:id', domiciliosController_1.domiciliosController.delete);\n this.router.put('/:id', domiciliosController_1.domiciliosController.update);\n }", "run(req, method) {\n const params = req.query;\n if (method !== undefined) {\n delete params.method;\n }\n else {\n return this._response(this.CODE_METHOD_NOT_FOUND, {\n message: `The method is not exist in the request`,\n });\n }\n if (this.needAuth) {\n const token = this.auth(req);\n if (token === undefined) {\n return this.on(method, req.query, req.body, undefined);\n }\n else {\n Screens.auth(token, (screen) => {\n return this.on(method, req.query, req.body, screen);\n });\n }\n }\n else {\n return this.on(method, req.query, req.body, undefined);\n }\n return this._response(this.CODE_ERROR, {});\n }", "constructor() {\n this.express = express();\n this.middleware();\n this.routes();\n }", "function AboutRoute(db) {\n //var ctrl = new AboutCtrl(db);\n \n return [\n {\n method: 'GET',\n path: '/',\n handler: (request, h) => {\n \n return 'Hello, world!';\n }\n },\n {\n method: 'GET',\n path: '/{name}',\n handler: (request, h) => {\n \n return 'Hello, ' + encodeURIComponent(request.params.name) + '!';\n }\n }\n ];\n}", "function route(req, res, module, app, next) {\n\n // Add dev tools view \n res.menu.admin.addMenuItem({name:'Development',path:'admin/dev',url:'#',description:'Dev tools ...',security:[]});\n res.menu.admin.addMenuItem({name:'Calipso Events',path:'admin/dev/events',url:'/admin/dev/events',description:'View events and event listeners ...',security:[]});\n \n // Router\n module.router.route(req, res, next);\n\n}", "init() {\n this.router.route('/')\n .get(this.getAll)\n .post(this.postHero);\n this.router.route('/:id')\n .get(this.getOne);\n }", "post(...args) {\n this.route('post', ...args);\n }", "function route(connection, data) {\n condHasAttr(connection, data, ['action'], function(conn, data) {\n if (_.has(actions, data.action)) {\n actions[data.action](conn, data);\n } else {\n Connection.notifyError('The action ' +\n util.inspect(data.action) +\n ' is not managed', conn.user);\n }\n });\n}", "function middleware2 (req, res, next) { //please keep in mind that a function name is not needed, also => may be used instead\n res.render (\"index2\");\n}", "constructor() {\n this.express = express(); //THE APP\n this.middleware();\n this.routes();\n }", "constructor() {\n this.express = express(); //THE APP\n this.middleware();\n this.routes();\n }", "static registerLegacyRouteHandler() {}", "function fhmiddleware() {\n var fh = fhMbaasApi.getFhApi();\n return function(req, res, next) {\n var requestTime = new Date().getTime();\n\n // TODO - need to dig into analytics here and find out what exactly funct should be,\n // and possibly replace funct with url in analytics\n var funct = req.url;\n\n // Note we can't peek into the request body for POST/PUT as can can't assume its been unrolled at this stage\n var params = {};\n params = paramsUtils.parseFHParams(req);\n\n params._headers = req.headers;\n params._files = req.files;\n\n var msgParams = params;\n msgParams.ipAddress = getIPofClient(req);\n msgParams.agent = (req.headers && req.headers['user-agent']) ? req.headers['user-agent'] : '-';\n msgParams.funct = funct;\n\n function getIPofClient(req) {\n var ret = \"nonset\"; // default value\n\n if (req.headers && req.headers['x-forwarded-for']) {\n ret = req.headers['x-forwarded-for']; // this may be a comma seperated list of addresses added by proxies and load balancers\n } else if (req.connection && req.connection.remoteAddress) {\n ret = req.connection.remoteAddress;\n }\n return ret;\n }\n\n // check secure endpoints\n req.pause();\n authentication(req, res, params).authenticate(funct, function(err) {\n req.resume();\n\n if (err) {\n res.writeHead(err.code, {\n \"Cache-Control\": \"no-cache\",\n \"Content-Type\": \"application/json\"\n });\n return res.end(JSON.stringify(err));\n }\n\n\n res.on('finish', function() {\n sendReport();\n });\n\n function sendReport() {\n var responseTime = new Date().getTime();\n msgParams.status = res.statusCode || 200;\n msgParams.time = (responseTime - requestTime); //milisecs;\n msgParams.start = requestTime;\n msgParams.end = responseTime;\n\n try {\n fhreports.sendReport({\n func: funct,\n fullparams: msgParams,\n topic: 'fhact'\n });\n } catch (e) {\n // error purposely ignored\n }\n\n // also log live stat\n fh.stats.timing(funct + '_request_times', msgParams['time'], true);\n fh.stats.timing('__fh_all_request_times', msgParams['time'], true);\n }\n\n next();\n });\n };\n}", "show(req, res) {\n logging.logTheinfo(\"widgets show Router\");\n res.status(200).send(\"show\");\n\n }", "function reduxActionFunctions(dispatch){\n return bindActionCreators({\n set_sampleString : set_sampleString,\n set_is_logged : set_is_logged\n\t\t// si set_sampleString function kay makit an sa actions folder\n },dispatch);\n }", "function reduxActionFunctions(dispatch){\n return bindActionCreators({\n set_sampleString : set_sampleString,\n set_is_logged : set_is_logged\n\t\t// si set_sampleString function kay makit an sa actions folder\n },dispatch);\n }", "function routeSetup(app){\n\tapp.get('/users/:id', getUser(app));\n\tapp.delete('/users/:id', deleteUser(app));\n\tapp.use('/users/:id', bodyParser.json());\n\tapp.post('/users/:id', postUser(app));\n\tapp.put('/users/:id', putUser(app));\n}", "function router(app) {\n\n}", "function access(req, res, next){\r\n console.log(req.ip + \"\\t\" + req.method + \"\\t\" + req.url);\r\n next();\r\n}", "function initController(route){\n\tvar fn = route.to.split('.');\n\n\treturn function*(next){\n\t\tvar Controller = Risotto.controllers[fn[0]];\n\t\tthis._instance = new Controller();\n\t\tthis._instance.koaContext = this;\n\t\tyield next;\n\t}\n}", "function exampleMiddleware(storeAPI) {\n return function wrapDispatch(next) {\n return function handleAction(action) {\n return next(action);\n };\n };\n}", "routes() {\n this.app.use('/', indexRoutes_1.default);\n this.app.use('/api/games', gamesRoutes_1.default);\n }", "function route() {\n this.method = this.req.method.toLowerCase();\n var n = w.map[this.method];\n if (!n) {\n this.reply4xx(404, \"no route for method: \"+this.req.method);\n this.end();\n return\n } else {\n this.url = w.dep.url.parse(this.req.url, true);\n this.query = this.url.query || {};\n this.context = {};\n for (var e in this.query) { this.context[e] = this.query[e] }\n this.context._work = this;\n this.context._js = [];\n this.context._css = [];\n \n var p = this.url.pathname.split('/');\n console.log(this.req.url, \"route to ===============> \" + this.req.method.toUpperCase(), p);\n \n for (var i = 1; i < p.length; ++i) {\n var segment = p[i];\n if (n.branches[segment]) { n = n.branches[segment]; continue };\n if (n.branches[':']) { //varname\n this.context[n.varname] = segment;\n console.log(\"//varname: \" + n.varname + \" = \" + this.context[n.varname]);\n n = n.branches[':'];\n continue\n };\n if (n.branches['*']) { //wildcard\n this.context['_location'] = p.slice(i).join('/');\n console.log(\"//wildcard: \" + this.context['_location']);\n n = n.branches['*'];\n break\n };\n this.reply4xx(404, \"no route to: \"+this.req.method+' '+this.req.url);\n this.end();\n return\n };\n };\n \n if (n.handler) {\n this.mapnode = n;\n n.handler.call(this);\n this.end();\n return\n }\n\n this.reply5xx(500, \"no handler found for: \"+this.req.method+' '+this.req.url);\n this.end();\n return\n}", "function registerFunctionRoutes(app, userFunction, functionSignatureType) {\n if (functionSignatureType === SignatureType.HTTP) {\n app.use('/favicon.ico|/robots.txt', (req, res) => {\n // Neither crawlers nor browsers attempting to pull the icon find the body\n // contents particularly useful, so we send nothing in the response body.\n res.status(404).send(null);\n });\n app.use('/*', (req, res, next) => {\n onFinished(res, (err, res) => {\n res.locals.functionExecutionFinished = true;\n });\n next();\n });\n app.all('/*', (req, res, next) => {\n const handler = makeHttpHandler(userFunction);\n handler(req, res, next);\n });\n }\n else if (functionSignatureType === SignatureType.EVENT) {\n app.post('/*', (req, res, next) => {\n const wrappedUserFunction = wrapEventFunction(userFunction);\n const handler = makeHttpHandler(wrappedUserFunction);\n handler(req, res, next);\n });\n }\n else {\n app.post('/*', (req, res, next) => {\n const wrappedUserFunction = wrapCloudEventFunction(userFunction);\n const handler = makeHttpHandler(wrappedUserFunction);\n handler(req, res, next);\n });\n }\n}", "middlewares() {\n this.server.use(cors());\n this.server.use(express.json());\n }", "process(req, res){}", "function middleware(req, res, next) {\n req.context = createNamespace('context');\n req.context.run(() => next());\n}", "function getStoreController(modelMap) {\n const router = express.Router();\n\n router.post(\n \"/additemtostore\",\n bodyParser.json(),\n createControllerHandler(\n \"POST\",\n addItemToStoreSchema,\n modelMap,\n validatedAddItemToStoreHandler\n )\n );\n\n router.post(\n \"/buyitem\",\n bodyParser.json(),\n createControllerHandler(\n \"POST\",\n buyItemSchema,\n modelMap,\n validatedBuyItemHandler\n )\n );\n\n router.get(\n \"/listbuyables\",\n bodyParser.json(),\n createControllerHandler(\n \"GET\",\n listBuyablesSchema,\n modelMap,\n validateListBuyablesHandler\n )\n );\n\n router.get(\n \"/getstoreidfromuser\",\n createControllerHandler(\n \"GET\",\n getStoreIDFromUserSchema,\n modelMap,\n validatedGetStoreIDFromUserHandler\n )\n );\n\n router.get(\n \"/liststores\",\n createControllerHandler(\n \"GET\",\n listStoresSchema,\n modelMap,\n validatedListStoresHandler\n )\n );\n\n return router;\n}", "function route(method: string, path: string, action: string, handler) {\n // $FlowFixMe - doesn't like calling a computed method\n router[method](path, can(action), wrap(handler));\n }", "function init(router) {\n router.route('/categories').get(getCategories);\n router.route('/categories/:categoryCode').get(getCategoriesByCategoryCode);\n router.route('/categories/:categoryCode/types').get(getTypesByCategoryCode);\n router.route('/categories/:categoryCode/types/:typeCode').get(getTypesByCategoryAndTypeCode);\n router.route('/categories/:categoryCode/types/:typeCode/subtypes').get(getSubTypesByCategoryCodeAndTypeCode);\n router.route('/categories/:categoryCode/types/:typeCode/subtypes/:subTypeCode').get(getSubTypesByCategoryCodeTypeCodeAndSubTypeCode);\n router.route('/categories/:categoryCode/typedesc/:typeDesc/subtypedesc/:subTypeDesc').get(getSubTypeCodeByCategoryCodeTypeCodeAndSubType);\n\n router.route('/tenants').get(getTenantsByTenantCode);\n router.route('/tenants/:tenantCode').get(getTenantsByTenantCode);\n\n router.route('/priorities').get(getPrioritiesByPriorityCode);\n router.route('/priorities/:priorityCode').get(getPrioritiesByPriorityCode);\n\n router.route('/statuses').get(getStatus);\n router.route('/statuses/:statusCode').get(getStatusByStatusCode);\n router.route('/statuses').post(postStatusByArrayOfStatusCodes);\n}", "function endpointHandler(req, res) {\n\n // Extract stuff we're interested in from the POST.\n const refererQueryParams = utils.extractQueryParams(req.headers['referer']);\n // const userLogin = req.body['custom_canvas_user_loginid'];\n // const assignmentId = refererQueryParams['assignment'];\n\n // Secret path for debugging that shows us what is getting passed to the endpoint\n // https://ourdomain.instructure.com/accounts/1/external_tools/67839876483?display=borderless&assignment=abcxyz&route=showpost\n if (refererQueryParams['route'] === 'showpost') {\n postParamsHandler(req, res); \n } else if (isValidRequest('POST', process.env.CST_LTI_LAUNCH_URL, req.body)) {\n // Special redirect handling for particular user first names\n var firstName = req.body['custom_person_name_given'];\n if (['Candidate', 'Teacher'].includes(firstName)) {\n termRedirectHandler(req, res, '989');\n } else { // Normal redirect handling']\n redirectHandler(req, res);\n }\n } else {\n res.send('OAuth post not authenticated');\n }\n}", "function myLoggingMiddleWare(req, res, next){\n var url = req.url;\n var method = req.method;\n\n console.log('%s request at %s', url, method); //, first %s is the url, second %s is the method. %s everytime a route is hit, it will print what url and method is being used, e.g., get or post\n next();\n}", "function notfound_action(){\n \n res.status = 200;\n \n var action, output, name;\n \n // setup path names to look through\n var names = req.path.split('/');\n \n // resolve path names against the object hierarchy\n var obj = root;\n do {\n if (obj.get(names[0]))\n obj = obj.get(names[0]);\n else\n break;\n }\n while (names.shift());\n \n if (!obj.render)\n res.redirect(obj._parent.href());\n \n req.data.action = names[0] || 'main';\n \n // handle idempotent requests as such\n idempotentAction = req.data.action +'_'+ req.method.toLowerCase();\n \n // call a softcoded idempotent action\n if (obj.actions[idempotentAction])\n obj.actions[idempotentAction].call(obj,names);\n \n // call a softcoded standard action\n else if (obj.actions[req.data.action])\n obj.actions[req.data.action].call(obj,names);\n \n // render auto-action-enabled views \n else if (obj.actionviews_json \n && obj.actionviews_json[req.data.action] \n && obj.access[req.data.action])\n obj.renderPage();\n \n // if the main action was denied, redirect to the login\n else if (req.data.action == 'main')\n res.redirect(obj.href('login'));\n \n // otherwise redirect to the main action\n else \n res.redirect(obj.href());\n}", "function adminRoutes(){\n\t\n\t// url map to POST login details\n\tapp.post('/api/login/' ,passport.authenticate('local-login'),\n\t\t function (req, res) {\n\t\t res.json( {message: 'OK'} );\n\t\t });\n\t\n\t// logging-out\n\tapp.get('/api/logout/', isLoggedIn,\n\t\tfunction (req, res){\n\t\t req.logout();\n\t\t res.json({message : 'OK'});\n\t\t});\n\t\n\t// url map to GET admin page(list of admins)\n\tapp.get('/api/admin/', isLoggedIn,\n\t\tfunction (req, res) {\n\t\t User.find(\n\t\t\tfunction (err, admins) {\n\t\t\t if (err)\n\t\t\t\tres.send(err);\n\t\t\t\t \n\t\t\t var adminList = {};\n\t\t\t for (var i in admins)\n\t\t\t\tadminList[admins[i][\"id\"]] = admins[i][\"local\"][\"email\"]; \n\t\t\t\t \n\t\t\t res.json(adminList);\n\t\t\t});\t\t \n\t\t});\n\t// url map to add a new admin\n\tapp.post('/api/admin/',isLoggedIn,\n\t\t passport.authenticate('local-signup'),\n\t\t function (req, res) {\n\t\t res.json( {message: 'OK'} );\n\t\t });\n\t \t\t\n\t// url map to DELETE a admin\n\tapp.delete('/api/admin/:user_id', isLoggedIn,\n\t\t function (req, res) {\n\t\t User.remove({_id : req.params.user_id},\n\t\t\t\t function (err, user) {\n\t\t\t\t if (err)\n\t\t\t\t\t res.send(err);\n\t\t\t\t res.json({message : 'OK'});\n\t\t\t\t });\n\t\t });\n\t\n }", "static middlewareHandler(closure) {\n\n config.middlewareHandler = closure;\n }", "function route() {\n var router = new express.Router();\n router.use(cors());\n router.use(bodyParser());\n\n // POST REST endpoint - note we use 'body-parser' middleware above to parse the request body in this route.\n // This can also be added in application.js\n // See: https://github.com/senchalabs/connect#middleware for a list of Express 4 middleware\n router.post('/', function(req, res) {\n console.log('Hi', req.body);\n //Must pass a username & password\n var username = req.body.username || req.body.userId;\n var password = req.body.password;\n if (!username || !password) {\n return res.status(500).json({'status': 'error','message': 'You need to provide a username and password.'});\n }\n\n checkCredentials(username, password)\n .then(function (result){\n console.log('username', username, 'authenticated')\n res.status(result.statusCode).json(result);\n })\n .catch(function (err) {\n console.log('username', username, 'not authenticated', 'err', err)\n res.status(err.statusCode).json(err);\n });\n\n });\n\n return router;\n}", "function main () {\n let app = express(); // Export app for other routes to use\n let handlers = new HandlerGenerator();\n const port = process.env.PORT || 8000;\n app.use(bodyParser.urlencoded({ // Middleware\n extended: true\n }));\n app.use(bodyParser.json());\n // Routes & Handlers\n app.post('/login', handlers.login);\n app.get('/', middleware.checkToken, handlers.index);\n app.listen(port, () => console.log(`Server is listening on port: ${port}`));\n}" ]
[ "0.6964572", "0.6805262", "0.64788353", "0.644326", "0.64190686", "0.637253", "0.63364655", "0.6270464", "0.6206107", "0.6199991", "0.61869925", "0.6167403", "0.6141563", "0.6139946", "0.6119526", "0.6117217", "0.60917133", "0.6086891", "0.60454565", "0.604518", "0.6026071", "0.60008144", "0.5990038", "0.596649", "0.5962326", "0.595804", "0.5943232", "0.593853", "0.5929742", "0.58933103", "0.58873016", "0.58808434", "0.5877758", "0.5866912", "0.5866897", "0.5860403", "0.58438", "0.5842368", "0.5840851", "0.58289325", "0.5821172", "0.5820907", "0.58178216", "0.58035594", "0.57744616", "0.5767108", "0.5751193", "0.5749262", "0.57476413", "0.5746181", "0.5723408", "0.5696691", "0.56890506", "0.56890464", "0.56829184", "0.56825465", "0.56825465", "0.5682424", "0.5676401", "0.56755686", "0.56665707", "0.56609356", "0.5659926", "0.5654375", "0.5650658", "0.5642074", "0.56415004", "0.5634279", "0.56331784", "0.56296754", "0.56290966", "0.56255114", "0.5621195", "0.56092095", "0.56092095", "0.56066823", "0.5597818", "0.5587684", "0.558304", "0.558304", "0.5569405", "0.55574745", "0.5553232", "0.5544589", "0.55416226", "0.5537115", "0.5533571", "0.5523965", "0.55199814", "0.5518735", "0.5513217", "0.551131", "0.5509833", "0.5501342", "0.5500313", "0.55000764", "0.5499023", "0.54989254", "0.5498462", "0.54927367", "0.54870886" ]
0.0
-1
Read all Object names sequentially, that do not have aliases
async function readAllNames(ids) { for (let i = 0; i < ids.length; i++) { const obj = await adapter.getForeignObjectAsync(ids[i]); await updateStateSettings(ids[i], obj); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getAllObjectNames() {\n var objNameList = [];\n appInstance.scene.traverse(function (obj) {\n if (notIgnoredObj(obj)) objNameList.push(obj.name);\n });\n return objNameList;\n }", "function getAllObjectNames() {\n var objNameList = [];\n appInstance.scene.traverse(function(obj) {\n if (notIgnoredObj(obj))\n objNameList.push(obj.name)\n });\n return objNameList;\n}", "function retrieveObjectNames(objNames) {\n var acc = [];\n retrieveObjectNamesAcc(objNames, acc);\n return acc;\n}", "function retrieveObjectNames(objNames) {\n var acc = [];\n retrieveObjectNamesAcc(objNames, acc);\n return acc.filter(function (name) {\n return name;\n });\n }", "getObjectKeys(obj){\n\t\tlet arr = '';\n\t\tObject.keys(obj).map(function(keyName, keyIndex) {\t\t\t\n\t\t\tarr = obj[keyName]['name'];\n\t\t})\n\t\treturn arr;\n\t}", "function getFieldNamesFromObject(obj) {\n console.log('getFieldNamesFromObject');\n tmp = []\n Object.getOwnPropertyNames(obj).forEach(function(val, idx, array) {\n //console.log(val + ' -> ' + obj[val]);\n tmp.push(val);\n });\n //console.log(tmp);\n return tmp;\n}", "function readNames(cb, lvl){\t\t\t\t\t\t\t\t\t\t\t\t//lvl is for reading past state blocks, tbd exactly\n\tread('_all', cb, lvl);\n}", "function gatherStrings(obj) {\n\n}", "function getObjectNamesByGroupName(targetGroupName) {\n var objNameList = [];\n appInstance.scene.traverse(function (obj) {\n if (notIgnoredObj(obj)) {\n var groupNames = obj.groupNames;\n if (!groupNames) return;\n for (var i = 0; i < groupNames.length; i++) {\n var groupName = groupNames[i];\n if (groupName == targetGroupName) {\n objNameList.push(obj.name);\n }\n }\n }\n });\n return objNameList;\n }", "function getObjectNamesByGroupName(targetGroupName) {\n var objNameList = [];\n appInstance.scene.traverse(function(obj){\n if (notIgnoredObj(obj)) {\n var groupNames = obj.groupNames;\n if (!groupNames)\n return;\n for (var i = 0; i < groupNames.length; i++) {\n var groupName = groupNames[i];\n if (groupName == targetGroupName) {\n objNameList.push(obj.name);\n }\n }\n }\n });\n return objNameList;\n}", "function gatherStrings(obj) {\n const rs = [];\n function recursionHelper(obj){\n for (let value of Object.values(obj)){\n if (value === Object(value)){\n recursionHelper(value);\n }else if (typeof value === 'string'){\n rs.push(value);\n }\n }\n }\n recursionHelper(obj);\n return rs;\n}", "function gatherStrings(obj) {\n let strings = [];\n for(let key in obj){\n if(typeof obj[key] === 'string') strings.push(obj[key])\n if(typeof obj[key] === 'object') strings.push(...gatherStrings(obj[key]))\n }\n return strings\n}", "function getOwnPropertyNames(obj){\n var props = getProperties(obj);\n if (hasOwn(obj, globalID))\n splice(props, indexOf(props, globalID), 1);\n return props;\n }", "function getOwnPropertyNames(obj) {\n var result = [];\n var seen = {};\n // TODO(erights): revisit once we do ES5ish attribute control.\n var implicit = isJSONContainer(obj);\n for (var k in obj) {\n if (hasOwnProp(obj, k)) {\n if (implicit && !endsWith__.test(k)) {\n if (!myOriginalHOP.call(seen, k)) {\n seen[k] = true;\n result.push(k);\n }\n } else {\n var match = attribute.exec(k);\n if (match !== null) {\n var base = match[1];\n if (!myOriginalHOP.call(seen, base)) {\n seen[base] = true;\n result.push(base);\n }\n }\n }\n }\n }\n return result;\n }", "function collectStrings(obj) {\n var stringsArr = [];\n \n function gatherStrings(o) {\n for(var key in o) {\n if(typeof o[key] === 'string') {\n stringsArr.push(o[key]);\n }\n else if(typeof o[key] === 'object') {\n return gatherStrings(o[key]);\n }\n }\n }\n \n gatherStrings(obj);\n \n return stringsArr;\n}", "function collectStrings(obj) {\n var stringsArr = [];\n function gatherStrings(o) {\n for (var key in o) {\n if (typeof o[key] === 'string') {\n stringsArr.push(o[key]);\n }\n else if (typeof o[key] === 'object') {\n return gatherStrings(o[key]);\n }\n }\n }\n gatherStrings(obj);\n return stringsArr;\n}", "function gatherStrings(obj) {\n const strArr=[];\n for (let key in obj) {\n if (typeof obj[key] === \"string\") strArr.push(obj[key]);\n if (typeof obj[key] === \"object\") strArr.push(...gatherStrings(obj[key]));\n }\n return strArr;\n}", "function collectStrings(obj) {\n var stringsArr = [];\n\n function gatherStrings(o) {\n for (var key in o) {\n if (typeof o[key] === \"string\") {\n stringsArr.push(o[key]);\n } else if (typeof o[key] === \"object\") {\n return gatherStrings(o[key]);\n }\n }\n }\n\n gatherStrings(obj);\n\n return stringsArr;\n}", "function gatherStrings(obj) {\n let stringArr = [];\n for (let key in obj) {\n if (typeof obj[key] === \"string\") stringArr.push(obj[key]);\n if (typeof obj[key] === \"object\") stringArr.push(...gatherStrings(obj[key]));\n }\n return stringArr;\n}", "function getName(o) {\n return o.name;\n} // Warm up JIT", "function getFieldNames(object) {\n var d = Def.fromValue(object);\n if (d) {\n return d.fieldNames.slice(0);\n }\n\n if (\"type\" in object) {\n throw new Error(\n \"did not recognize object of type \" +\n JSON.stringify(object.type)\n );\n }\n\n return Object.keys(object);\n }", "function getFieldNames(object) {\n var d = defFromValue(object);\n if (d) {\n return d.fieldNames.slice(0);\n }\n if (\"type\" in object) {\n throw new Error(\"did not recognize object of type \" +\n JSON.stringify(object.type));\n }\n return Object.keys(object);\n }", "function getFieldNames(object) {\n\t var d = Def.fromValue(object);\n\t if (d) {\n\t return d.fieldNames.slice(0);\n\t }\n\n\t if (\"type\" in object) {\n\t throw new Error(\n\t \"did not recognize object of type \" +\n\t JSON.stringify(object.type)\n\t );\n\t }\n\n\t return Object.keys(object);\n\t}", "function getFieldNames(object) {\n\t var d = defFromValue(object);\n\t if (d) {\n\t return d.fieldNames.slice(0);\n\t }\n\t if (\"type\" in object) {\n\t throw new Error(\"did not recognize object of type \" +\n\t JSON.stringify(object.type));\n\t }\n\t return Object.keys(object);\n\t }", "function getFieldNames(object) {\n\t var d = Def.fromValue(object);\n\t if (d) {\n\t return d.fieldNames.slice(0);\n\t }\n\n\t if (\"type\" in object) {\n\t assert.ok(\n\t false,\n\t \"did not recognize object of type \" +\n\t JSON.stringify(object.type)\n\t );\n\t }\n\n\t return Object.keys(object);\n\t}", "function nameRecursion(prefix, obj) {\n var key, returnResult, newPrefix, isVoid = true, result = [];\n for (key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n isVoid = false;\n // dont concatenate with void prefix\n newPrefix = prefix !== '' ? prefix.concat(self.delimiter, key) : key;\n // merge arrays by recursion\n result = result.concat(nameRecursion(newPrefix, obj[key]));\n }\n }\n if (self.includeNodes && prefix !== '') {\n returnResult = result.concat([prefix]);\n } else {\n returnResult = isVoid ? [prefix] : result;\n }\n return returnResult;\n }", "function extractAll(str) {\n var tokenStream = (0, _lexerUtils.TokenStream)(lex(str));\n var objects = [];\n\n while (tokenStream.present) {\n var parsed = parseObject(tokenStream);\n\n if (parsed) {\n objects.push(parsed[0]);\n tokenStream = parsed[1];\n } else {\n tokenStream = tokenStream.advance();\n }\n }\n\n return objects;\n}", "function childrenObjects(obj)\n {\n var objects = {};\n for(var i in obj)\n {\n if(obj[i]!==endString) objects[i]=obj[i];\n }\n return objects;\n }", "function gatherStrings(obj) {\n // hidden base case: when you are done looping\n let out = [];\n\n function _gatherStrings(obj) {\n for (let value of Object.values(obj)) {\n if (typeof value === 'object' && typeof value !== null) {\n _gatherStrings(value);\n }\n if (typeof value === 'string') {\n out.push(value);\n }\n }\n }\n\n _gatherStrings(obj);\n return out;\n\n // With accumulator, out = []\n // for (let value of Object.values(obj)) {\n // if (typeof value === 'object' && typeof value !== null) {\n // gatherStrings(value, out);\n // } else {\n // if (typeof value === 'string') {\n // out.push(value);\n // }\n // }\n // }\n\n // return out;\n}", "function collectStrings(obj){\n \n let result = []\n \n for(let key in obj){\n if(typeof obj[key] === 'string'){\n result.push(obj[key])\n }\n if(typeof obj[key] === 'object'){\n result = result.concat(collectStrings(obj[key]))\n }\n }\n return result\n \n }", "function nameProps(obj) {\n\n}", "names() {\n return Object.keys(this.name2Id);\n }", "function getPropertyNames(o, /*opcional*/ a) {\n\ta = a || [];\n\tfor(var p in o) a.push(p);\n\treturn a;\n}", "function collectStrings(obj) {\n var stringsArr = [];\n for(var key in obj) {\n if(typeof obj[key] === 'string') {\n stringsArr.push(obj[key]);\n }\n else if(typeof obj[key] === 'object') {\n stringsArr = stringsArr.concat(collectStrings(obj[key]));\n }\n }\n \n return stringsArr;\n}", "function gatherStrings(obj) {\n\tlet stringArr = [];\n\tfor (let key in obj) {\n\t\t// only get string values\n\t\tif (typeof obj[key] === 'string') stringArr.push(obj[key]);\n\t\t// if key is a nested object, use recursion\n\t\tif (typeof obj[key] === 'object')\n\t\t\tstringArr.push(...gatherStrings(obj[key]));\n\t}\n\treturn stringArr;\n}", "function customPrintNames(array) {\n\tvar stringtoPrint = \" \";\n\tfor(var i = 0; i < array.length; i++) {\n\t\tstringtoPrint = stringtoPrint + array[i].get(\"name\") + \" \";\n\t}\n\t//log(\"Final object order\" + stringtoPrint);\n}", "function __objLoop(obj, names, fn){ \n\tif (isGlobalNS(obj, names[0])) names.shift();\n\tvar nsObj = obj, flag = true, i=0, len = names.length; \n\twhile(i<len && flag && nsObj){\n\t\tvar curname = names[i];\n\t\tif (curname === \"\") {\n\t\t\tconsole.error(\"invalid NS name:\" + names.join(\".\"));\n\t\t\treturn undefined;\n\t\t}\n\t\tflag = fn(curname, nsObj);\n\t\tif(flag)\n\t\t\tnsObj = nsObj[curname];\n\t\ti++;\n\t}\n\treturn flag;\n}", "function __objLoop(obj, names, fn){ \n\tif (isGlobalNS(obj, names[0])) names.shift();\n\tvar nsObj = obj, flag = true, i=0, len = names.length; \n\twhile(i<len && flag && nsObj){\n\t\tvar curname = names[i];\n\t\tif (curname === \"\") {\n\t\t\tconsole.error(\"invalid NS name:\" + names.join(\".\"));\n\t\t\treturn undefined;\n\t\t}\n\t\tflag = fn(curname, nsObj);\n\t\tif(flag)\n\t\t\tnsObj = nsObj[curname];\n\t\ti++;\n\t}\n\treturn flag;\n}", "function __objLoop(obj, names, fn){ \n\tif (isGlobalNS(obj, names[0])) names.shift();\n\tvar nsObj = obj, flag = true, i=0, len = names.length; \n\twhile(i<len && flag && nsObj){\n\t\tvar curname = names[i];\n\t\tif (curname === \"\") {\n\t\t\tconsole.error(\"invalid NS name:\" + names.join(\".\"));\n\t\t\treturn undefined;\n\t\t}\n\t\tflag = fn(curname, nsObj);\n\t\tif(flag)\n\t\t\tnsObj = nsObj[curname];\n\t\ti++;\n\t}\n\treturn flag;\n}", "function collectStrings(obj) {\n\n var resultado = [];\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n\n if(typeof obj[key] === \"object\"){\n\n resultado = resultado.concat(collectStrings(obj[key]));\n\n }else if (typeof obj[key] === \"string\") {\n resultado.push(obj[key]);\n\n }\n\n }\n }\n\n return resultado;\n}", "function getNames(data) {\n return data.names;\n}", "GetAllAssetNames() {}", "function collectStrings(obj) {\n var stringsArr = [];\n for (var key in obj) {\n if (typeof obj[key] === \"string\") {\n stringsArr.push(obj[key]);\n } else if (typeof obj[key] === \"object\") {\n stringsArr = stringsArr.concat(collectStrings(obj[key]));\n }\n }\n\n return stringsArr;\n}", "function collectStrings(obj){\n let a = []\n\n let aObj = Object.values(obj)\n\n for (let i = 0; i < aObj.length; i++) {\n if(typeof aObj[i] === \"string\") a.push(aObj[i])\n if(typeof aObj[i] === \"object\") a = a.concat(collectStrings(aObj[i]))\n }\n\n return a\n}", "function deanonymize(o, name) {\n name = name || 'named'\n if (o) {\n const keys = Object.keys(o)\n keys.forEach(key => {\n if (typeof o[key] == 'function') {\n o[key][name] = key\n }\n })\n return keys\n } else {\n return []\n }\n}", "listObjects(bucketName, prefix, recursive) {\n if (!validateBucketName(bucketName)) {\n throw new errors.InvalidateBucketNameException('Invalid bucket name: ' + bucketName)\n }\n // recursive is null set delimiter to '/'.\n var delimiter = recursive ? null : \"/\"\n var dummyTransformer = transformers.getDummyTransformer()\n var self = this\n function listNext(marker) {\n self.listObjectsOnce(bucketName, prefix, marker, delimiter, 1000)\n .on('error', e => dummyTransformer.emit('error', e))\n .on('data', result => {\n result.objects.forEach(object => {\n dummyTransformer.push(object)\n })\n if (result.isTruncated) {\n listNext(result.nextMarker)\n return\n }\n dummyTransformer.push(null) // signal 'end'\n })\n }\n listNext()\n return dummyTransformer\n }", "function preProcessNames(fileData) {\n\n var i = 0;\n var nextNewlinePos = -1;\n var name = \"\";\n var nameObj = null;\n var nameList = new Array();\n\n do {\n nextNewlinePos = fileData.indexOf(\"\\n\", i);\n if (nextNewlinePos > -1)\n name = fileData.substring(i, nextNewlinePos).trim();\n else // go to end of line\n name = fileData.substring(i).trim();\n // Check if we got 2 newlines in a row or something like that.\n if (name.length > 0) {\n nameObj = new NameClass(name);\n // Did the name get a bucket?\n if (nameObj.bucket)\n // Could this bucket be in the solution?\n if (nameObj.length < gTotalCharCount && isBucketContained(nameObj.bucket, gaCharacters))\n nameList.push(nameObj);\n } // end if name actually has a value.\n i = nextNewlinePos + 1;\n } while (nextNewlinePos > -1);\n\n return nameList;\n}", "function getPropNamesAndSymbols (obj = {}) {\n const listOfKeys = Object.getOwnPropertyNames(obj);\n return isFunction(Object.getOwnPropertySymbols)\n ? listOfKeys.concat(Object.getOwnPropertySymbols(obj))\n : listOfKeys;\n}", "getAllNames() {\n return Array.from(this.commitPerName.keys());\n }", "function getObjNames(list, ids) {\n var shortList = [];\n var id = '';\n if (list === undefined) {\n //TODO - switch to english translation file in case of a non-existent translation\n for (i = 0; i < ids.length; i++) {\n id = '';\n if (typeof (ids[i]) == \"number\") {\n id = \"'\" + ids[i] + \"'\";\n } else {\n id = ids[i];\n }\n shortList[i] = [ids[i], id];\n }\n } else {\n for (i = 0; i < ids.length; i++) {\n id = '';\n if (typeof (ids[i]) == \"number\") {\n id = \"'\" + ids[i] + \"'\";\n } else {\n id = \"'\" + ids[i] + \"'\";\n }\n shortList[i] = [list[ids[i]], id];\n }\n }\n return shortList;\n}", "function Enumerate(obj) {\n var e = [];\n if (Object(obj) !== obj) return e;\n var visited = new Set;\n while (obj !== null) {\n Object.getOwnPropertyNames(obj).forEach(function(name) {\n if (!visited.has(name)) {\n var desc = Object.getOwnPropertyDescriptor(obj, name);\n if (desc) {\n visited.add(name);\n if (desc.enumerable) e.push(name);\n }\n }\n });\n obj = Object.getPrototypeOf(obj);\n }\n return e[$$iterator]();\n }", "function listAllObjects(oci, bucket) {\n return oci.request(bucket)\n .then(({ data }) => data.objects.map(o => o.name));\n}", "function getAssignmentObjects(exp) {\n var matches = getAssignedVars(exp, true),\n names = [];\n matches.forEach(function(s) {\n var match = /^([^.]+)\\.[^.]+$/.exec(s);\n var name = match ? match[1] : null;\n if (name && name != 'this') {\n names.push(name);\n }\n });\n return utils.uniq(names);\n }", "function getObjectKeys(object) {\n // YOUR CODE BELOW HERE //\n //return an array of the object keys\n return Object.keys(object);\n \n \n \n // YOUR CODE ABOVE HERE //\n}", "function collectStrings(obj) {\n // create a result array\n let strings = [];\n\n // helper\n function helper(object) {\n // base case:\n // if object is empty, return\n if (Object.keys(object).length === 0) return;\n\n // recursive case:\n // iterate over object\n // if val is string\n // push val to strings\n // if val is object\n // recursively call helper on val\n for (let key in object) {\n if (typeof object[key] === 'string') strings.push(object[key]);\n if (typeof object[key] === 'object' && !Array.isArray(object[key])) helper(object[key]);\n }\n }\n\n // call helper on input obj\n helper(obj);\n\n return strings;\n}", "function getAllPropertyNames(obj) {\r\n let res = [];\r\n let proto = Object.getPrototypeOf(obj);\r\n while (Object.prototype !== proto) {\r\n res = res.concat(Object.getOwnPropertyNames(proto));\r\n proto = Object.getPrototypeOf(proto);\r\n }\r\n return res;\r\n}", "static async scanBpmnObjectForMessages(bpmnObject) {\n let messageNames = []; // mutated in the recursive function\n await scanRecursively(bpmnObject);\n return [...new Set(messageNames.sort())];\n async function scanRecursively(obj) {\n let k;\n if (obj instanceof Object) {\n for (k in obj) {\n if (obj.hasOwnProperty(k)) {\n if (k === 'bpmn:message') {\n const messages = Array.isArray(obj[k])\n ? obj[k]\n : [obj[k]];\n messageNames = messageNames.concat(messages.map(m => m.attr['@_name']));\n }\n else {\n // recursive call to scan property\n await scanRecursively(obj[k]);\n }\n }\n }\n }\n else {\n // not an Object so obj[k] here is a value\n }\n }\n }", "function getObjectKeys(object) {\n // YOUR CODE BELOW HERE //\n let obj = [];\n for (var key in object) {\n obj.push(key);\n }\n return obj;\n\n \n \n \n \n // YOUR CODE ABOVE HERE //\n}", "ownKeys () {\n return Object.getOwnPropertyNames(obj)\n }", "function parseObjects(reader, offset, cb) {\n var src = ByteReader(reader, offset);\n seekObjectStart(src);\n while (src.peek() == LBRACE) {\n cb(readObject(src));\n readToken(src, COMMA);\n }\n }", "function getDefinitionByName(data, name) {\n var key = 'name';\n var objects = [];\n for (var i in data) {\n if (!data.hasOwnProperty(i)) continue;\n if (typeof data[i] == 'object') {\n objects = objects.concat(getDefinitionByName(data[i], name));\n } else if (i == key && data[key] == name) {\n objects.push(data);\n }\n }\n return objects;\n}", "function lazyKeys() {\n if (!ownNames) {\n ownNames = Object.getOwnPropertyNames(Node.prototype);\n }\n}", "function lazyKeys() {\n if (!ownNames) {\n ownNames = Object.getOwnPropertyNames(Node.prototype);\n }\n}", "function lazyKeys() {\n if (!ownNames) {\n ownNames = Object.getOwnPropertyNames(Node.prototype);\n }\n}", "function lazyKeys() {\n if (!ownNames) {\n ownNames = Object.getOwnPropertyNames(Node.prototype);\n }\n}", "getPropertyNameCompletions() {\n let results = [];\n this.enumerateBrsFiles((file) => {\n results.push(...file.propertyNameCompletions);\n });\n return results;\n }", "function _getKeys(obj) {\n\tvar keys = [];\n\tfor(var key in obj){\n\t keys.push(key);\n\t}\n\treturn keys;\n }", "function __getObjs($name) {\r\n return __arrayDoms(document.all[$name]);\r\n}", "get assetNames() {}", "getFactNames() {\n this.PuppetDB.query('fact-paths',\n null,\n { order_by: angular.toJson([{ field: 'path', order: 'asc' }]) },\n data => {\n this.factPaths = angular.fromJson(data).filter(fact => fact.path[0][0] !== '_')\n .map(fact => fact.path);\n }\n );\n }", "function allOwnKeys(o) {\n return [\n ...Object.getOwnPropertyNames(o),\n ...Object.getOwnPropertySymbols(o)\n ];\n}", "function set_sorted_names() {\n // Before going on, create a separate list that has the\n // sample ids sorted by name.\n names_to_ids = {};\n for (var id in proj.samples) {\n names_to_ids[proj.samples[id].name] = id;\n }\n console.log(names_to_ids);\n sorted_names = Object.keys(names_to_ids).sort();\n console.log(sorted_names);\n}", "returnlist(nameof) {\n let current = this.head;\n try {\n while (current != null) {\n if (current.name === nameof) return current.nameset;\n current = current.next;\n }\n } catch (error) {\n console.log(\"/\" + dat + \"/\" + \"was entered\");\n }\n }", "get namedItems() {\n this.updateCache();\n return this.childrenByName;\n }", "list() {\n // list all stored objects by reading the file system\n return mkderp(dir)\n .then(() => readDir(dir))\n .then(files =>\n Promise.all(files.filter(f => f.substr(-5) === '.json').map(loadFile))\n );\n }", "function listCharacters() {\n console.log(\"Characters:\");\n for(var obj in adventuringParty) {\n console.log(\" * \" + adventuringParty[obj].name);\n }\n}", "function collectStrings(obj){\n var newArr = [];\n\n function helperStrings(obj){\n for (var key in obj){\n if(typeof obj[key] === 'string'){\n newArr.push(obj[key]);\n }else if(typeof obj[key] === 'object' && !Array.isArray(obj[key])){\n helperStrings(obj[key]);\n }\n }\n }\n helperStrings(obj);\n return newArr;\n}", "async userNames() {\n let cursor;\n const userNames = {};\n do {\n const {\n members: users,\n response_metadata: { next_cursor: nextCursor },\n } = await this.usersList({\n cursor,\n });\n\n for (const user of users) {\n userNames[user.id] = user.name;\n }\n\n cursor = nextCursor;\n } while (cursor);\n return userNames;\n }", "function getObjectKeys(object) {\n // create empty array to hold object keys\n let objectArray= [];\n // use for in loop to iterate through object items \n for( var key in object){\n // push only the keys onto the empty array \n objectArray.push(key);\n }\n \n return objectArray; \n \n \n \n // YOUR CODE ABOVE HERE //\n}", "getKeys(obj){\n var keys = [];\n for(var key in obj) keys.push(key);\n return keys;\n }", "function allTheNames(dataArr) {\n const result = [];\n dataArr.forEach((person,index) => \n person.name ? result[index] = person.name : null);\n return result;\n}", "function list () {\n jsonfile.readFile(STORAGE, function (error, aliases) {\n if (error) {\n // TODO: Handle this error.\n }\n\n let hasAlias = false;\n\n for (let prop in aliases) {\n if (aliases.hasOwnProperty(prop) && prop !== 'cb6b7b52-ad1c-4a4e-a66a-fbc3a0c3b503') {\n hasAlias = true;\n console.log('* ' + chalk.bold.magenta(prop) + ' => ' + chalk.bold.cyan(aliases[prop]));\n }\n }\n \n if (!hasAlias) {\n console.log(chalk.bold.yellow('No saved aliases.'));\n }\n });\n}", "function getItemNames(){\n let namesArr = [];\n for (let i = 0; i < allItems.length; i++){\n namesArr.push(allItems[i].name);\n }\n return namesArr;\n}", "async getNames() {\n const data = await this.getData();\n\n // We are using map() to transform the array we get into another one\n return data.map((medewerkers) => {\n return { naam: medewerkers.naam };\n });\n }", "function nameIterator(names) {\n let nextIndex = 0;\n\n return {\n next: function() {\n return nextIndex < names.length ?\n {value: names[nextIndex++], done: false} : {done: true}\n }\n }\n}", "function viewer(obj)\r\n{\r\n\tvar names = \"\";\r\n\tfor ( var name in obj )\r\n\t\tnames += name + \" : \" + obj[name]+\"\\n\";\r\n\talert(names);\r\n}", "get_all(name) {\n let ret = [];\n for(let item of this.data) {\n if(item.name === name) {\n ret.push(item);\n }\n }\n return ret;\n }", "function fastpathRead(obj, name) {\n if (name === 'toString') { fail(\"internal: Can't fastpath .toString\"); }\n obj[name + '_canRead___'] = obj;\n }", "static getRnObjectByName(uniqueName) {\n return RnObject.__objectsByNameMap.get(uniqueName);\n }", "extractReferences(index, count, first_object_id) {\n let _refs = [];\n let res = { result: null, start_index: -1, end_index: index };\n for (let i = 0; count === -1 || i < count; ++i) {\n res = util_1.Util.readNextWord(this.data, res.end_index + 1);\n let pointer = util_1.Util.extractNumber(res.result, 0).result;\n res = util_1.Util.readNextWord(this.data, res.end_index + 1);\n let generation = util_1.Util.extractNumber(res.result, 0).result;\n res = util_1.Util.readNextWord(this.data, res.end_index + 1);\n let ptr_flag = res.result;\n let isFree = ptr_flag[0] === 102; // 102 = f\n _refs.push({\n id: first_object_id + i,\n pointer: pointer,\n generation: generation,\n free: isFree,\n update: !isFree\n });\n // if the word trailer occurs stop since we reached the end\n if (this.data[util_1.Util.skipSpaces(this.data, res.end_index + 1)] === 116) {\n break;\n }\n }\n return { refs: _refs, end_index: res.end_index };\n }", "function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o),\n r,\n ar = [],\n e;\n\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n } catch (error) {\n e = {\n error: error\n };\n } finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n } finally {\n if (e) throw e.error;\n }\n }\n\n return ar;\n}", "function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m)\n return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done)\n ar.push(r.value);\n }\n catch (error) {\n e = { error: error };\n }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"]))\n m.call(i);\n }\n finally {\n if (e)\n throw e.error;\n }\n }\n return ar;\n }", "function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m)\n return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done)\n ar.push(r.value);\n }\n catch (error) {\n e = { error: error };\n }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"]))\n m.call(i);\n }\n finally {\n if (e)\n throw e.error;\n }\n }\n return ar;\n }", "function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m)\n return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done)\n ar.push(r.value);\n }\n catch (error) {\n e = { error: error };\n }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"]))\n m.call(i);\n }\n finally {\n if (e)\n throw e.error;\n }\n }\n return ar;\n }", "function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m)\n return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done)\n ar.push(r.value);\n }\n catch (error) {\n e = { error: error };\n }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"]))\n m.call(i);\n }\n finally {\n if (e)\n throw e.error;\n }\n }\n return ar;\n }", "function getObjectKeys(object) {\n // YOUR CODE BELOW HERE //\n \n //create an empty array to hold keys\n var arr = [];\n // use for in loop to retrieve all of the keys in the object\n for(var key in object){\n arr.push(key);\n \n }\n // return Object.keys(object);\nreturn arr;\n \n \n // YOUR CODE ABOVE HERE //\n}", "function firstName(obj) {\n var arr = [];\n for (let i = 0; i < obj.length; i++) {\n arr.push(obj[i].name.first);\n }\n return arr;\n}", "function createPeopleObjects(obj) {\n var people = [];\n obj.forEach(function(val) {\n if (val){\n var nameArr = val.value.split(\" \");\n var lastName = nameArr[nameArr.length-1];\n var firstName = nameArr.slice(0,nameArr.indexOf(lastName)).join(\" \");\n people.push(new Person(val.id, firstName, lastName));\n }\n });\n return people;\n}", "function getKeys(obj) {\n var keys = [];\n\n for(var key in obj) {\n if(obj.hasOwnProperty(key)) {\n keys.push(key);\n }\n }\n log(keys.join('\\n'));\n return keys;\n}", "function objectScan (obj) {\n if (obj==null) return \"Object is null\";\n if (typeof obj == \"string\") return obj;\n var nl = \"\\n\";\n var ht = \"\";\n for (var ppty in obj) {\n ht += ppty + \"=\" + obj[ppty] + nl;\n }\n return ht;\n}" ]
[ "0.69463766", "0.6889968", "0.6595303", "0.6542297", "0.62997997", "0.59456205", "0.59136266", "0.58243036", "0.5760578", "0.5734781", "0.5717844", "0.5699025", "0.56614965", "0.5632451", "0.56161517", "0.55903566", "0.5588703", "0.5556608", "0.5542931", "0.5506107", "0.54973423", "0.54629487", "0.54581684", "0.5451164", "0.54164284", "0.5411644", "0.5397821", "0.53885883", "0.53856194", "0.5361693", "0.53600454", "0.5347306", "0.52999043", "0.5296969", "0.5284685", "0.5269847", "0.52647245", "0.52647245", "0.52647245", "0.52613074", "0.5250094", "0.5243435", "0.524232", "0.52310866", "0.5229767", "0.5226725", "0.52240664", "0.5215225", "0.51988876", "0.51858103", "0.5182564", "0.5167883", "0.51447374", "0.51446015", "0.51116925", "0.51090455", "0.5084587", "0.5079546", "0.50543815", "0.5046686", "0.504565", "0.5040404", "0.5040404", "0.5040404", "0.5040404", "0.50322473", "0.50126034", "0.50036675", "0.5002006", "0.49990207", "0.4995086", "0.49768397", "0.4968313", "0.49597108", "0.49593407", "0.4951695", "0.49399462", "0.4936764", "0.49190724", "0.4913773", "0.49129432", "0.49101377", "0.4908361", "0.4908107", "0.4906286", "0.4901316", "0.48981124", "0.488265", "0.48822385", "0.4881082", "0.48793995", "0.4876663", "0.4876663", "0.4876663", "0.4876663", "0.48691034", "0.48664325", "0.48653182", "0.48605815", "0.48522282" ]
0.55092984
19
Read as "blank x" (verb, noun) meaning "set x to undefined"
function __(x) { x = undefined; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "set normal(value) {}", "set normal(value) {}", "set Normal(value) {}", "function ruleEmpty(meta, lex) {\n meta.transcript = (meta.transcript === '') ? '' : meta.transcript || lex\n}", "set None(value) {}", "set None(value) {}", "set None(value) {}", "set None(value) {}", "set force(value) {}", "function blank() {\n\t return '_:b' + blankId++;\n\t }", "function blank() {\n return '_:b' + blankId++;\n }", "function reset()\n\t{\n\t\tsetValue('')\n\t}", "set Ignore(value) {}", "set normalized(value) {}", "function recordEmptySpace(number) {\n\temptySpace = number;\n}", "set Raw(value) {}", "reset(valueToo) {\n this.target = this.defaultValue;\n if(valueToo) this.o[this.pn] = this.defaultValue;\n }", "function nospaces(t){\n\t\tif(t.value.match(/\\s/g)){\n\t\t\tt.value = t.value.replace(/\\s/g,'');\n\t\t}\n\t}", "function clearField(x) {\n\t x.value = '';\n\t}", "static set zero(value) {}", "fixBlankLines(){\n\t\tconst settingName = \"language-roff.blankLineReplacement\";\n\t\tconst replacement = atom.config.get(settingName) || \".\";\n\t\t\n\t\tthis.replace(/^[ \\t]*$/gm, match => {\n\t\t\tconst {range, replace} = match;\n\t\t\tconst {scopes} = ed.scopeDescriptorForBufferPosition(range.start);\n\t\t\tif(-1 === scopes.indexOf(\"comment.block.ignored-input.roff\")\n\t\t\t&& -1 === scopes.indexOf(\"meta.function.definition.request.de.roff\")\n\t\t\t&& -1 === scopes.indexOf(\"meta.function.definition.request.am.roff\")\n\t\t\t&& -1 === scopes.indexOf(\"string.unquoted.roff\"))\n\t\t\t\treplace(replacement);\n\t\t});\n\t}", "function verifUndefined(){\n if($scope.adress===undefined){\n $scope.adress=\"\";\n }\n if($scope.codeP===undefined){\n $scope.codeP=\"\";\n }\n if($scope.ville===undefined){\n $scope.ville=\"\";\n }\n if($scope.montant===undefined){\n $scope.montant=0;\n }\n }", "function emptyWord(obj) {\n\tfor (var i = 0; i < game.fullWord.length; i++) {\n\t\tgame.dashes.push(\"_ \");\n\t}\n}", "function clear() {\n state = {\n operandOne: \"0\",\n operandTwo: undefined,\n operation: undefined,\n result: undefined\n };\n }", "function clear(value) {\n\t// console.log(value);\n\tif(value === \"C\")\n\t{\n\t\tbuffer = \"0\";\n\t}\n}", "function BlankArgument() {\n this.text = '';\n this.prefix = '';\n this.suffix = '';\n}", "applyDefaultToUndefined(field, data) {\n if(data[field] === undefined && this.model[field].default !== undefined)\n data[field] = this.model[field].default;\n }", "set human(value) {}", "function clearInput(){\n\tpenultimateword = previousword;\n\tpenultimateword = wordcheck(penultimateword,'zzzzz')\n\tpreviousword = typedword.join(\"\");\n\tpreviousword = wordcheck(previousword,'yyyyy')\n\ttypedword = [];\n\tevalword = \"\";\n\tbasechoicearray = [];\n\tABarray = [];\n\tABCarray = [];\n\tfinalchoicearray = [];\n\tpotentialword = true;\n\tpredictNext();\n}", "clear() {\n this.value = undefined;\n }", "function makingInputEmpty(input){\n input.value = \"\";\n}", "function putzero(e)\n {\n e.target.value==='' && change(0,index)\n }", "set Force(value) {}", "function clear() {\n op = '';\n a = '';\n b = '';\n displayValue = '0';\n}", "clearTitle() {\n this.inputValue = \"\";\n this.not_found = false;\n }", "makeEmpty() {\n this.setValue(0);\n }", "reset(command) {\n if (this.status[command]) {\n this.status[command] = 0;\n }\n }", "function resetFirstValue()\n{\n firstValue = ``;\n}", "reset() {\n this.string = this.axiom\n }", "function none(value) {\n\treturn value\n}", "set(v) { /* empty */ }", "function normalizeState(val) {\n if (val === null || typeof val === 'undefined')\n return ' ';\n val = (\"\" + val).trim();\n if (val === \"\")\n return \" \";\n else\n return val;\n}", "function reset (p, def) {\r if (p.isModified){\r if (p.expression!==\"\") p.expression = \"\";\r while (p.numKeys>0) p.removeKey(1);\r p.setValue(def);\r };\r return;\r}", "function orBlank(v) {\n return v === undefined ? '' : v;\n}", "function orBlank(v) {\n return v === undefined ? '' : v;\n}", "function nullf(){}", "function function_setnull(fieldname){\n var result = '';\n return result;\n}", "set full(value) {\n if (value) {\n this._namedArgs.full = \"1\";\n } else {\n delete this._namedArgs[\"full\"];\n }\n }", "function Blank() {}", "function Blank() {}", "function Blank() {}", "function Blank() {}", "function Blank() {}", "static _resetBlankNodePrefix() {\n blankNodePrefix = 0;\n }", "set x(value) {}", "getEmpty() {\n\t\treturn this.direction[4][0];\n\t}", "clear() {\n this.value = \"\";\n }", "set x(value = 42) {}", "function emptyinput(input){\n input.value = '';\n}", "function clearValue(val) {\n\tif(val) {\n\t\tval = undefined;\n\t}\n}", "function checkDefined(property) {\n\t\tif (property) {return property} else {return ' '};\n\t\t}", "function _undefinedCoerce() {\n return '';\n}", "reset() {\n this.currentOperand = '0';\n this.previousOperand = '';\n this.operation = undefined;\n }", "function fixDeformedData(data) {\n Object.keys(data).forEach(function (key) {\n if (data[key] === \"\") {\n data[key] = \"0\";\n }\n });\n return data;\n}", "function returnUndefined() {}", "function toUndefined(ma) {\n return isNone(ma) ? undefined : ma.value;\n}", "function notNullOrUndefined (x) {\n if (x === null || x === undefined) {\n throw 'Expected a value, but got ' + x;\n }\n\n return x;\n }", "function displaySecretWordBlank() {\n\tvar bLine = \"\";\n\tfor (var i=0; i<secretWord.length; i++) {\n\t\tif (blank[i] !== blankSpace) {\n\t\t\tbLine = bLine + blank[i] + \" \";\n\t\t} else {\n\t\t\tbLine = bLine + blankSpace;\n\t\t} \n\t}\n\t$(\"#secret\").val(bLine); \n\tcheckWin();\n}", "function fillField(event){\n\t\tvar inputVal = $.trim($(this).val());\n\t\tif(inputVal === 0){\n\t\t\t$(this).val($(this).data(\"defaultValue\"));\n\t\t}\n\t}", "_readPredicateAfterBlank(token) {\n switch (token.type) {\n case '.':\n case '}':\n // No predicate is coming if the triple is terminated here\n this._subject = null;\n return this._readPunctuation(token);\n default:\n return this._readPredicate(token);\n }\n }", "_readPredicateAfterBlank(token) {\n switch (token.type) {\n case '.':\n case '}':\n // No predicate is coming if the triple is terminated here\n this._subject = null;\n return this._readPunctuation(token);\n\n default:\n return this._readPredicate(token);\n }\n }", "function yell(name){\n\tif(name==null || name==\"\") {\n\t\tname = ' ';\n\t}\n}", "_isSet(value) {\n if (value) {\n return value;\n } else {\n return 'no data :('\n }\n }", "function no(t) {\n return ho.Qn(t, Xi.store);\n}", "setEmpty() {\n this.filled = false;\n this.color = null;\n }", "function myFunction(){\r\n\t\tif (document.getElementById('textview').value === 'undefined') {\r\n\t\t\tdocument.getElementById('textview').value = 0;\r\n\t\t}\r\n\r\n\t\tif (document.getElementById('textview').value === 'Infinity') {\r\n\t\t\tdocument.getElementById('textview').value = 'fuck you';\r\n\t\t}\r\n\t\tif (document.getElementById('textview').value === '') {\r\n\t\t\tdocument.getElementById('textview').value = 0;\r\n\t\t}\r\n\t\t//document.getElementById('textview').value = \"\"\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n}", "function reset() {\n updateFormula(function() {\n return \"\";\n }, true);\n }", "handleEmptyValue() {\n if (!this.get('value') || this.get('value') === '') {\n this.set('value', 'Empty');\n }\n }", "set Baked(value) {}", "function clear() {\n commandLine.value = '';\n phantomUserInput.innerHTML = '';\n }", "function text0(t){\n\tif(t!=undefined && t.length!=undefined)\n\t\treturn t;\n\telse\n\t\treturn \"\";\n}", "function ifUndefined(x, def) {\n return x !== undefined ? x : def;\n}", "function blank(name) {\n if (typeof name === 'string') { // Only use name if a name is given\n if (name.startsWith('e_')) return Parser.factory.blankNode(name);\n return Parser.factory.blankNode('e_' + name);\n }\n return Parser.factory.blankNode('g_' + blankId++);\n }", "function clr() {\n document.getElementById(\"userInput\").value = \" \";\n}", "function dash2null(value){return (/^\\s*-+\\s*$/g.test(value))?'':value}", "function noXform_(metadata, value) {\n return value;\n}", "function noXform_(metadata, value) {\n return value;\n}", "function noXform_(metadata, value) {\n return value;\n}", "function noXform_(metadata, value) {\n return value;\n}", "function noXform_(metadata, value) {\n return value;\n}", "function noXform_(metadata, value) {\n return value;\n}", "function noXform_(metadata, value) {\n return value;\n}", "function noXform_(metadata, value) {\n return value;\n}", "clear() {\n\t\t\tthis.mutate('');\n\t\t}", "_unset(){\r\n this.currentOperator = '';\r\n this.currentValue = '';\r\n if ( this.columns.length > 1 ){\r\n this.currentField = '';\r\n }\r\n }", "function fillTheBlanks( word ) {\n console.log(\"Blanking word\");\n /*\n * Global variable blankedWord so we can use it to replace single\n * letters as they are guessed\n */\n window.blankedWord = [];\n\n for ( var letters = 0; letters < word.length; letters++ ) {\n blankedWord.push(\"_\");\n }\n\n return blankedWord;\n }", "function setInitialValue(node) {\n\tnode.textContent = resetValue();\n}", "function ifUndefined(x, def) {\n return x ?? def;\n}", "function emptyValue(){\n const message = \"No seas tímid@, atrévete a jugar y escribe un número!\";\n return paintGameTips(message);\n}", "clear() {\n this.currentOperand = ''\n this.previousOperand = ''\n this.operation = undefined\n }" ]
[ "0.6475919", "0.6475919", "0.5928419", "0.58958673", "0.5758426", "0.5758426", "0.5758426", "0.5758426", "0.55832267", "0.5498183", "0.54376215", "0.53393984", "0.5333855", "0.53226423", "0.5313265", "0.52907926", "0.52664465", "0.52548796", "0.52299476", "0.52027375", "0.51649886", "0.5163416", "0.51567775", "0.5152004", "0.51502776", "0.51469034", "0.5143234", "0.5133391", "0.5122452", "0.5118582", "0.5111221", "0.5097621", "0.5088789", "0.50804603", "0.50733477", "0.50712746", "0.50702256", "0.50469565", "0.5043448", "0.5036989", "0.5024663", "0.5022806", "0.5015636", "0.50137085", "0.50137085", "0.50009257", "0.4996524", "0.49959952", "0.4992957", "0.4992957", "0.4992957", "0.4992957", "0.4992957", "0.49709833", "0.49553397", "0.49500424", "0.4944195", "0.4938562", "0.4937767", "0.49347293", "0.4933655", "0.49272338", "0.4922509", "0.49157283", "0.4905488", "0.49053237", "0.4887696", "0.4885598", "0.4876643", "0.48659736", "0.48574567", "0.4856695", "0.485159", "0.48449397", "0.48398378", "0.4836613", "0.48360386", "0.4833418", "0.4831995", "0.48286936", "0.4825236", "0.48193982", "0.481809", "0.481046", "0.4804542", "0.48029113", "0.48029113", "0.48029113", "0.48029113", "0.48029113", "0.48029113", "0.48029113", "0.48029113", "0.479705", "0.47878253", "0.47870964", "0.4781116", "0.4779475", "0.47617278", "0.47589314" ]
0.5489486
10
Specify a proxy that is already open to us. Called by the stash.
function activateProxy(args, info) { return util_1.createMethod(Object.assign({ method: { args, name: 'activateProxy', pallet: 'democracy' } }, info)); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function setProxyWs(incoming) {\n if (incoming.get(\"ws\") && incoming.get(\"mode\") === \"proxy\") {\n return incoming.setIn([\"proxy\", \"ws\"], true);\n }\n return incoming;\n}", "SetProxy(short, bool, int, string, string) {\n\n }", "registerProxy(proxy) {\n proxy.initializeNotifier(this.multitonKey);\n this.proxyMap[proxy.getProxyName()] = proxy;\n proxy.onRegister();\n }", "function proxy(options, arg, cbDone)\n{\n console.log(\"github\",arg);\n arg.url = 'https://api.singly.com/proxy/github/repos/'+options.user+'/'+options.repo+'/git'+arg.url+'?access_token='+options.token;\n arg.json = true;\n request(arg, cbDone);\n}", "function defineProxyProperty(name,descriptor){Object.defineProperty(proxy,name,descriptor);}", "function defineProxyProperty(name,descriptor){Object.defineProperty(proxy,name,descriptor);}", "isproxy() {\n return this.state == PROXY;\n }", "addProxy(obj) {\n this.proxy = obj;\n this.target.setAttribute(\"id\", \"proxyOf\" + obj.parentElement.id);\n }", "function defineProxyProperty(name, descriptor) {\n\t Object.defineProperty(proxy, name, descriptor);\n\t }", "function defineProxyProperty(name, descriptor) {\n\t Object.defineProperty(proxy, name, descriptor);\n\t }", "function defineProxyProperty(name, descriptor) {\n Object.defineProperty(proxy, name, descriptor);\n }", "function defineProxyProperty(name, descriptor) {\n Object.defineProperty(proxy, name, descriptor);\n }", "function defineProxyProperty(name, descriptor) {\n Object.defineProperty(proxy, name, descriptor);\n }", "function defineProxyProperty(name, descriptor) {\n Object.defineProperty(proxy, name, descriptor);\n }", "function defineProxyProperty(name, descriptor) {\n Object.defineProperty(proxy, name, descriptor);\n }", "function defineProxyProperty(name, descriptor) {\n Object.defineProperty(proxy, name, descriptor);\n }", "function defineProxyProperty(name, descriptor) {\n Object.defineProperty(proxy, name, descriptor);\n }", "function defineProxyProperty(name, descriptor) {\n Object.defineProperty(proxy, name, descriptor);\n }", "attachProxy() {\n var _a;\n\n if (!this.proxyInitialized) {\n this.proxyInitialized = true;\n this.proxy.style.display = \"none\";\n this.proxyEventsToBlock.forEach(name => this.proxy.addEventListener(name, this.stopPropagation)); // These are typically mapped to the proxy during\n // property change callbacks, but during initialization\n // on the initial call of the callback, the proxy is\n // still undefined. We should find a better way to address this.\n\n this.proxy.disabled = this.disabled;\n this.proxy.required = this.required;\n\n if (typeof this.name === \"string\") {\n this.proxy.name = this.name;\n }\n\n if (typeof this.value === \"string\") {\n this.proxy.value = this.value;\n }\n\n this.proxy.setAttribute(\"slot\", proxySlotName);\n this.proxySlot = document.createElement(\"slot\");\n this.proxySlot.setAttribute(\"name\", proxySlotName);\n }\n\n (_a = this.shadowRoot) === null || _a === void 0 ? void 0 : _a.appendChild(this.proxySlot);\n this.appendChild(this.proxy);\n }", "function Proxy(){}", "function Proxy(){}", "createProxy() {\n invariant(this.pubsub, 'Redis PubSub has not been started');\n\n this.debug(`Requesting proxy`);\n\n // listen to offers of proxies\n this.pubsub.onceMessage(NETWORK_PROXY_OFFER, this.onProxyOffer);\n\n // Emits a proxy request each x seconds\n const emitProxyRequest = this.pubsub.send.bind(this.pubsub, NETWORK_PROXY_REQUEST);\n this.proxyRequesterInterval = setInterval(emitProxyRequest, this.requestInterval);\n emitProxyRequest();\n\n // If no response in a long time commit suicide\n this.proxyRequesterTimeout = setTimeout(this.onTimeout, this.requestTimeout);\n }", "setProxyOptions() {\n if (this.proxy instanceof HTMLSelectElement && this.options) {\n this.proxy.options.length = 0;\n this.options.forEach(option => {\n const proxyOption = option.proxy || (option instanceof HTMLOptionElement ? option.cloneNode() : null);\n\n if (proxyOption) {\n this.proxy.appendChild(proxyOption);\n }\n });\n }\n }", "showProxySettings() {}", "function get(){return proxy;}", "function get(){return proxy;}", "function SetMergeProxySymbol(oProj)\n{\n\ttry\n\t{\n\t\t// if merging proxy/stub, proj will have dlldatax.c\n\t\tif (!oProj.Object.Files(\"dlldatax.c\"))\n\t\t\treturn;\n\n\t\t// add _MERGE_PROXYSTUB if necessary\n\t\tvar oConfigs = oProj.Object.Configurations;\n\t\tfor (var nCntr = 1; nCntr <= oConfigs.Count; nCntr++)\n\t\t{\n\t\t\tvar oConfig = oConfigs(nCntr);\n\t\t\tvar oCLTool = oConfig.Tools(\"VCCLCompilerTool\");\n\t\t\tif (-1 == oCLTool.PreprocessorDefinitions.indexOf(\"_MERGE_PROXYSTUB\"))\n\t\t\t\toCLTool.PreprocessorDefinitions += \";_MERGE_PROXYSTUB\";\n\t\t}\n\t}\n\tcatch(e)\n\t{\n\t\tthrow e;\n\t}\n}", "proxy(id) {\n let proxy = new Frame(this);\n proxy.state = PROXY;\n proxy.slots = [this.id, id];\n this.frames.set(id, proxy);\n return proxy;\n }", "retrieveProxy(proxyName) {\n return this.proxyMap[proxyName];\n }", "function Proxy () {\n log.info('Proxy constructor');\n var self = this;\n\n this.proxy = httpProxy.createProxyServer({});\n this.proxy.on('error', function (err, req/*, proxiedRes */) {\n var res = req.res;\n var logData = {\n tx: true,\n err: err,\n req: req\n };\n log.error(logData, 'proxy.on error');\n /**\n * we need to keep the didError logic. sometimes (not sure why) but we try to proxy the same\n * request twice (in some network cases) and navi will crash saying you can't send on a request\n * that is already ended\n */\n if (!req.didError) {\n req.didError = true;\n var errorUrl = errorPage.generateErrorUrl('unresponsive', {\n shortHash: req.shortHash,\n elasticUrl: req.elasticUrl\n });\n var targetHost = getHostAndAugmentReq(req, errorUrl);\n log.trace(put({\n targetHost: targetHost,\n errorUrl: errorUrl\n }, logData), 'proxy.on error !req.didError');\n self.proxy.web(req, res, { target: targetHost });\n } else {\n log.trace(logData, 'proxy.on error req.didError');\n }\n });\n\n /**\n * Listen to proxy events for timing logs\n */\n this.proxy.on('proxyReq', function () {\n log.trace({\n tx: true\n }, 'proxy.on proxyReq');\n });\n\n this.proxy.on('proxyRes', function (proxyRes, req, proxiedRes) {\n var res = req.res;\n var targetInstanceName = keypather.get(req, 'targetInstance.attrs.name');\n log.trace({\n tx: true,\n targetInstanceName: targetInstanceName,\n res: res\n }, 'proxy.on proxyRes');\n self._addHeadersToRes(req, proxyRes, targetInstanceName);\n self._streamRes(proxyRes, proxiedRes, res, keypather.get(req, 'naviEntry.redirectEnabled'));\n });\n}", "function connect(req, socket, head){\n\t\t\t// Check auth\n if (self._token) {\n if (!req.headers['proxy-authorization'] || req.headers['proxy-authorization'] !== self._token) {\n\t\t\t\t\twinston.error('[Master] Error: Wrong proxy credentials for CONNECT method');\n\t\t\t\t\tsocket.write('HTTP/1.1 407\\r\\nConnection: close\\r\\nProxy-Authenticate: Basic realm=\"scrapoxy\"\\r\\n\\r\\n');\n return socket.end();\n }\n }\n\t\t\t\n\t\t\t// Decrypt target\n\t\t\tparseTarget(req.url, (err, target) => {\n\t\t\t\tif (err) {\n\t\t\t\t\twinston.error('Error (parsing): ', err);\n\t\t\t\t\treturn socket.end();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t// Trigger scaling if necessary\n\t\t\t\tself._manager.requestReceived();\n\t\n\t\t\t\t// Get domain\n\t\t\t\tconst uri = domain.convertHostnamePathToUri(target.hostname, target.url);\n\t\t\t\tconst basedomain = domain.getBaseDomainForUri(uri);\n\t\n\t\t\t\t// Find instance\n\t\t\t\tconst forceName = req.headers['x-cache-proxyname'],\n\t\t\t\t\tinstance = self._manager.getNextRunningInstanceForDomain(basedomain, forceName);\n\t\n\t\t\t\tif (!instance) {\n\t\t\t\t\twinston.error('[Master] Error: No running instance found');\n\t\t\t\t\tsocket.write('HTTP/1.1 500 Error: No running instance found\\r\\n\\r\\n');\n return socket.end();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t// Build Connect request for Instance\n\t\t\t\tconst proxyOpts = {\n\t\t\t\t\thost: instance.proxyParameters.hostname,\n\t\t\t\t\tport: instance.proxyParameters.port,\n\t\t\t\t\tmethod: 'CONNECT',\n\t\t\t\t\theaders: req.headers, //Useless...\n \tpath: req.url\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\t // Update headers\n \t\tinstance.updateRequestHeaders(proxyOpts.headers);\n\n\t\t\t\t\n\t\t\t\tvar proxy_connect_request = http.request(proxyOpts);\n\t\t\t\t\n\t\t\t\t// Start timer\n \tconst start = process.hrtime();\n\t\t\t\t\n\t\t\t\tproxy_connect_request.on('connect', function (routing_req, routing_socket, routing_head) {\n\t\t\t\t\tsocket.on('error', (err) => {\n\t\t\t\t\t\twinston.error('Error (socket): ', err);\n\t\t\t\t\t\trouting_socket.end();\n\t\t\t\t\t});\n\t\t\t\n\t\t\t\t\trouting_socket.on('error', (err) => {\n\t\t\t\t\t\twinston.error('Error (routing_socket): ', err);\n\t\t\t\t\t\tsocket.write('HTTP/1.1 500 Error (routing_socket): Target closed connection\\r\\n\\r\\n');\n\t\t\t\t\t\tsocket.end();\n\t\t\t\t\t});\n\t\t\t\t\tsocket.write('HTTP/1.1 200 Connection established\\r\\n\\r\\n');\n\t\t\t\t\trouting_socket.pipe(socket);\n\t\t\t\t\tsocket.pipe(routing_socket);\n\t\t\t\t});\n\t\t\t\t\n\t\t\t\tsocket.on('end', function () {\n\t\t\t\t\t\t// Stop timer and record duration when Tunnel connexion is closed\n\t\t\t\t\t\tconst duration = process.hrtime(start);\n\t\t\t\t\t\tself._stats.requestEnd(\n\t\t\t\t\t\t\tduration,\n\t\t\t\t\t\t\tsocket._bytesDispatched,\n\t\t\t\t\t\t\tsocket.bytesRead\n\t\t\t\t\t\t);\n\t\t\t\t\t\tinstance.incrRequest();\n\t\t\t\t});\n\t\t\t\t\n\t\t\t\t// Log errors\n\t\t\t\tproxy_connect_request.on('error',\n\t\t\t\t\t(err) => {\n\t\t\t\t\t\twinston.error('[Master] Error: request error from client (%s %s on instance %s):', req.method, req.url, instance.toString(), err);\n\t\t\t\t\t\tsocket.write('HTTP/1.1 500 Error: request error from client\\r\\n\\r\\n');\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t\n\t\t\t\t// End Connect Request\n\t\t\t\tproxy_connect_request.end();\n\t\t\t\t\n\t\t\t\t\n\t\t\t});\n\t\t\t\n\t\t\tfunction parseTarget(url, callback) {\n\t\t\t\tif (!url) return callback('No URL found');\n\t\t\t\n\t\t\t\tconst part = url.split(':');\n\t\t\t\tif (part.length !== 2) {\n\t\t\t\t\treturn callback(`Cannot parse target: ${url}`);\n\t\t\t\t}\n\t\t\t\n\t\t\t\tconst hostname = part[0],\n\t\t\t\t\tport = parseInt(part[1]);\n\t\t\t\n\t\t\t\tif (!hostname || !port) {\n\t\t\t\t\treturn callback(`Cannot parse target (2): ${url}`);\n\t\t\t\t}\n\t\t\t\n\t\t\t\tcallback(null, {hostname, port});\n\t\t\t}\n\t\t\t\n\t\t}", "_initFlyOverWaypoint() {\n this._isFlyOverWaypoint = true;\n }", "function FindProxyForURLByAutoProxy(url, host) {\n\nreturn \"DIRECT\";\n}", "[kUsePreferredAddress](address) {\n process.nextTick(() => {\n try {\n this.emit('usePreferredAddress', address);\n } catch (error) {\n this.destroy(error);\n }\n });\n }", "createProxy() {\r\n return this;\r\n }", "attachTo(proxy) {\n proxy.on('proxyRes', (proxyRes, req) => {\n if (req.method !== 'POST' || req.path !== '/api/v1/plugins/') {\n return;\n }\n if (proxyRes.statusCode !== 201 || proxyRes.statusMessage !== 'Created') {\n print(colors.bold(colors.red('Store upload failed: '\n + `${proxyRes.statusCode} ${proxyRes.statusMessage}`)));\n return;\n }\n const buffer = [];\n proxyRes.on('data', chunk => buffer.push(chunk));\n proxyRes.on('end', () => {\n const body = JSON.parse(Buffer.concat(buffer).toString());\n this.registerAndRun(body);\n });\n });\n }", "hasProxy(proxyName) {\n return this.proxyMap[proxyName] != null;\n }", "function defineProxyPropertyWithValue(name,value){var _ref=Object.getOwnPropertyDescriptor(current,name)||{};var _ref$enumerable=_ref.enumerable;var enumerable=_ref$enumerable===undefined?false:_ref$enumerable;var _ref$writable=_ref.writable;var writable=_ref$writable===undefined?true:_ref$writable;defineProxyProperty(name,{configurable:true,enumerable:enumerable,writable:writable,value:value});}", "function defineProxyPropertyWithValue(name,value){var _ref=Object.getOwnPropertyDescriptor(current,name)||{};var _ref$enumerable=_ref.enumerable;var enumerable=_ref$enumerable===undefined?false:_ref$enumerable;var _ref$writable=_ref.writable;var writable=_ref$writable===undefined?true:_ref$writable;defineProxyProperty(name,{configurable:true,enumerable:enumerable,writable:writable,value:value});}", "function warehouse_proxy(req, reply){\n //logger.request(req);\n\n reception.emit('digger:warehouse', req, reply);\n }", "function defineProxyPropertyWithValue(name, value) {\n\t var _ref = Object.getOwnPropertyDescriptor(current, name) || {};\n\n\t var _ref$enumerable = _ref.enumerable;\n\t var enumerable = _ref$enumerable === undefined ? false : _ref$enumerable;\n\t var _ref$writable = _ref.writable;\n\t var writable = _ref$writable === undefined ? true : _ref$writable;\n\n\n\t defineProxyProperty(name, {\n\t configurable: true,\n\t enumerable: enumerable,\n\t writable: writable,\n\t value: value\n\t });\n\t }", "function defineProxyPropertyWithValue(name, value) {\n\t var _ref = Object.getOwnPropertyDescriptor(current, name) || {};\n\n\t var _ref$enumerable = _ref.enumerable;\n\t var enumerable = _ref$enumerable === undefined ? false : _ref$enumerable;\n\t var _ref$writable = _ref.writable;\n\t var writable = _ref$writable === undefined ? true : _ref$writable;\n\n\n\t defineProxyProperty(name, {\n\t configurable: true,\n\t enumerable: enumerable,\n\t writable: writable,\n\t value: value\n\t });\n\t }", "function socksProxy (proxy, secure) {\n return new SocksProxyAgent(proxy, secure);\n}", "function get() {\n return proxy;\n }", "function get() {\n return proxy;\n }", "function get() {\n return proxy;\n }", "function get() {\n return proxy;\n }", "function get() {\n return proxy;\n }", "function get() {\n return proxy;\n }", "function get() {\n return proxy;\n }", "function get() {\n return proxy;\n }", "async currentProxy() {\n return this._currentAddress === this.get('web3').currentAddress()\n ? this._currentProxy\n : this.getProxyAddress();\n }", "function defineProxyPropertyWithValue(name, value) {\n var _ref = Object.getOwnPropertyDescriptor(current, name) || {};\n\n var _ref$enumerable = _ref.enumerable;\n var enumerable = _ref$enumerable === undefined ? false : _ref$enumerable;\n var _ref$writable = _ref.writable;\n var writable = _ref$writable === undefined ? true : _ref$writable;\n\n\n defineProxyProperty(name, {\n configurable: true,\n enumerable: enumerable,\n writable: writable,\n value: value\n });\n }", "function defineProxyPropertyWithValue(name, value) {\n var _ref = Object.getOwnPropertyDescriptor(current, name) || {};\n\n var _ref$enumerable = _ref.enumerable;\n var enumerable = _ref$enumerable === undefined ? false : _ref$enumerable;\n var _ref$writable = _ref.writable;\n var writable = _ref$writable === undefined ? true : _ref$writable;\n\n\n defineProxyProperty(name, {\n configurable: true,\n enumerable: enumerable,\n writable: writable,\n value: value\n });\n }", "function defineProxyPropertyWithValue(name, value) {\n var _ref = Object.getOwnPropertyDescriptor(current, name) || {};\n\n var _ref$enumerable = _ref.enumerable;\n var enumerable = _ref$enumerable === undefined ? false : _ref$enumerable;\n var _ref$writable = _ref.writable;\n var writable = _ref$writable === undefined ? true : _ref$writable;\n\n\n defineProxyProperty(name, {\n configurable: true,\n enumerable: enumerable,\n writable: writable,\n value: value\n });\n }", "function defineProxyPropertyWithValue(name, value) {\n var _ref = Object.getOwnPropertyDescriptor(current, name) || {};\n\n var _ref$enumerable = _ref.enumerable;\n var enumerable = _ref$enumerable === undefined ? false : _ref$enumerable;\n var _ref$writable = _ref.writable;\n var writable = _ref$writable === undefined ? true : _ref$writable;\n\n\n defineProxyProperty(name, {\n configurable: true,\n enumerable: enumerable,\n writable: writable,\n value: value\n });\n }", "function defineProxyPropertyWithValue(name, value) {\n var _ref = Object.getOwnPropertyDescriptor(current, name) || {};\n\n var _ref$enumerable = _ref.enumerable;\n var enumerable = _ref$enumerable === undefined ? false : _ref$enumerable;\n var _ref$writable = _ref.writable;\n var writable = _ref$writable === undefined ? true : _ref$writable;\n\n\n defineProxyProperty(name, {\n configurable: true,\n enumerable: enumerable,\n writable: writable,\n value: value\n });\n }", "function defineProxyPropertyWithValue(name, value) {\n var _ref = Object.getOwnPropertyDescriptor(current, name) || {};\n\n var _ref$enumerable = _ref.enumerable;\n var enumerable = _ref$enumerable === undefined ? false : _ref$enumerable;\n var _ref$writable = _ref.writable;\n var writable = _ref$writable === undefined ? true : _ref$writable;\n\n\n defineProxyProperty(name, {\n configurable: true,\n enumerable: enumerable,\n writable: writable,\n value: value\n });\n }", "function defineProxyPropertyWithValue(name, value) {\n var _ref = Object.getOwnPropertyDescriptor(current, name) || {};\n\n var _ref$enumerable = _ref.enumerable;\n var enumerable = _ref$enumerable === undefined ? false : _ref$enumerable;\n var _ref$writable = _ref.writable;\n var writable = _ref$writable === undefined ? true : _ref$writable;\n\n\n defineProxyProperty(name, {\n configurable: true,\n enumerable: enumerable,\n writable: writable,\n value: value\n });\n }", "function defineProxyPropertyWithValue(name, value) {\n var _ref = Object.getOwnPropertyDescriptor(current, name) || {};\n\n var _ref$enumerable = _ref.enumerable;\n var enumerable = _ref$enumerable === undefined ? false : _ref$enumerable;\n var _ref$writable = _ref.writable;\n var writable = _ref$writable === undefined ? true : _ref$writable;\n\n\n defineProxyProperty(name, {\n configurable: true,\n enumerable: enumerable,\n writable: writable,\n value: value\n });\n }", "function initProxySettings()\n{\n let proxyType, proxyAddrPort, proxyUsername, proxyPassword;\n let reply = gProtocolSvc.TorGetConfStr(kTorConfKeySocks4Proxy, null);\n if (!gProtocolSvc.TorCommandSucceeded(reply))\n return false;\n\n if (reply.retVal)\n {\n proxyType = \"SOCKS4\";\n proxyAddrPort = reply.retVal;\n }\n else\n {\n reply = gProtocolSvc.TorGetConfStr(kTorConfKeySocks5Proxy, null);\n if (!gProtocolSvc.TorCommandSucceeded(reply))\n return false;\n\n if (reply.retVal)\n {\n proxyType = \"SOCKS5\";\n proxyAddrPort = reply.retVal;\n reply = gProtocolSvc.TorGetConfStr(kTorConfKeySocks5ProxyUsername, null);\n if (!gProtocolSvc.TorCommandSucceeded(reply))\n return false;\n\n proxyUsername = reply.retVal;\n reply = gProtocolSvc.TorGetConfStr(kTorConfKeySocks5ProxyPassword, null);\n if (!gProtocolSvc.TorCommandSucceeded(reply))\n return false;\n\n proxyPassword = reply.retVal;\n }\n else\n {\n reply = gProtocolSvc.TorGetConfStr(kTorConfKeyHTTPSProxy, null);\n if (!gProtocolSvc.TorCommandSucceeded(reply))\n return false;\n\n if (reply.retVal)\n {\n proxyType = \"HTTP\";\n proxyAddrPort = reply.retVal;\n reply = gProtocolSvc.TorGetConfStr(\n kTorConfKeyHTTPSProxyAuthenticator, null);\n if (!gProtocolSvc.TorCommandSucceeded(reply))\n return false;\n\n let values = parseColonStr(reply.retVal);\n proxyUsername = values[0];\n proxyPassword = values[1];\n }\n }\n }\n\n let haveProxy = (proxyType != undefined);\n setElemValue(kUseProxyCheckbox, haveProxy);\n setElemValue(kProxyTypeMenulist, proxyType);\n if (!proxyType)\n showMenuListPlaceholderText(kProxyTypeMenulist);\n\n onProxyTypeChange();\n\n let proxyAddr, proxyPort;\n if (proxyAddrPort)\n {\n let values = parseColonStr(proxyAddrPort);\n proxyAddr = values[0];\n proxyPort = values[1];\n }\n\n setElemValue(kProxyAddr, proxyAddr);\n setElemValue(kProxyPort, proxyPort);\n setElemValue(kProxyUsername, proxyUsername);\n setElemValue(kProxyPassword, proxyPassword);\n\n return true;\n} // initProxySettings", "function next (multiaddr) {\n const conn = t.dial(multiaddr, () => {\n proxyConn.setInnerConn(conn)\n callback(null, proxyConn)\n })\n }", "removeProxy() {\n const me = this;\n if (me.proxy) {\n me.proxy.remove();\n me.resize.destroy();\n me.proxy = me.resize = null;\n\n // This CSS class is to block further drag creates when one is in progress (like awaiting async finalization)\n me.client.element.classList.remove('b-dragcreating');\n // This CSS class is to block hover for other events during actually dragging the proxy\n me.client.element.classList.remove('b-dragcreating-proxy-sizing');\n me.tip && me.tip.hide();\n }\n }", "function RosterProxy(service) {\n this.service = service;\n this.helpers = new Helpers();\n}", "removeProxy() {\n const me = this;\n\n if (me.proxy) {\n me.proxy.remove();\n me.resize.destroy();\n me.proxy = me.resize = null; // This CSS class is to block further drag creates when one is in progress (like awaiting async finalization)\n\n me.client.element.classList.remove('b-dragcreating'); // This CSS class is to block hover for other events during actually dragging the proxy\n\n me.client.element.classList.remove('b-dragcreating-proxy-sizing');\n me.tip && me.tip.hide();\n }\n }", "function proxy(resp, headers) {\n if (!defaults.proxyURL) {\n return abort404(resp, 'Request Timeout');\n }\n request(defaults.proxyURL, headers, defaults.proxyTimeout, function(err, proxyResp) {\n if (err) {\n return abort404(resp, 'Proxy failed: ' + err.message);\n }\n if (proxyResp.statusCode === 200) {\n return success(resp, proxyResp);\n }\n return abort404(resp, 'Proxy with: ' + proxyResp.statusCode);\n });\n}", "function proxyServer(options) {\n this.port = 9393;\n this.onServerError = function() {};\n this.onBeforeRequest = function() {};\n this.onBeforeResponse = function() {};\n this.onRequestError = function() {};\n\n fs.readFile('./websites.json', (err, data) =>{\n if(err) throw err;\n\n blockList = JSON.parse(data);\n for(var i =0; i<blockList.websites.length; i++){\n console.log(blockList.websites[i].address);\n map.set(blockList.websites[i].address, \"block\");\n }\n });\n\n fs.readFile('./cached.json', (err,data) => {\n if(err) throw err;\n\n cache = JSON.parse(data);\n });\n\n}", "function browserSyncProxy(url, done) {\r\n\r\n const cfg = browserSyncProxyConf();\r\n cfg.proxy.target = url;\r\n cfg.port = config.browsersync.port;\r\n cfg.open = config.browsersync.openBrowser;\r\n\r\n imports.browserSync.init(cfg);\r\n\r\n if(done) {\r\n done();\r\n }\r\n\r\n }", "async setRemote({ url }) {\r\n if (!url) return;\r\n\r\n await spawnGit([\"remote\", \"add\", \"origin\", url]);\r\n }", "function proxyRemoteConnect() {\n client.proxyBusObject = new ClientBusObject(client.busAtt, OBJECT_PATH);\n client.proxyBusObject.proxyBusObject.introspectRemoteObjectAsync(null).then(function (introResult) {\n if (AllJoyn.QStatus.er_OK == introResult.status) {\n OutputLine(\"Introspection of the service bus object was successful.\");\n client.proxyBusObject.callPingMethod();\n } else {\n OutputLine(\"Introspection of the service bus object was unsuccessful.\");\n client.busAtt.leaveSession(sessionId);\n }\n });\n }", "function setOpenTiddlers(tiddlersTitles){\n var StoryList = {title:'$:/StoryList', list: tiddlersTitles};\n $tw.wiki.addTiddler( new $tw.Tiddler(StoryList));\n }", "async proxy(request) {\n // create a new request from orginal one\n const opts = {\n mode: \"cors\",\n method: request.method,\n };\n }", "function initializeProxy() {\n try {\n // Code originally from https://github.com/yeoman/yo/blob/b2eea87e/lib/cli.js#L19-L28\n var MAJOR_NODEJS_VERSION = parseInt(process.version.slice(1).split('.')[0], 10);\n if (MAJOR_NODEJS_VERSION >= 10) {\n // `global-agent` works with Node.js v10 and above.\n require('global-agent').bootstrap();\n }\n else {\n // `global-tunnel-ng` works with Node.js v10 and below.\n require('global-tunnel-ng').initialize();\n }\n }\n catch (e) {\n d('Could not load either proxy modules, built-in proxy support not available:', e);\n }\n}", "function checkProxy(){\n var proxy = JonDoSwitcher.getProxy();\n if(proxy == \"JonDo\"){\n window.top.document.getElementById(\"enableJonDo\").style.display = \"none\";\n window.top.document.getElementById(\"jondo-switcher-message\").value = JonDoSwitcher.stringsBundle.GetStringFromName(\"connectedToJondo\") + \" \";\n // start socket connecting\n JonDoCommunicator.startSocketConnecting();\n }else if(proxy == \"Tor\"){\n window.top.document.getElementById(\"enableTor\").style.display = \"none\";\n window.top.document.getElementById(\"jondo-switcher-message\").value = JonDoSwitcher.stringsBundle.GetStringFromName(\"connectedToTor\") + \" \"; \n }else if(proxy == \"Direct\"){\n window.top.document.getElementById(\"disableAllProxies\").style.display = \"none\";\n window.top.document.getElementById(\"jondo-switcher-message\").value = JonDoSwitcher.stringsBundle.GetStringFromName(\"connectedDirectly\") + \" \"; \n }\n if(proxy != \"Unknown\"){\n clearInterval(checkProxyTimerObj);\n checkProxyTimerObj = null;\n // show survey info if not done already\n showSurveyInfo();\n }\n\tlet prefsBranch = prefsService.getBranch(\"extensions.jondoswitcher.\");\n if(prefsBranch){\n\t\tif(prefsBranch.getIntPref(\"switched_once\") == 0){\n\t\t\twindow.top.document.getElementById(\"alert_arrow\").hidden = false;\n\t\t}\n\t\t\n\t}\n}", "function pacProxy (proxy, secure) {\n var agent = new PacProxyAgent(proxy);\n agent.secureEndpoint = secure;\n return agent;\n}", "onProxyLinkDown() {\n this.debug('provider droped proxy, getting a new one');\n this.emit(USER_PROXY_DOWN, CLIENT_PROXY_LINK_DROP);\n this.proxy.stop();\n this.proxy = null;\n this.removeHandlers();\n this.getProxy();\n }", "function setDefaultStateProxy(el) {\n el.stateProxy = elementStateProxy;\n var textContent = el.getTextContent();\n var textGuide = el.getTextGuideLine();\n\n if (textContent) {\n textContent.stateProxy = elementStateProxy;\n }\n\n if (textGuide) {\n textGuide.stateProxy = elementStateProxy;\n }\n}", "repickHost() {\n this.host = null;\n var newHostId = Object.keys(this.socketNames)[0];\n this.host = newHostId ? newHostId : null;\n }", "function setupProxy() {\n var globalAgent = require('global-agent');\n var globalTunnel = require('global-tunnel-ng');\n var proxyAddress = getProxyAndSetupEnv();\n\n const NODEJS_VERSION = parseInt(process.version.slice(1).split('.')[0], 10);\n if (NODEJS_VERSION >= 10 && proxyAddress) {\n // `global-agent` works with Node.js v10 and above.\n globalAgent.bootstrap();\n global.GLOBAL_AGENT.HTTP_PROXY = proxyAddress;\n } else {\n // `global-tunnel-ng` works only with Node.js v10 and below.\n globalTunnel.initialize();\n }\n}", "function hook() {\n var origRequire = Module.prototype.require;\n var _require = function(context, path) {\n return origRequire.call(context, path);\n };\n\n Module.prototype.require = function(path) {\n if(path === \"discord.js\") {\n return proxy;\n }\n\n return _require(this, path);\n };\n}", "function __proxyObj(origObj, proxyObj, funkList) {\n\t\tfor (var v in funkList) {\n\t\t\torigObj[funkList[v]] = proxyObj[funkList[v]];\n\t\t}\n\t}", "function setDefaultStateProxy(el) {\n\t el.stateProxy = elementStateProxy;\n\t var textContent = el.getTextContent();\n\t var textGuide = el.getTextGuideLine();\n\t\n\t if (textContent) {\n\t textContent.stateProxy = elementStateProxy;\n\t }\n\t\n\t if (textGuide) {\n\t textGuide.stateProxy = elementStateProxy;\n\t }\n\t }", "function get() {\n\t return proxy;\n\t }", "function get() {\n\t return proxy;\n\t }", "function RecorderProxy() {\n this.active = null;\n}", "function proxyServer(req,res){\n\tclient.rpoplpush(\"vistedSites\",\"redirectports\",function(error,value){\n\t\tconsole.log(\" redirected to port :\" + value)\n\t\tres.redirect(\"http://localhost:\"+value+req.url);\n\t});\n\tclient.rpoplpush(\"redirectports\",\"vistedSites\")\n}", "function usingProxy() {\n return !!process.argv.filter(function (arg) {\n return arg.indexOf('--proxy') === 0;\n }).length;\n}", "proxyContract(contract) {\n this._proxiedContract = contract;\n }", "function setGateway(gw) {\r\n _defaultGateway = gw;\r\n}", "SET_SOCKET( state, id ) {\n\n state.socket = id\n\n }", "function ProxyLauncher(agent) {\n this.agent = agent;\n\n this.indexDir = undefined;\n}", "function updateProxy()\n{\n // var hostname = document.location.hostname || \"127.0.0.1\";\n var hostname = document.location.hostname || \"192.168.2.220\";\n var proxy = communicator.stringToProxy(\"hello\" +\n \":ws -h \" + hostname + \" -p 8080 -r /demows\" +\n \":wss -h \" + hostname + \" -p 9090 -r /demowss\");\n\n //\n // Set or clear the timeout.\n //\n var timeout = $(\"#timeout\").val();\n proxy = proxy.ice_invocationTimeout(timeout > 0 ? timeout : -1);\n\n //\n // Set the mode and protocol\n //\n var mode = $(\"#mode\").val();\n if(mode == \"twoway\")\n {\n proxy = proxy.ice_twoway();\n }\n else if(mode == \"twoway-secure\")\n {\n proxy = proxy.ice_twoway().ice_secure(true);\n }\n else if(mode == \"oneway\")\n {\n proxy = proxy.ice_oneway();\n }\n else if(mode == \"oneway-secure\")\n {\n proxy = proxy.ice_oneway().ice_secure(true);\n }\n else if(mode == \"oneway-batch\")\n {\n proxy = proxy.ice_batchOneway();\n }\n else if(mode == \"oneway-batch-secure\")\n {\n proxy = proxy.ice_batchOneway().ice_secure(true);\n }\n helloPrx = Demo.HelloPrx.uncheckedCast(proxy);\n\n //\n // The batch requests associated to the proxy are lost when we\n // update the proxy.\n //\n batch = 0;\n $(\"#flush\").addClass(\"disabled\").off(\"click\");\n}", "function proxy (stream, key) {\n if (key in stream) {\n debug('not proxying prop \"%s\" because it already exists on target stream', key);\n return;\n }\n\n function get () {\n return stream.res[key];\n }\n function set (v) {\n return stream.res[key] = v;\n }\n Object.defineProperty(stream, key, {\n configurable: true,\n enumerable: true,\n get: get,\n set: set\n });\n}", "function WaqrProxy() {\r\n this.wiz = new Wiz();\r\n this.repositoryBrowserController = new RepositoryBrowserControllerProxy();\r\n}", "function getProxyPage() {\n\treturn globalOptions.proxy;\n}", "constructor() {\n ProxyState.on('houses', _drawHouse)\n\n }", "function __proxyObj(origObj, proxyObj, funkList) {\n for (var v in funkList) {\n origObj[funkList[v]] = proxyObj[funkList[v]];\n }\n}", "function addAuthProxyHandler (app, sourcePath, target) {\n debug.settings(`Add auth proxy from ${sourcePath} to ${target}`)\n\n // Proxy to the target, removing the source path\n // (e.g., /my/proxy/path resolves to http://my.proxy/path)\n const sourcePathLength = sourcePath.length\n const settings = Object.assign({\n target,\n onProxyReq: addAuthHeaders,\n onProxyReqWs: addAuthHeaders,\n pathRewrite: path => path.substr(sourcePathLength)\n }, PROXY_SETTINGS)\n\n // Activate the proxy\n const proxy = createProxy(settings)\n for (let action in REQUIRED_PERMISSIONS) {\n const permissions = REQUIRED_PERMISSIONS[action]\n app[action](`${sourcePath}*`, setOriginalUrl, ...permissions.map(allow), proxy)\n }\n}", "removeProxy(proxyName) {\n var proxy = this.proxyMap[proxyName];\n if (proxy) {\n this.proxyMap[proxyName] = null;\n proxy.onRemove();\n }\n\n return proxy;\n }", "handleConnect(req, socket, head) {\n if (req.headers.host) {\n const { host } = req.headers\n const { id, hostname, port } = this.parseHost(host)\n // Node may not provide port in `host` header\n const parsedUrl = req.url && this.parseHost(req.url)\n\n // If https make socket go through https proxy on 2001\n // TODO find a way to detect https and wss without relying on port number\n if (port === '443' || (parsedUrl && parsedUrl.port === '443')) {\n log(`HTTPS Connect → Redirect to HTTP proxy - ${host}`)\n return tcpProxy.proxy(socket, daemonConf.port + 1, hostname)\n }\n\n const item = this.find(id)\n\n if (item) {\n if (port && port !== '80') {\n log(`Connect - ${host} → ${port}`)\n tcpProxy.proxy(socket, port)\n } else if (item.start) {\n const { PORT } = item.env\n log(`Connect - ${host} → ${PORT}`)\n tcpProxy.proxy(socket, PORT)\n } else {\n const { hostname, port } = url.parse(item.target)\n const targetPort = port || 80\n log(`Connect - ${host} → ${hostname}:${port}`)\n tcpProxy.proxy(socket, targetPort, hostname)\n }\n } else {\n log(`Connect - Can't find server for ${id}`)\n socket.end()\n }\n } else {\n log('Connect - No host header found')\n }\n }" ]
[ "0.6090196", "0.5978869", "0.58043545", "0.54435056", "0.5435811", "0.5435811", "0.5368981", "0.5316783", "0.52316004", "0.52316004", "0.52275294", "0.52275294", "0.52275294", "0.52275294", "0.52275294", "0.52275294", "0.52275294", "0.52275294", "0.5208669", "0.5197916", "0.5197916", "0.514769", "0.51326114", "0.5128352", "0.5127002", "0.5127002", "0.5086342", "0.5061323", "0.5054444", "0.50056666", "0.49951276", "0.49600857", "0.4954904", "0.48981264", "0.48955858", "0.48932174", "0.48837036", "0.48453695", "0.48453695", "0.48414308", "0.48267037", "0.48267037", "0.47757217", "0.4762931", "0.4762931", "0.4762931", "0.4762931", "0.4762931", "0.4762931", "0.4762931", "0.4762931", "0.47575313", "0.47524998", "0.47524998", "0.47524998", "0.47524998", "0.47524998", "0.47524998", "0.47524998", "0.47524998", "0.4746959", "0.47416002", "0.47407702", "0.47369608", "0.47085428", "0.46973884", "0.46953487", "0.46936065", "0.46869472", "0.46811968", "0.46769044", "0.46488905", "0.46387616", "0.46365452", "0.46290705", "0.46277595", "0.4626262", "0.46226946", "0.46217555", "0.46207055", "0.46034926", "0.45967588", "0.4594102", "0.4594102", "0.45870236", "0.4586026", "0.45786136", "0.45646605", "0.45631546", "0.4554598", "0.4548898", "0.4530006", "0.45291582", "0.45286152", "0.45147088", "0.45135525", "0.44981182", "0.44978923", "0.44949532", "0.44909605" ]
0.4766005
43
Extend tty.Server to override middleware setup
function MyServer() { this.canonical = options.canonical; return TTYServer.apply(this, arguments); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function MiddleMan() {\n this._server = http.createServer(this._onRequest.bind(this));\n this._proxyServer = httpProxy.createProxyServer({});\n this._handlers = [];\n}", "__prepareServer () {\n\n\t\tthis.server.inject(`sharedLogger`, sharedLogger);\n\n\t\tthis.server.mount(`/health-check`, (req, res) => res.respond({ healthy: true, version: this.appVersion }));\n\t\tthis.server.mount(`/webview`, this.workflowManager.handleWebviewRequests.bind(this.workflowManager));\n\t\tthis.server.mount(`/track-link`, this.workflowManager.handleLinkTrackingRequests.bind(this.workflowManager));\n\t\tthis.server.mount(`/api/flow/reload-dynamic`, this.workflowManager.reloadDynamicFlows.bind(this.workflowManager));\n\n\t}", "startServer() {\n let requestHandler = this.onRequest.bind(this);\n let port = this.port;\n http.createServer(requestHandler).listen(port);\n console.log(\"Server running at http://localhost:%d\", port);\n }", "useMiddlewareStack () {\n if (!this.server) throw new Error('Create server first')\n this._setStack()\n const middlewares = this.stack.getMiddlewareFunctions(this.config, this)\n this.server.on('request', this._getRequestHandler(middlewares))\n }", "initExpressMiddleWare() {\n\t\tthis.app.use(bodyParser.urlencoded({ extended: true }));\n\t\tthis.app.use(bodyParser.json());\n\t}", "applyMiddlewares() {\n super.applyMiddlewares();\n this.log.debug('This is only a custom messagem from your custom server :)');\n }", "requestHandler(req, res) {\n // All requests are assumed to be \"Express-like\" and have the bodyParser run\n // before it. Express doesn't have a good way (that I'm aware of) to specify\n // \"run this middleware if it hasn't already been run\".\n this.emit('message', req.body)\n this.handler(req.body, this.responseHandler.bind(this, res))\n }", "setupAppMiddleware() {\n\t\t// small security protections by adjusting request headers\n\t\tthis.app.use(helmet());\n\n\t\t// adding the request's client ip\n\t\tthis.app.use(requestIp.mw());\n\n\t\tif(Config.isDev) {\n\t\t\t// Log requests in the console in dev mode\n\t\t\tthis.app.use(morgan('dev'));\n\t\t}\n\t\telse {\n\t\t\t// Compress responses in prod mode\n\t\t\tthis.app.use(compression());\n\t\t}\n\n\t\t// decode json-body requests\n\t\tthis.app.use(bodyParser.json());\n\n\t\t// TODO: Move mongo sanitation to save actions\n\t\t// sanitizing request data for mongo-injection attacks\n\t\tthis.app.use(mongoSanitize());\n\n\t\t// any internal data that is needed to be attached to the request must be attached to the \"internalAppVars\" object\n\t\tthis.app.use((req, res, next) => {\n\t\t\treq.internalAppVars = {};\n\t\t\tnext();\n\t\t});\n\t}", "middlewares() {\n this.server.disable('x-powered-by');\n this.server.use(cors());\n this.server.use(express.json());\n }", "serve() {\n return function (req, res, next) {\n next();\n };\n }", "constructor() {\n /* server code from https://cs.nyu.edu/courses/fall18/CSCI-UA.0480-003/_site/homework/03.html */\n this.server = net.createServer(sock => this.handleConnection(sock));\n this.routes = {};\n this.middleware = null;\n }", "bindHttpServer() {\n this.app.singleton('server', _Server.default);\n }", "socketMiddleware(server) {\n this.plugins.filter((plugin) => {\n return \"function\" === typeof plugin.socketMiddleware;\n }).forEach((plugin) => {\n plugin.socketMiddleware(server);\n });\n }", "start()\n {\n this.app.use(\n this.bp.json(\n {\n limit: '50mb'\n }\n )\n );\n\n this.app.use(\n this.bp.urlencoded(\n {\n limit: '50mb',\n extended: true\n }\n )\n );\n\n this.server.listen(Config.WebServer.Port, () =>\n {\n Logger.info(`Server started on port: ${this.server.address().port}`);\n }\n );\n\n this.app.all('*', (req, res) =>\n {\n res.header('Access-Control-Allow-Origin', '*');\n res.header('Access-Control-Allow-Headers', 'Content-type');\n this.handleReq(req, res);\n }\n );\n }", "middlewares() {\n this.server.use(cors());\n this.server.use(express.json());\n }", "constructor() {\n // Initializes the internal state\n this.logger = loggerManager.getLogger('Server');\n this.platformCredentials = {\n key: '',\n certificate: ''\n };\n\n this.app = express();\n this.app.set('x-powered-by', false);\n this.app.enable('trust proxy');\n this.app.use(bodyParser.json());\n\n this.routedServices = [];\n this.app.all('*', this._getCheckRoutedServicesFunction(this.routedServices));\n\n this.httpsServer = null;\n }", "start(){\n this.applyMiddleWare();\n this.init();\n this.instance.listen(process.env.SERVER_PORT,()=>{\n console.log(`Server started on port ${process.env.SERVER_HOST}.`);\n console.log(`Navigate to http://${process.env.SERVER_HOST}:${process.env.SERVER_PORT}`);\n });\n }", "constructor() {\n this.app = express();\n\n this.app.use(interceptor((req, res) => ({\n isInterceptable() {\n // About this temporary \"used\" hack... One requirement I am really\n // wanting to fulfill is allowing the consoleApp be configured to '/'\n // while distApp is '/out', as well as allowing the reverse\n // configuration where consoleApp can be configured to '/console-app'\n // while distApp is '/'. If anyone has any ideas of how to allow both\n // of these configurations without a hack like this please file issue.\n console.log('USED LENGTH ', used.length, used, req.originalUrl, res.get('Content-Type'));\n for (let i = 0; i < used.length; i++) {\n if (used[i] === '/') {\n if (req.originalUrl === '/') {\n console.log('used is / and origUrl is /');\n return false;\n }\n } else if (req.originalUrl.startsWith(used[i])) {\n console.log('starts with used');\n return false;\n }\n }\n if (/text\\/html/.test(res.get('Content-Type'))) {\n console.log('IS HTML');\n } else {\n console.log('IS NOT HTML');\n }\n return /text\\/html/.test(res.get('Content-Type'));\n },\n intercept(body, send) {\n const $document = cheerio.load(body);\n $document('body').append(`\n <script src=\"/socket.io/socket.io.js\"></script>\n <script>\n var socket = io();\n socket.on('reload-clients', function () {\n window.location.reload(true)\n });\n </script>\n `);\n send($document.html());\n }\n })));\n }", "middleware() {\n this.express.use(logger('dev'));\n this.express.use(bodyParser.json());\n this.express.use(bodyParser.urlencoded({ extended: false }));\n }", "function server(req, res) {\r\n var self = this;\r\n req.startTime = Date.now();\r\n req.query = qs.parse(url.parse(req.url).query);\r\n // Hack to make it work with weird paths and encoding types, especial\r\n // File names with spaces like \"Hi world.pdf\" or \"niña.pdf\"\r\n // Hat tip to @mathias\r\n req.url = decodeURIComponent(url.parse(req.url).pathname);\r\n //\r\n // Emit the method to the parent if I can't handle it yep before of anything else.\r\n // So you can do:\r\n // var myapp = require('nhouston')(options);\r\n // myapp.on('POST', function(req,res){ /* my codez */});\r\n //\r\n res.error = function(code, msg) {\r\n res.statusCode = code || 500;\r\n res.setHeader('Content-type', 'text/html');\r\n return res.end(\r\n '<div style=\"text-align:center\"><h1> ' + code + ' - ' + msg + ' </h1><hr>' +\r\n '<p> node-' + process.version + ' running on ' + cfg.port + '</p></div>'\r\n );\r\n };\r\n\r\n res.setHeader('Server', 'node/' + process.version.replace('v', '') + ' (' + os + ')');\r\n res.setHeader('X-Powered-By', pkg.name + '/' + pkg.version);\r\n\r\n if (self.listeners(req.url).length) {\r\n return self.emit(req.url, req, res)\r\n }\r\n if (req.method != 'GET' && self.listeners(req.method).length) {\r\n return self.emit(req.method, req, res);\r\n } else if (req.method != 'GET') {\r\n return res.error(501, 'Not Implemented');\r\n }\r\n\r\n var absolute = path.join(cfg.path, req.url),\r\n isPublic = req.url.substr(0, 8) == '/public/',\r\n rabpub = '';\r\n\r\n req.isPublic = isPublic;\r\n\r\n req.once('error', function() {\r\n res.error(500, 'Internal Server Error');\r\n });\r\n\r\n var ext = path.extname(req.url).replace('.', '');\r\n\r\n if (req.url == '/favicon.ico')\r\n return pipeStream(__dirname + '/../public/img.png', req, res);\r\n if (isPublic) rabpub = path.join(__dirname, '..', req.url);\r\n\r\n if (req.url === '/') {\r\n readContents(cfg.path, req, res);\r\n } else if (req.url !== '/favicon.ico' && !isPublic) {\r\n\r\n if (existsSync(absolute)) {\r\n var stats = fs.statSync(absolute);\r\n if (res.statusCode == 304) return res.end();\r\n if (stats.isDirectory()) {\r\n readContents(absolute, req, res);\r\n } else {\r\n pipeStream(absolute, req, res);\r\n }\r\n csl.log(req.method + req.url, (Date.now() - req.startTime) + 'ms');\r\n } else {\r\n var raw = req.query.raw === false || req.query.raw == 'false';\r\n if (!req.query.raw) raw = true;\r\n // Custom actions for your files\r\n if (actions[ext] && raw) {\r\n if (typeof actions[ext] == 'function') {\r\n return actions[ext].call(actions, req, res);\r\n }\r\n }\r\n else\r\n res.error(404, 'Not found');\r\n }\r\n } else if (isPublic && existsSync(rabpub) && !fs.statSync(rabpub).isDirectory()) {\r\n\r\n pipeStream(rabpub, req, res);\r\n\r\n } else if (isPublic && existsSync(req.url)) {\r\n\r\n if (path.extname(req.url) === '') {\r\n res.writeHeader(200, {\r\n 'Content-type': 'text/html'\r\n });\r\n return res.end(readDir(rabpub));\r\n }\r\n } else if (isPublic) {\r\n pipeStream(__dirname + '/../public/default.png', req, res);\r\n } else {\r\n var raw = req.query.raw === false || req.query.raw == 'false';\r\n if (!req.query.raw) raw = true;\r\n // Custom actions for your files\r\n if (actions[ext] && raw) {\r\n if (typeof actions[ext] == 'function') {\r\n return actions[ext].call(actions, req, res);\r\n }\r\n } else \r\n return res.error(404, 'Not found');\r\n }\r\n}", "function Server() {}", "constructor(log) {\n // create server\n this.server = restify.createServer({\n name: 'src',\n log: log,\n formatters: {\n 'application/json': function (req, res, body, cb) {\n res.setHeader('Cache-Control', 'must-revalidate');\n\n // Does the client *explicitly* accepts application/json?\n var sendPlainText = false;\n if (req.header('Accept')) {\n sendPlainText = (req.header('Accept').split(/, */).indexOf('application/json') === -1);\n }\n\n // Send as plain text\n if (sendPlainText) {\n res.setHeader('Content-Type', 'text/plain; charset=utf-8');\n }\n\n // Send as JSON\n if (!sendPlainText) {\n res.setHeader('Content-Type', 'application/json; charset=utf-8');\n }\n return cb(null, JSON.stringify(body));\n }\n }\n });\n\n // setup defaults middlewares\n this.server\n .pre(restify.pre.sanitizePath())\n .use(restify.fullResponse())\n .use(restify.bodyParser())\n .use(restify.queryParser())\n .use(restify.gzipResponse())\n .use(restify.CORS());\n\n // setup server event handlers\n this.server\n .on('uncaughtException', function (req, res, route, err) {\n console.log('******* Begin Error *******');\n console.log(route);\n console.log('*******');\n console.log(err.stack);\n console.log('******* End Error *******');\n if (!res.headersSent) {\n return res.send(500, {error: err.message});\n }\n res.write(\"\\n\");\n res.end();\n })\n .on('after', restify.auditLogger({log: log}));\n }", "function Server() {\n this.app = express_1[\"default\"]();\n this.config();\n }", "initializeServer() {\n this.createRoutes();\n\n // Create an Express app\n this.app = express();\n\n // Create a server\n this.server = http.createServer(this.app);\n\n // Health endpoint\n this.app.get('/health', (req, res) => { res.json({ status: 'healthy' }) });\n\n //setup basic authentication\n this.app.use(auth);\n\n // Initialize the runtime with a server and settings\n RED.init(this.server, this.redSettings);\n console.log('%s is the userDir for RED', this.redSettings.userDir);\n\n // Serve the editor UI from /red\n this.app.use(this.redSettings.httpAdminRoot,RED.httpAdmin);\n\n // Serve the http nodes UI from /api\n this.app.use(this.redSettings.httpNodeRoot,RED.httpNode);\n\n // Add a simple route for static content served from 'public'\n //self.app.use(\"/\",express.static(\"public\"));\n\n // Add handlers for the app (from the routes).\n for (let r in this.routes) {\n this.app.get(r, this.routes[r]);\n }\n }", "constructor() {\n\t super();\n\n\t this.proxy = false;\n\t this.middleware = [];\n\t this.subdomainOffset = 2;\n\t this.env = process.env.NODE_ENV || 'development';\n\t this.context = Object.create(context);\n\t this.request = Object.create(request);\n\t this.response = Object.create(response);\n\t }", "constructor() {\n super();\n\n this.proxy = false;\n this.middleware = [];// 中间件容器\n this.subdomainOffset = 2;\n this.env = process.env.NODE_ENV || 'development';\n this.context = Object.create(context);\n this.request = Object.create(request);\n this.response = Object.create(response);\n if (util.inspect.custom) {\n this[util.inspect.custom] = this.inspect;\n }\n }", "bindHttpServer() {\n\t\tthis.app.singleton('server', HttpServer);\n\t}", "function setupServerMiddleware (app) {\n\n\t// General middleware.\n\tapp.use(compression({ threshold: 0 }));\n\tapp.use(cookieParser(config.authentication.cookie.secret));\n\tapp.use(bodyParser.urlencoded({ // This will let us get the data from a POST.\n\t\textended: true,\n\t}));\n\tapp.use(bodyParser.json());\n\n\t// Static files (must come before logging to avoid logging out every request for a static file e.g. favicon).\n\tconst staticDirectory = path.resolve(__dirname, `..`, `..`, `frontend`, `build`, `static`);\n\tapp.use(`/public`, express.static(staticDirectory, { maxAge: config.caching.maxAge, index: false }));\n\n\t// Temporary favicon.\n\tapp.use(`/favicon.ico`, (req, res) => res.status(404).end(`NOT_ADDED_YET`));\n\n\t// Health check endpoint.\n\tapp.use(`/health-check`, middleware.healthCheck);\n\n\t// Redirect to HTTPS.\n\tapp.use(middleware.enforceHttps);\n\n\t// Authentication.\n\tapp.use(basicAuth({\n\t\tusers: config.authentication.basicAuth.users,\n\t\tchallenge: true,\n\t\trealm: packageJson.name,\n\t\tunauthorizedResponse: req => JSON.stringify({\n\t\t\tsuccess: false,\n\t\t\terror: (req.auth ? `Invalid credentials.` : `No credentials provided.`),\n\t\t}),\n\t}));\n\n}", "function createServer () {\n\n // Create server\n\n var server = express.createServer();\n\n // Configure Server\n\n server.configure(function () {\n\n // Built-in\n\n server.use(express.methodOverride()); // Allow method override using _method form parameter\n server.use(express.bodyDecoder()); \t // Parse application/x-www-form-urlencoded\n server.use(express.staticProvider(__dirname + '/files')); // Serve client documents in local directory\n\n // Local\n\n server.use(setResponseHeader()); // Set default response headers for CORS\n server.use(logConsole()); // Display incoming requests\n\n // Authentication\n\n server.use(auth([auth.Mac({ realm: \"Example\", // Set realm, typically a domain name or application name\n getTokenAttributes: getToken, // Function used to fetch the access token record, typically from a database\n // hostHeader: 'x-forwarded-host', // Needed when running behind a proxy such as Apache2\n // isHTTPS: true, // Uncomment for HTTPS\n checkNonce: nonceCheck, // Optional nonce checking function\n bodyHashMode: \"require\" })])); // Require body hash validation for all non GET/HEAD/OPTIONS requests\n });\n\n // Setup generic OPTIONS route\n\n server.options(/.+/, function (req, res) {\n\n res.send(' ');\n });\n\n return server;\n}", "setupApp() {\n this.app = express();\n if (this.config.bodyParserOptions.json) {\n this.app.use(bodyParser.json(this.config.bodyParserOptions.json));\n }\n if (this.config.bodyParserOptions.raw) {\n this.app.use(bodyParser.raw(this.config.bodyParserOptions.raw));\n }\n if (this.config.bodyParserOptions.text) {\n this.app.use(bodyParser.text(this.config.bodyParserOptions.text));\n }\n if (this.config.bodyParserOptions.urlencoded) {\n this.app.use(bodyParser.urlencoded(this.config.bodyParserOptions.urlencoded));\n }\n this.app.use(cookieParser(this.config.cookieParserOptions));\n this.app.use(morgan(this.config.morganOptions));\n this.app.use(compression(this.config.compressionOptions));\n }", "function middleware(request, response, next) {}", "middlewares () {\n this.express.use(express.urlencoded({ extended: false }))\n this.express.use(flash())\n this.express.use(\n session({\n store: new LokiStore({\n path: path.resolve(__dirname, '..', 'tmp', 'sessions.db')\n }),\n secret: 'MyAppSecret',\n resave: false,\n saveUninitialized: true\n })\n )\n }", "function addMiddleware(server) {\n if (process.env.NODE_ENV === 'production') {\n // server.use(morgan('combined'))\n server.use((0, _compression2.default)());\n server.use(_express2.default.static(_Constants.PUBLIC_DIR, { maxAge: 31536000000 }));\n }\n // } else {\n // server.use(morgan('dev'))\n // }\n\n server.use(_express2.default.static(_path2.default.join(_Constants.APP_PATH, 'static')));\n server.use(_bodyParser2.default.json());\n server.use((0, _hpp2.default)());\n server.use(_helmet2.default.contentSecurityPolicy({\n defaultSrc: [\"'self'\"],\n scriptSrc: [\"'self'\"],\n styleSrc: [\"'self'\"],\n imgSrc: [\"'self'\"],\n connectSrc: [\"'self'\", 'ws:'],\n fontSrc: [\"'self'\"],\n objectSrc: [\"'none'\"],\n mediaSrc: [\"'none'\"],\n frameSrc: [\"'none'\"]\n }));\n server.use(_helmet2.default.xssFilter());\n server.use(_helmet2.default.frameguard('deny'));\n server.use(_helmet2.default.ieNoOpen());\n server.use(_helmet2.default.noSniff());\n}", "run() {\n const app = express();\n\n app.use(bodyParser.json());\n app.use(bodyParser.urlencoded({\n extended: true\n }));\n\n // Handle favicon request\n app.get('/favicon.ico', function (req, res) {\n HttpHelpers.write('', 'image/x-icon', res);\n });\n\n // Handle API proxy calls\n\n app.all('/api*', this.handleApiRequest.bind(this));\n\n app.all('*', this.handle.bind(this));\n\n app.listen(this.getPort());\n\n console.log(`Server process ${process.pid} started on port ${this.getPort()}`);\n }", "middleware() {\n this.server.use(express.json());\n this.server.use(\n '/file',\n express.static(path.resolve(__dirname, '../', 'tmp', 'uploads'))\n );\n }", "function unifiedServer(req, res) {\n const parsedUrl = new URL(req.url, `http://${req.headers.host}`);\n\n const path = parsedUrl.pathname;\n const trimmedPath = path.replace(/^\\/+|\\/$/g, '');\n\n const method = req.method;\n const requestQuery = parsedUrl.searchParams;\n\n const headers = req.headers;\n\n // decoder for decoding buffers\n const decoder = new StringDecoder('utf8');\n let buffer = '';\n\n // called only for requests with body to handle incomming chunks from the stream\n req.on('data', (chunk) => {\n buffer += decoder.write(chunk); // decode each chunk and append to the earlier received chunks\n });\n\n // called for all requests regardless if they contain a body\n req.on('end', () => {\n buffer += decoder.end();\n\n // check if request path is among the available routes\n const selectedCallback = handlers[trimmedPath] || handlers.notFound\n\n // construct data to be sent to all handlers\n const data = {\n 'path': trimmedPath,\n 'method': method,\n 'query': requestQuery,\n headers,\n 'payload': buffer\n }\n\n selectedCallback(data, function(statusCode = 200, payload = {}) {\n const responseData = JSON.stringify(payload);\n\n res.setHeader('Content-Type', 'application/json')\n res.writeHead(statusCode);\n res.end(responseData);\n })\n })\n}", "_compile() {\n this._middlewares = this._handler.server.concat(this._handler.global)\n }", "use (middleware) {\n this.app.use(middleware)\n }", "async start() {\n await this.resolvePort();\n\n const Koa = (this.Koa = require('koa'));\n const bodyParser = require('koa-bodyparser');\n const Http = require('http');\n const koaApp = (this.koaApp = new Koa());\n\n this.httpServer = Http.createServer(koaApp.callback());\n\n let { publicPath, publicPaths } = this.config;\n\n await rapid._hookEmit('middlewareWillAttach');\n if (publicPath) addPublicDir(publicPath);\n if (publicPaths) publicPaths.forEach(addPublicDir);\n\n koaApp.use(errorHandlerMiddleware);\n koaApp.use(addUtilityFunctionsMiddleware);\n koaApp.use(loggerMiddleware);\n koaApp.use(bodyParser());\n\n if (this.config.cors) {\n koaApp.use(koaCors());\n }\n await rapid._hookEmit('middlewareDidAttach');\n\n function addPublicDir(publicPath) {\n const serveStatic = require('koa-static');\n const fullPublicPath = rapid.localPath(publicPath);\n koaApp.use(serveStatic(fullPublicPath));\n }\n }", "applyMiddleware() {\n //Allows the server to parse json\n this.expressApp.use(bodyParser.json())\n\n //Registers the routes used by the app\n new Routes(this.expressApp)\n }", "initExpress() {\n\t\tthis.app.set(\"port\", 8000);\n\t}", "function Application() {\n var me = this;\n\n me.verbs = {};\n me.errorHandlers = {\n 403: function(req, res) {\n res.writeHead(403, {\n 'Content-type' : 'text/html'\n });\n res.end(html('Access denied', 'Access Denied'));\n },\n 404 : function(req, res) {\n res.writeHead(404, {\n 'Content-type' : 'text/html'\n });\n res.end(html('Not Found', 'Not found'));\n }\n\n };\n me.listeners = {};\n me.server = http.createServer(function(req, res) {\n var verb,\n verbs = me.verbs,\n errorHandlers = me.errorHandlers,\n config,\n status;\n\n try {\n req.args = req.uri.substr(1).split('/');\n verb = req.verb = req.args.shift();\n if (req.uri.endsWith('/')) {\n req.args.pop();\n }\n if (!verb.length) {\n req.verb = '/';\n }\n\n me.fire('beginRequest', req, res);\n // in case beginRequest handler changed it!\n verb = req.verb;\n config = verbs[verb] || verbs[404] || 404;\n if (config !== 404) {\n status = config.handler(config, req, res);\n }\n else {\n status = 404;\n }\n config = errorHandlers[status];\n if (config) {\n if (config.handler) {\n config.handler(config, req, res);\n }\n else {\n errorHandlers[status](req, res);\n }\n }\n }\n catch (e) {\n if (e === 'RES.STOP') {\n throw e;\n }\n else if (e === 'EOF') {\n throw e;\n }\n me.fire('exception', e, req, res);\n res.error = e;\n config = errorHandlers[500];\n if (config) {\n if (config.handler) {\n config.handler(config, req, res, internalServerError);\n }\n else {\n config(req, res, internalServerError);\n }\n }\n else {\n internalServerError(req, res);\n }\n }\n me.fire('endRequest', req, res);\n });\n}", "serve() {\n\t // a no-op, these are absolute URLs\n\t return function (req, res, next) {\n\t next();\n\t };\n\t}", "function RCConfigExecServer() {\n var p = RCConfigExecServer.prototype;\n p = this;\n var self = this;\n self.data = {}\n\n var indexPageSecurityEnding = '567.html'\n\n\n self.data.dirDlManifests = sh.fs.makePath(__dirname, 'manifests')\n self.data.dirFileList = sh.fs.join(__dirname, 'data', 'fileList')\n\n p.loadConfig = function loadConfig(config) {\n self.settings = config;\n config.port = sh.dv(config.port, 6018);\n self.proc('go to ', 'http://localhost:' + config.port);\n self.proc('go to ', 'http://' + sh.getIpAddress() + ':' + config.port + '/' + 'index.html' + indexPageSecurityEnding);\n\n config.port2 = config.port;\n config.port += 2; //express can use any available port, we will forward to it \n self.runServer();\n self.startSocket();\n self.data.id = exports.RCExtV\n console.error('RCConfigExecServer', exports.RCExtV)\n // asdf3g.f\n\n // asd.g\n self.runTests();\n }\n\n self.runServer = function runServer() {\n var express = require('express')\n var app = express()\n self.app = app;\n\n app.use(sh.blockIndexPage(indexPageSecurityEnding, __dirname));\n\n app.use(function addCrossDomainMiddlware(req, res, next) {\n //asdf.g\n res.header(\"Access-Control-Allow-Origin\", \"*\");\n if (req.headers.origin != null) {\n res.header(\"Access-Control-Allow-Origin\", req.headers.origin);\n }\n ;\n res.header(\"Access-Control-Allow-Headers\", \"X-Requested-With\");\n res.header(\"Access-Control-Allow-Headers\", \"Content-Type\");\n res.header(\"Access-Control-Allow-Credentials\", \"true\");\n res.header(\"Access-Control-Allow-Methods\", \"PUT, GET, POST, DELETE, OPTIONS\");\n next();\n });\n\n var bodyParser = require(\"body-parser\");\n //var multer = require('multer');\n\n app.use(bodyParser.json({limit: '50mb'}));\n\n app.use(bodyParser.urlencoded({\n limit: '50mb',\n extended: true\n }));\n\n app.use(bodyParser.json({type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json\n\n app.use(express.static(__dirname + '/' + 'public_html'));\n //uiutils in local\n var dirUIUtils = sh.require(\n /*sh.fs.join('mp', 'testingFramework'),*/\n 'mp/testingFramework/',\n true)\n //console.log('ok, ', dirUIUtils)\n //sh.x()\n sh.fs.exists(dirUIUtils, 'wh not here')\n app.use('/js/lib', express.static(dirUIUtils));\n app.get('/js/lib/ui_utils.js', function onReadFile(req, res) {\n var content = sh.readFile(dirUIUtils + 'shelpers-mini.js')\n res.send(content);\n });\n app.get('/js/lib/shelpers-mini.js', function onReadFile(req, res) {\n var content = sh.readFile(dirUIUtils + 'ui_utils.js')\n res.send(content);\n });\n\n app.get('/C:/Users/user1/Dropbox/projects/crypto/mp/testingFramework/ui_utils.js', function onReadFile(req, res) {\n var content = sh.readFile('C:/Users/user1/Dropbox/projects/crypto/mp/testingFramework/ui_utils.js')\n res.send(content);\n });\n\n\n /*return;\n var dirSaves = __dirname+'/'+'saves/';\n sh.mkdirp(dirSaves);\n sh.writeFile(dirSaves + 'test.html', 'Test content <br /> ok ok ok ?');\n */\n app.get('/readFile', function onReadFile(req, res) {\n var name = req.query.name;\n var content = sh.readFile(dirSaves + name + '.html')\n res.send(content);\n\n });\n\n app.post('/saveFile', function onSaveFile(req, res) {\n var body = req.body;\n var name = body.name;\n var contents = body.body;\n //var name = req.params.name;\n console.log(req.body)\n sh.writeFile(dirSaves + name + '.html', contents)\n\n res.send('Hello World!');\n });\n\n\n app.get('/goToFile', function onReadFile(req, res) {\n var name = req.query.file;\n name = name.replace('/media/sf_Dropbox', 'G:/Dropbox/')\n console.log(name)\n var opened = false;\n if (sh.fs.exists(name)) {\n if (sh.fs.isDir(name)) {\n sh.run('start \"\" ' + sh.qq(name))\n opened = true\n } else {\n var dir = sh.fs.goUpOneDir(name)\n sh.run('start \"\" ' + sh.qq(name))\n opened = true\n }\n }\n\n if (opened == false) {\n res.status(404)\n res.send('no found ' + name)\n return;\n }\n\n res.send('ok');\n\n });\n\n sh.defineExitware(self.app)\n\n var JSONFileHelper = require('shelpers').JSONFileHelper;\n\n function defineResumeMethods() {\n\n //var j = new JSONFileHelper();\n\n var j = new JSONFileHelper();\n var config = {};\n config.file = __dirname + '/' + 'recent_files.json';\n j.init(config);\n self.data.j = j;\n\n app.post('/saveFile', function onSaveFile(req, res) {\n var body = req.body;\n var name = body.name;\n var contents = body.body;\n //var name = req.params.name;\n console.log(req.body);\n var fileJSON = dirSaves + name + '.html';\n sh.writeFile(fileJSON, contents);\n\n\n var bookJSON = {\n file: fileJSON,\n name: name\n }\n self.data.j.addRecent(bookJSON, true, 'file');\n\n res.send('Hello World!');\n });\n\n app.get('/removeFile', function onRemoveFile(req, res) {\n var body = req.query;\n var name = body.name;\n var fileJSON = dirSaves + name + '.html';\n self.proc('removing', name)\n\n var bookJSON = {\n file: fileJSON,\n name: name\n }\n self.data.j.removeRecent(bookJSON, 'file');\n\n res.send('removed');\n });\n\n app.get('/listFiles', function onSaveFile(req, res) {\n\n var files = [];//self.utils.getfilesInDir();\n\n files = self.data.j.readFile();\n res.json(files)\n\n return;\n var body = req.body;\n var name = body.name;\n var contents = body.body;\n //var name = req.params.name;\n console.log(req.body)\n sh.writeFile(dirSaves + name + '.html', contents)\n\n res.send('Hello World!');\n });\n\n }\n\n defineResumeMethods();\n\n\n function defineResumeMethods2() {\n //var j = new JSONFileHelper();\n\n var j = new JSONFileHelper();\n var config = {};\n config.file = __dirname + '/' + 'recent_tasks.json';\n config.propUpsert = 'name';\n\n\n j.init(config);\n self.data.j2 = j;\n\n app.post('/saveTask', function onSaveFile(req, res) {\n var body = req.body;\n var name = body.name;\n var contents = body.body;\n //var name = req.params.name;\n console.log('why?', name, body);\n\n var fileJSON = sh.fs.join(__dirname, 'tasks', name + '.json')\n sh.fs.mkdirp(fileJSON, true)\n sh.writeJSONFile(fileJSON, contents)\n\n //var fileJSON = dirSaves+name+'.html';\n //sh.writeFile(fileJSON, contents);\n var bookJSON = {\n contents: contents,\n name: name\n }\n self.data.j2.addRecent(bookJSON, true, 'name');\n res.send('Hello World!');\n });\n\n app.get('/getTask', function getTask(req, res) {\n var body = req.query;\n var name = body.name;\n\n if (name.endsWith('.json') == false) {\n name += '.json'\n }\n var fileJSON = sh.fs.join(__dirname, 'tasks', name)\n self.proc('getTask', name, fileJSON);\n res.sendfile(fileJSON);\n //res.send('removed');\n });\n\n app.get('/removeTask', function onRemoveFile(req, res) {\n var body = req.query;\n var name = body.name;\n self.proc('removingTasls', name)\n if (name.endsWith('.json') == false) {\n name += '.json'\n }\n\n var fileJSON = sh.fs.join(__dirname, 'tasks', name)\n\n var bookJSON = {\n name: name\n }\n removedresult = self.data.j2.removeRecent(bookJSON, 'name');\n if (removedresult) {\n sh.fs.delete(fileJSON, true)\n }\n res.send('removed');\n });\n\n app.get('/listTasks', function onSaveFile(req, res) {\n var files = [];//self.utils.getfilesInDir();\n files = self.data.j2.readFile();\n res.json(files)\n return;\n });\n\n var dirSaveNewTaskPath = sh.fs.join(__dirname, 'data', 'uploadTasks') //(app,)\n sh.uploadFileHelper({\n app: app,\n uploadPath: '/uploadTask',\n dirStore: dirSaveNewTaskPath,\n fxDone: function onUploadedFile(file, bbb) {\n self.proc('file', file, bbb);\n self.newTask(file)\n }\n })\n\n\n p.newTask = function newTask(file) {\n var fileDlManifest = file;\n var leaf = sh.fs.leaf(file)\n leaf = leaf.replace('.json', '')\n\n var dirUploadedLists = sh.fs.join(__dirname, 'data', 'uploadedLists')\n sh.fs.mkdirp(dirUploadedLists)\n var fileUploadedManifest = sh.fs.join(dirUploadedLists, sh.fs.leaf(file))\n var fileTask = sh.fs.join(__dirname, 'tasks', leaf)\n //asdf.g\n sh.fs.cp2(file, fileUploadedManifest);\n\n var json = {\n \"name\": leaf,\n //\"fileFileList\": \"G:\\\\Dropbox\\\\projects\\\\crypto\\\\mp\\\\RCExt\\\\data\\\\filelists\\\\http___localhost_6024_.txt\",\n \"listDlManifest\": fileUploadedManifest,\n //\"G:\\\\Dropbox\\\\projects\\\\crypto\\\\ritv/imdb_movie_scraper/IMDB_App_Output/dlListsWrapC/List ls Ids_ls05139_11.json\",\n \"props\": {\n \"upload from a file\": new Date(),\n }\n }\n\n //store json\n sh.writeJSONFile(fileTask, json)\n\n\n self.utils.storeConfig(leaf, fileTask);\n //update recent\n }\n\n\n self.addTest(function onTestSavingFile() {\n //G:\\Dropbox\\projects\\crypto\\mp\\RCExt\\data\\uploadTasks\\test_dl_manifest.json\n var fileTestUpload = sh.fs.join(__dirname, 'testData', 'test_dl_manifest.json')\n var orig = self.data.j2.settings.addToTop;\n self.data.j2.settings.addToTop = false;\n self.newTask(fileTestUpload);\n self.data.j2.settings.addToTop = orig;\n })\n\n }\n\n defineResumeMethods2();\n\n\n var file = 'mp/SpeakerJava2/SpeakServer/public_html/powershell/goto/OpenFileInWebstorm.js'\n var file2 = sh.require(file, true)\n if (sh.fs.exists(file2)) {\n //asdf.g\n var OpenFileInWebstorm = sh.require(file)\n .OpenFileInWebstorm\n self.data.openFile = new OpenFileInWebstorm();\n }\n\n\n app.get('/openFile', function openFile(req, res) {\n var body = req.query;\n var file = body.file;\n //var fileJSON = dirSaves+name+'.html';\n self.proc('...', file)\n if (file == null || file == 'undefined') {\n res.send('abort')\n return;\n }\n var cfg = {}\n cfg.file = file;\n self.proc('file', file)\n self.data.openFile.init(cfg);\n\n res.send('opened ....');\n });\n\n\n app.get('/nudgetSocket', function nudgetSocket(req, res) {\n var body = req.query;\n var file = body.file;\n //var fileJSON = dirSaves+name+'.html';\n self.proc('... nudget socket', file)\n\n self.socket\n\n res.send('nudged ....');\n });\n\n function defineVerifyStep() {\n //move to other server\n app.get('/getFiles', function onGetFiles(req, res) {\n //start here and move to socket in other server\n\n\n var dirs = []\n\n\n var dir3 =\n\n sh.async(dirs, function onEachDir(dir, fx) {\n\n }, function onEachDirsDione() {\n res.send('onGetFiles');\n })\n\n return\n });\n\n app.get('/listFiles', function onSaveFile(req, res) {\n var files = [];\n\n files = self.data.j.readFile();\n res.json(files)\n\n return;\n var body = req.body;\n var name = body.name;\n var contents = body.body;\n //var name = req.params.name;\n console.log(req.body)\n sh.writeFile(dirSaves + name + '.html', contents)\n\n res.send('Hello World!');\n });\n\n\n app.get('/resetSockets', function resetSockets(req, res) {\n var body = req.query;\n var name = body.name;\n self.proc('removing', name);\n if (self.data.socketBreed) {\n self.data.socketBreed.disconnect()\n }\n self.data.socketBreed = null;\n if (self.data.socketBreed2) {\n self.data.socketBreed2.disconnect()\n }\n self.data.socketBreed2 = null;\n res.send('reset');\n });\n\n app.get('/clearLog', function clearLog(req, res) {\n var body = req.query;\n var name = body.name;\n self.proc('removing', name);\n console.log('.............clear log..................')\n sh.each.times(30, function onAdd() {\n console.log('')\n })\n res.send('clearLog');\n });\n\n\n }\n\n defineVerifyStep();\n\n //asdf.g\n\n self.active_server = app.listen(self.settings.port, function () {\n console.log('Listening on ' + self.settings.port)\n });\n\n return self.active_server;\n\n }\n\n\n self.startSocket = function startSocket() {\n // return\n console.error('startSocket ... no no n')\n var http = require('http').Server(self.app);\n var io = require('socket.io')(http);\n http.listen(self.settings.port2, function onSTarted() {\n console.log('started port2', exports.RCExtV)\n self.active_server2 = this;\n // console.log('go to ', baseUrl)\n })\n self.appSocket = io\n io.sockets.on('connection', function (socket) {\n console.log('new connnnn')\n self.pSocket = socket;\n socket.emit('news', {hello: 'world'});\n socket.on('my other event', function (data) {\n console.log(data);\n });\n /*socket.on('chat message', function (data) {\n console.log(data);\n });*/\n socket.on('chat message', function (msg) {\n io.emit('chat message', msg);\n });\n\n\n socket.on('runcmd', function onRunCmd(data) {\n self.proc('what is command', data.cmd, sh.toJSONString(data))\n // self.proc('cmd no match', data)\n\n\n self.handleSocket(data, function onFinished(a, b, c) {\n var result = {}\n\n result.a = a;\n /* if ( sh.isObject(a) ) {\n result = a; \n }*/\n result.b = b;\n result.c = c;\n if (data.noreturn != true) {\n var str = data.cmd + '' + '_results'\n self.proc('socket handled ... str', str)\n io.emit(str, result);\n }\n ;\n })\n\n return\n if (data.noreturn != true) {\n var str = data.cmd + '' + '_results'\n console.log('str', str)\n io.emit(str, data);\n }\n });\n\n\n socket.on('window.invoke', function (x) {\n console.log('window invoke')\n socket.broadcast.emit('window.invoke', x);\n })\n\n\n socket.on('getLocalFiles', function onGetLocalFiles(data) {\n self.proc('what is command', data.cmd, sh.toJSONString(data))\n\n socket.emit('getLocalFiles_results', 'cool');\n\n return\n });\n\n\n });\n\n self.http = http;\n }\n\n\n var dirCrypto = __dirname + '/' + '../' + '../'\n\n function defineCMD() {\n p.handleSocket = function handleSocket(data, fx) {\n\n\n if (sh.isWin() == false && data.fileManifest) {\n data.fileManifest = sh.fs.slash(data.fileManifest)\n //asdf.g\n if (data.fileManifest.includes('crypto/')) {\n data.fileManifest = sh.fs.join(__dirname,\n sh.str.after(data.fileManifest, 'RCExt'))\n\n }\n }\n /// sh.fs.exists(fileDlRecManifest)\n\n\n console.log(data.cmd, 'cmd')\n if (data.cmd == 'searchpb') {\n self.cmds.searchPb(data, fx)\n }\n if (data.cmd == 'listids') {\n self.cmds.listids(data, fx)\n }\n if (data.cmd == 'makemani') {\n console.log('..dfsd.')\n var dirManifest = __dirname + '/' + 'manifests/'\n sh.makePathIfDoesNotExist(dirManifest);\n\n sh.throwIfNull(data.title, 'need a title')\n\n if (data.file) {\n\n }\n if (data.tor) {\n var tors = [data.tor]\n }\n var fileDLManifest = sh.fs.join(dirManifest, data.title + '.json')\n sh.writeJSONFile(fileDLManifest, tors)\n self.proc('makemani', 'storing file here', fileDLManifest)\n\n fx({fileDLManifest: fileDLManifest})\n }\n if (data.cmd == 'dlFileList') {\n self.cmds.dlFileList(data, fx)\n }\n if (data.cmd == 'dlListTypeConfig') {\n self.cmds.dlListTypeConfig(data, fx)\n }\n\n if (data.cmd == 'dlRemoteFileList') {\n self.cmds.dlRemoteFileList(data, fx)\n }\n if (data.cmd == 'dlRemoteFileListWithSizes') {\n self.cmds.dlRemoteFileList(data, fx, true)\n }\n\n if (data.cmd == 'taskCheckProgressLite') {\n self.cmds.taskCheckProgressLite(data, fx)\n }\n\n if (data.cmd == 'taskGetDLProgressStatus') {\n self.cmds.taskGetDLProgressStatus(data, fx)\n }\n\n if (data.cmd == 'sanitizeFileList') {\n self.cmds.sanitizeFileList(data, fx)\n }\n\n if (data.cmd == 'importRecFile') {\n self.cmds.importRecFile(data, fx)\n }\n\n if (data.cmd == 'uploadAndRun') {\n self.cmds.uploadAndRun(data, fx)\n }\n\n return;\n };\n }\n\n defineCMD()\n\n\n function defineCmds() {\n p.cmds = {}\n p.cmds.sendStatus = function sendStatus(msg, type, data1) {\n var data = {};\n if (data1) {\n data = data1;\n }\n data.msg = msg;\n data.type = type;\n self.appSocket.emit('updateStatus', data);\n }\n p.cmds.searchPb = function searchPb(data, fx) {\n var dirScript = dirCrypto + '/ritv/distillerv3/utils/SearchPB.js'\n var SearchPB = require(dirScript).SearchPB\n\n self.cmds.sendStatus('msg ... starting search')\n\n var token = {};\n token.query = data.query;\n\n var options = {}\n sh.mergeObjects(token, options)\n options.query = token.query\n options.pbCategory = token.pbCategory;\n options.pbCategory2 = token.pbCategory2;\n options.showAllMatches = true\n\n if (data.searchInCategory != null) {\n options.pbCategory = data.searchInCategory;\n }\n options.pbMinSeederCount = token.pbMinSeederCount;\n\n var go = new SearchPB()\n options.callback = function onDone(_urlTorrent, token) {\n token.urlTorrent = _urlTorrent;\n self.proc('token.urlTorrent', token.query, _urlTorrent)\n if (token.testPbQuery) {\n token.fxCallback()\n return;\n }\n var result = {}\n // result.title = token.title;\n // result.urlMagnet = token.urlMagnet;\n result = token.selectedLink;\n fx(result, token.linkz);\n }\n options.fxBail = function bailX(msg) {\n\n var bailOnQuery = false;\n //TODO: if have to add a 3rd category, store searchInCategory in array\n //and verify each attempt\n //feature: bookmark.searchAgain without category restrictions\n if (token.pbCategory != null) {\n if (token.pbCategory2 == null) {\n bailOnQuery = true\n } else {\n var haveSearchedCategory2 = token.pbCategory2 == searchInCategory;\n if (haveSearchedCategory2 == true) {\n bailOnQuery = true\n } else {\n //retry\n token.query = token.query.replace('720p', '')\n self.searchByName(token, cb, token.pbCategory2)\n }\n }\n } else {\n bailOnQuery = true\n }\n\n if (bailOnQuery) {\n console.error('bailing bc', msg)\n // token.fxBail(msg)\n fx(null, msg);\n }\n }\n go.go(options);\n }\n\n console.log('...sdfxsdf......')\n p.cmds.listids = function listids(cmd, fx) {\n\n console.log('.....!@ddddd9999#d$', exports.RCExtV, self.data.id)\n var fxHelper = {}\n var fH = fxHelper;\n fH.startCmd_Dl = function startCmd_Dl(token, cb) {\n self.proc('startCmd_Dl');\n\n console.log('cmd', cmd)\n\n var listIds = sh.splitStrIntoArray(cmd.listIds)\n fx.data = {};\n fx.data.listIds = listIds;\n\n fx.data.taskName = cmd.taskName;\n if (fx.data.taskName == null) {\n fx.data.taskName = listIds[0] + listIds.length + '_more_' + sh.getTimeStamp();\n }\n console.log(sh.n)\n console.log('list', fx.data);\n console.log(sh.n)\n //display info\n\n cb();\n }\n\n\n var dirScript = 'G:/Dropbox/projects/crypto/ritv/imdb_movie_scraper/' +\n 'wrappers/imdb_app_v3_wrapper.js'\n\n dirScript = sh.deos(dirScript)\n var ConvertXToIMDB_PB_List = require(dirScript).ConvertXToIMDB_PB_List\n\n fH.dlLists = function dlLists(token, cb) {\n self.proc('dlLists');\n\n // return;\n if (cmd.wrapType == 'ttIds') {\n ConvertXToIMDB_PB_List.downloadIds(fx.data.listIds, true, fx.data.taskName, onSavedFile);\n return;\n\n }\n if (cmd.wrapType == 'idList') {\n ConvertXToIMDB_PB_List.downloadLists(fx.data.listIds, true, fx.data.taskName, onSavedFile);\n return;\n }\n\n if (cmd.wrapType == 'imdbSearch') {\n ConvertXToIMDB_PB_List.createIMDBList_fromSearch(cmd, true, fx.data.taskName, onSavedFile);\n return;\n }\n\n\n // if (cmd.wrapType == 'lsList') {\n ConvertXToIMDB_PB_List.downloadLists(fx.data.listIds, true, fx.data.taskName, onSavedFile);\n\n function onSavedFile(file) {\n console.log('finished with lax', file);\n self.utils.storeConfig(fx.data.taskName, file);\n fx.data.fileDLManifest = file;\n var fileMissing = file + '.missing.json';\n //clear\n self.proc('do have file', sh.fs.exists(fileMissing), fileMissing)\n sh.fs.delete(fileMissing, true)\n self.cmds.sendStatus('file is ' + file)\n self.cmds.sendStatus('finished making manifest')\n cb();\n }\n\n //dl list\n\n }\n fH.storeInFile = function storeInFile(token, cb) {\n self.proc('storeInFile', fx.data.fileDLManifest)\n sh.log.file(fx.data.fileDLManifest)\n fx({fileDLManifest: fx.data.fileDLManifest});\n //create manifest and return manifest name\n cb();\n }\n\n\n var token = {}\n\n var work = new PromiseHelperV3();\n token.silentToken = true\n work.wait = token.simulate == false;\n work.startChain(token)\n .add(fH.startCmd_Dl)\n .add(fH.dlLists)\n .add(fH.storeInFile)\n //.log()\n .end();\n self.cmds.sendStatus('msg ... starting search')\n\n return;\n\n\n var dirScript = dirCrypto + '/ritv/distillerv3/utils/SearchPB.js'\n var SearchPB = require(dirScript).SearchPB\n\n\n var token = {};\n token.query = data.query;\n\n var options = {}\n sh.mergeObjects(token, options)\n options.query = token.query\n options.pbCategory = token.pbCategory;\n options.pbCategory2 = token.pbCategory2;\n options.showAllMatches = true\n\n if (data.searchInCategory != null) {\n options.pbCategory = data.searchInCategory;\n }\n options.pbMinSeederCount = token.pbMinSeederCount;\n\n var go = new SearchPB()\n options.callback = function onDone(_urlTorrent, token) {\n token.urlTorrent = _urlTorrent;\n self.proc('token.urlTorrent', token.query, _urlTorrent)\n if (token.testPbQuery) {\n token.fxCallback()\n return;\n }\n var result = {}\n // result.title = token.title;\n // result.urlMagnet = token.urlMagnet;\n , result = token.selectedLink;\n fx(result, token.linkz);\n }\n options.fxBail = function bailX(msg) {\n\n var bailOnQuery = false;\n //TODO: if have to add a 3rd category, store searchInCategory in array\n //and verify each attempt\n //feature: bookmark.searchAgain without category restrictions\n if (token.pbCategory != null) {\n if (token.pbCategory2 == null) {\n bailOnQuery = true\n } else {\n var haveSearchedCategory2 = token.pbCategory2 == searchInCategory;\n if (haveSearchedCategory2 == true) {\n bailOnQuery = true\n } else {\n //retry\n token.query = token.query.replace('720p', '')\n self.searchByName(token, cb, token.pbCategory2)\n }\n }\n } else {\n bailOnQuery = true\n }\n\n if (bailOnQuery) {\n console.error('bailing bc', msg)\n // token.fxBail(msg)\n fx(null, msg);\n }\n }\n go.go(options);\n }\n p.cmds.dlFileList = function dlFileList(cmd, fx) {\n\n\n console.log('.....!@ddddd9999#d$', exports.RCExtV, self.data.id)\n\n //dl file\n //put in fileOutput dir\n\n var t = EasyRemoteTester.create('Dl List', {});\n var data = {};\n var urls = {};\n urls.notes = {};\n urls.reload = t.utils.createTestingUrl('reload')\n urls.file = cmd.url;\n // t.settings.baseUrl = baseUrl;\n t.settings.silent = true;\n\n var fileFileList = cmd.url.split('/').slice(-1)[0];\n\n\n sh.mkdirp(self.data.dirFileList);\n fileFileList = sh.fs.join(self.data.dirFileList, fileFileList)\n\n t.add(function dlFile() {\n t.quickRequest(urls.file,\n 'get', onResult)\n function onResult(body) {\n\n self.proc('saving file to ', fileFileList)\n sh.writeFile(fileFileList, body)\n\n fx();\n // console.log('body', body)\n // t.assert(body.id>0, 'post-verify did not let me do a search');\n t.cb();\n }\n }\n );\n\n }\n\n p.cmds.dlListTypeConfig = function dlListTypeConfig(cmd, fx) {\n console.log('.....!@ddddd9999#d$', exports.RCExtV, self.data.id)\n\n //dl file\n //put in fileOutput dir\n\n var t = EasyRemoteTester.create('Dl List', {});\n var data = {};\n var urls = {};\n urls.notes = {};\n urls.reload = t.utils.createTestingUrl('reload')\n urls.file = cmd.url;\n // t.settings.baseUrl = baseUrl;\n t.settings.silent = true;\n\n var fileFileList = cmd.url.split('/').slice(-1)[0];\n\n\n sh.mkdirp(self.data.dirFileList);\n fileFileList = sh.fs.join(self.data.dirFileList, fileFileList)\n\n t.add(function dlFile() {\n t.quickRequest(urls.file,\n 'get', onResult)\n function onResult(body) {\n\n self.proc('saving file to ', fileFileList)\n sh.writeFile(fileFileList, body)\n\n fx();\n // console.log('body', body)\n // t.assert(body.id>0, 'post-verify did not let me do a search');\n t.cb();\n }\n }\n );\n\n }\n\n\n }\n\n defineCmds();\n\n\n function defineCrossCmds() {\n p.cmds.dlRemoteFileList = function dlRemoteFileList(cmd, fx, withSizes) {\n console.log('.....!@ddddd9999#d$', exports.RCExtV, self.data.id)\n var fileScript = sh.fs.join(__dirname, 'supporting', 'WorkflowGetFilesFromRemoteMachine.js');\n var GetFileListFromRemote = require(fileScript).GetFileListFromRemote;\n\n // var dirFileLists = sh.fs.makePath(__dirname, 'data', 'files')\n\n var data = cmd;\n\n var fileDlManifest = sh.fs.join(self.data.dirDlManifests, cmd.fileManifest);\n var fileFileList = sh.fs.join(self.data.dirFileList, cmd.fileFileList);\n\n //self.cmds.sendStatus('running dlRemoteFileList');\n var type = 'dlRemoteFileList'\n if (withSizes) {\n type += 'WithSizes'; //dlRemoteFileListWithSizes\n }\n self.cmds.sendStatus('running dlRemoteFileList', type);\n\n var instance = new GetFileListFromRemote();\n var config = {};\n //config.ip = '127.0.0.1'\n //config.port = '6014'\n\n config.socket = self.data.socketBreed;\n if (cmd.url) {\n self.proc('port ip set')\n var split = cmd.url.split(':')\n config.ip = split[0];\n config.port = split[1];\n }\n\n config.ip = data.ip;\n config.port = data.port;\n\n if (withSizes) {\n config.withSizes = true;\n }\n\n if (data.initGFFRM) {\n self.proc('data.initGFFRM', '... ... ...');\n config.initGFFRM = data.initGFFRM;\n }\n //config.localTest = true\n config.fxDone = function fxDone(file, dataResult) {\n //console.log('...', 'y')\n self.proc('sending a result back.....');\n // console.log('-----------------what is reuslt', dataResult, 'ok')\n // self.cmds.sendStatus('done dlRemoteFileList '+ file);\n\n if (instance.data.socket && self.data.socketBreed == null) {\n self.data.socketBreed = instance.data.socket;\n }\n\n var output = {};\n output.data = file;\n /// self.cmds.sendStatusType('dlRemoteFileList')\n self.cmds.sendStatus('done dlRemoteFileList ' + file, type, output);\n\n if (data.initGFFRM) {\n self.cmds.sendStatus('done dlRemoteFileList ' + file, 'initGFFRM', dataResult);\n }\n }\n instance.init(config)\n\n\n }\n\n\n p.cmds.taskCheckProgressLite = function taskCheckProgressLite(cmd, fx) {\n console.log('.....!@ddddd9999#d$', exports.RCExtV, self.data.id)\n\n // var dirFileLists = sh.fs.makePath(__dirname, 'data', 'files')\n\n var fileDlManifest = cmd.fileManifest\n // var fileDlManifest = sh.fs.join(self.data.dirDlManifests, cmd.fileManifest);\n if (fileDlManifest.includes('/') == false && fileDlManifest.includes('\\\\') == false) {\n var fileDlManifest = sh.fs.join(self.data.dirDlManifests, cmd.fileManifest);\n }\n\n var fileFileList = cmd.fileFileList\n console.log('fileFileList', '<<<<<<<<<<<', fileFileList)\n if (fileFileList) {\n console.log('...', '')\n }\n if (fileFileList.includes('/') == false && fileFileList.includes('\\\\') == false) {\n var fileFileList = sh.fs.join(self.data.dirFileList, cmd.fileFileList);\n }\n\n console.log('fileFileList', '------------', fileFileList)\n\n self.cmds.sendStatus('running tool');\n var type = 'taskCheckProgressLite'\n self.cmds.sendStatus('running taskCheckProgressLite', type);\n\n RCScripts.verifyComplete(fileDlManifest, fileFileList, function onDone(output) {\n console.log('found how many?', output.foundCount);\n output.itemsValid = null;\n output.itemsFound = null;\n output.lines = output.lines.length\n output.result = 'found ' + output.foundCount;\n // sh.throwIf(output.foundCount != 2, 'did not match write count of items');\n fx(output);\n self.cmds.sendStatus('done with ' +\n type + ' ' + output.foundCount, type, output);\n });\n\n return;\n }\n\n p.cmds.taskGetDLProgressStatus = function taskGetDLProgressStatus(cmd, fx) {\n console.log('.....!@ddddd9999#d$', exports.RCExtV, self.data.id)\n /* var fileDlManifest = cmd.fileManifest\n // var fileDlManifest = sh.fs.join(self.data.dirDlManifests, cmd.fileManifest);\n if (fileDlManifest.includes('/') == false && fileDlManifest.includes('\\\\') == false) {\n var fileDlManifest = sh.fs.join(self.data.dirDlManifests, cmd.fileManifest);\n }\n\n var fileFileList = cmd.fileFileList\n console.log('fileFileList', '<<<<<<<<<<<', fileFileList)\n if ( fileFileList ) {\n console.log('...', '')\n }\n if (fileFileList.includes('/') == false && fileFileList.includes('\\\\') == false) {\n var fileFileList = sh.fs.join(self.data.dirFileList, cmd.fileFileList);\n }\n\n console.log('fileFileList', '------------', fileFileList)*/\n self.cmds.sendStatus('running tool');\n var type = 'taskGetDLProgressStatus'\n self.cmds.sendStatus('running taskGetDLProgressStatus', type);\n\n var t = EasyRemoteTester.create('Dl List', {});\n var data = {};\n var urls = {};\n urls.notes = {};\n t.settings.baseUrl = 'http://'+cmd.url;\n urls.file = t.utils.createTestingUrl('getStatus_ofInProgress')\n\n // t.settings.baseUrl = baseUrl;\n t.settings.silent = true;\n /*\n var fileFileList = cmd.url.split('/').slice(-1)[0];\n sh.mkdirp(self.data.dirFileList);\n fileFileList = sh.fs.join(self.data.dirFileList, fileFileList)\n\n */\n t.add(function dlFile() {\n t.quickRequest(urls.file,\n 'get', onResult)\n function onResult(body) {\n\n //self.proc('saving file to ', fileFileList)\n //sh.writeFile(fileFileList, body)\n\n console.log('body')\n body = sh.replace(body, '<br />', '\\n')\n body = sh.replace(body, '&nbsp;', ' ')\n console.log(body)\n\n fx();\n // console.log('body', body)\n // t.assert(body.id>0, 'post-verify did not let me do a search');\n t.cb();\n }\n }\n );\n }\n\n p.cmds.uploadAndRun = function uploadAndRun(cmd, fx) {\n self.proc('.....!@uploadAndRun#d$', exports.RCExtV, self.data.id)\n var fileDlManifest = self.utils.appendDirIfRelative(self.data.dirDlManifests, cmd.fileManifest)\n //var fileDlRecManifest=fileDlManifest+'.recipet.json'\n var fileDlManifestMissingFilesOnly = self.utils.appendDirIfRelative(self.data.dirDlManifests, cmd.fileManifest + '.missing.json')\n\n console.log('fileFileList', '<<<<<<<<<<<', fileDlManifest)\n\n self.cmds.sendStatus('running tool');\n\n var type = 'uploadAndRun'\n self.cmds.sendStatus('running uploadAndRun', type);\n\n if (sh.fs.exists(fileDlManifest) == false) {\n self.cmds.sendStatus('FAILED .... do the import first ', type);\n return;\n }\n\n if (sh.fs.exists(fileDlManifestMissingFilesOnly)) {\n self.proc('...', 'fileDlManifestMissingFilesOnly')\n fileDlManifest = fileDlManifestMissingFilesOnly\n self.cmds.sendStatus('running uploadAndRun with fileDlManifestMissingFilesOnly file---', type);\n }\n\n var cfg = sh.clone(cmd);\n cfg.fileManifest = fileDlManifest;\n cfg.ip = cmd.ip;\n cfg.port = cmd.port;\n delete cfg.url;\n cfg.socket = self.data.socketBreed2;\n console.log('111what is socket', cfg.socket)\n\n Workflow_UploadAndRun.uploadAndRun(cfg, function onDone(output) {\n console.log('found how many?', output);\n output.complete = true;\n output.result = 'fxed' + output.count;\n fx(output);\n self.data.socketBreed2 = cfg.socket\n self.cmds.sendStatus('done with ' + type, type, output);\n });\n\n return;\n }\n\n p.cmds.sanitizeFileList = function sanitizeFileList(cmd, fx) {\n console.log('.....!@ddddd9999#d$', 'sanitizeFileList',\n exports.RCExtV, self.data.id)\n //why: will import files into db, \n //will search manifest for files in db \n\n //2 check globally for path of file\n //make test dmoe file \n //see if it can find fake demo file \n\n // var dirFileLists = sh.fs.makePath(__dirname, 'data', 'files')\n\n //var fileDlManifest = sh.fs.join(self.data.dirDlManifests, cmd.fileManifest);\n //var fileFileList = sh.fs.join(self.data.dirFileList, cmd.fileFileList);\n\n\n //var fileDlManifest = sh.fs.join(self.data.dirDlManifests, cmd.fileManifest);\n var fileDlManifest = self.utils.appendDirIfRelative(self.data.dirDlManifests, cmd.fileManifest)\n var fileFileList = self.utils.appendDirIfRelative(self.data.dirFileList, cmd.fileFileList)\n /*\n\n var fileFileList = cmd.fileFileList\n\n\n if ( fileFileList.includes('/') == false && fileFileList.includes('\\\\') == false ) {\n var fileFileList = sh.fs.join(self.data.dirFileList, cmd.fileFileList);\n }\n */\n\n self.proc('fileFileList', '<<<<<<<<<<<', fileFileList)\n\n self.cmds.sendStatus('running tool');\n\n var type = 'sanitizeFileList'\n self.cmds.sendStatus('running sanitizeFileList', type);\n\n\n var cfg = {}\n\n cfg.fileList = fileFileList\n cfg.fileManifest = fileDlManifest\n\n cfg.fxDone = function onDone(output) {\n console.log('found how many?', output.foundCount);\n output.itemsValid = null;\n output.itemsFound = null;\n // output.lines = output.lines.length\n //sh.throwIf(output.foundCount != 2, 'did not match write count of items');\\\n var outputLite = self.utils.flatten(output)\n outputLite.output = JSON.stringify(outputLite)\n\n\n if (self.data.createFilteredList) {\n var fileDlRecManifest = fileDlManifest + '.recipet.json'\n }\n\n console.log('xoutput', outputLite)\n\n fx(output);\n self.cmds.sendStatus('done with sanitizeFileList ' + output.foundCount, type, outputLite);\n }\n //cfg.searchGlobalAllServers = true;\n\n /*\n cfg.checkFileSizes = true; //import the size in the filelist\n //make dl list get the import dl list\n cfg.checkForIMDB = true; //\n cfg.checkForFilePath = true; //match if ay portion is in file name ///so it would not concern with the end of file name ...\n //that's enough\n */\n\n RCScripts.checkPercentageCompleteDeep(cfg);\n\n return;\n }\n\n\n p.cmds.importRecFile = function importRecFile(cmd, fx) {\n console.log('.....!@ddddd9999#d$', exports.RCExtV, self.data.id)\n // var dirFileLists = sh.fs.makePath(__dirname, 'data', 'files')\n\n //var fileDlManifest = sh.fs.join(self.data.dirDlManifests, cmd.fileManifest);\n var fileDlManifest = self.utils.appendDirIfRelative(self.data.dirDlManifests, cmd.fileManifest)\n //var fileFileList = self.utils.appendDirIfRelative(self.data.dirFileList, cmd.fileFileList)\n\n var fileDlRecManifest = fileDlManifest + '.recipet.json'\n\n /*\n sh.fs.exists(fileDlManifest, 'this file must exist', function onError(err) {\n })\n */\n\n console.log('fileFileList', '<<<<<<<<<<<', fileDlRecManifest)\n\n self.cmds.sendStatus('running tool');\n\n var type = 'importRecFile'\n self.cmds.sendStatus('running importRecFile', type);\n\n if (sh.fs.exists(fileDlRecManifest) == false) {\n self.cmds.sendStatus('FAILED .... do the import first ', type);\n return;\n }\n\n Workflow_ImportVidsAgain.importRecFile(fileDlRecManifest, function onDone(output) {\n console.log('found how many?', output);\n output.complete = true\n output.result = 'fxed' + output.count\n fx(output);\n self.cmds.sendStatus('done with importRecFile ', type, output);\n });\n\n return;\n }\n\n\n }\n\n defineCrossCmds()\n\n function defineUtils() {\n p.utils = {}\n\n p.utils.storeConfig = function storeConfig_ForRecent(name, file) {\n //var fileConfig = sh.fs.makePath(__dirname, /*'../',*/ 'configs', name+'')\n // sh.fs.copy(file, fileConfig, true)\n\n var fileConfig = sh.fs.makePath(__dirname, 'manifests', name + '.json');\n self.proc('copy', file, 'to', fileConfig);\n sh.fs.copy(file, fileConfig, true);\n\n\n var bookJSON = {\n file: fileConfig,\n created_at: new Date(),\n name: name\n }\n self.data.j2.addRecent(bookJSON, true, 'file');\n //self.data.j.addRecent(j)\n\n }\n\n\n p.utils.appendDirIfRelative = function appendDirIfRelative(dir, file) {\n var fileOutput = file;\n if (file.includes('/') == false && file.includes('\\\\') == false) {\n var fileOutput = sh.fs.join(dir, file);\n }\n\n return fileOutput;\n }\n p.utils.flatten = function flatten(output, file) {\n var lite = sh.clone(output)\n var outputLite = {}\n sh.each(output, function copyOrCondense(k, v) {\n var val = v;\n if (sh.isArray(v)) {\n val = v.length;\n }\n outputLite[k] = val;\n })\n return outputLite;\n }\n }\n\n defineUtils();\n\n\n function defineTestsMethods() {\n p.addTest = function onAddTest(fx) {\n self.data.fxTests = sh.dv(self.data.fxTests, [])\n self.data.fxTests.push(fx)\n }\n p.runTests = function runTests() {\n sh.each(self.data.fxTests, function onTests(k, v) {\n v();\n })\n }\n }\n\n defineTestsMethods()\n /**\n * Receive log commands in special format\n */\n p.proc = function proc() {\n sh.sLog(arguments)\n }\n}", "serve() {\n // a no-op, these are absolute URLs\n return function(req, res, next) {\n next();\n };\n }", "function serve() {\n connect.server(serverConfig);\n}", "function unifiedServer(req, res) {\n // Get the Url Object\n const parsedUrl = url.parse(req.url, true);\n // Get the trimmed path\n const { pathname } = parsedUrl;\n const trimmedPath = pathname.replace(/^\\/+|\\/+$/g, \"\");\n // Get the HTTP method\n const method = req.method.toLowerCase();\n\n // Get the payload\n const decoder = new StringDecoder(\"utf-8\");\n let buffer = \"\";\n\n req.on(\"data\", data => {\n buffer += decoder.write(data);\n });\n req.on(\"end\", () => {\n buffer += decoder.end();\n const handler =\n typeof router[trimmedPath] !== \"undefined\"\n ? handlers[trimmedPath][method]\n : handlers.notFound;\n\n handler(buffer, (statusCode, payloadString) => {\n res.setHeader(\"Content-Type\", \"application/json\");\n res.writeHead(statusCode);\n res.end(JSON.stringify(payloadString));\n });\n });\n}", "setup() {\n this.app.use(express.json());\n\n this.app.get('/', (req, res) => {\n res.send(\"Hello World!\")\n });\n }", "function startServer () {\n // Enable CORS for all requests\n app.use(require('cors')());\n\n // Note: the order which we add middleware to Express here is important!\n app.use('/sys', mbaasExpress.sys([]));\n app.use('/mbaas', mbaasExpress.mbaas);\n\n // Note: important that this is added just before your own Routes\n app.use(mbaasExpress.fhmiddleware());\n\n // Important that this is last as per express conventions!\n app.use(mbaasExpress.errorHandler());\n\n const port = process.env.FH_PORT || process.env.OPENSHIFT_NODEJS_PORT || 8001;\n const host = process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0';\n\n server.listen(port, host, undefined, () => {\n log.info(`application started on ${host}:${port}`);\n });\n}", "constructor() {\n\t\tthis.app = express();\n\t\tthis.initExpress();\n\t\tthis.initExpressMiddleWare();\n\t\tthis.initControllers();\n\t\tthis.start();\n\t}", "override() {\n this.app.use(override());\n }", "function middleware(req, res, next) {\n req.context = createNamespace('context');\n req.context.run(() => next());\n}", "async registerHttpServer() {\n this.httpServer = new HttpServer(this.app, this.port);\n this.httpServer.on('error', (err) => {\n this.emit('error', err);\n });\n this.httpServer.on('info', (msg) => {\n this.emit('info', msg);\n });\n\n await this.httpServer.init();\n }", "constructor() {\n\n /** Set up a dummy ExpressJS Middleware Function\n * @param {Express.Request} req x\n * @param {Express.Response} res x\n * @param {ExpressNextFunction} next x\n */\n this.dummyMiddleware = function(req, res, next) { next() }\n\n // setTimeout(() => {\n // console.log(' \\n >> web.js dump >> ', Object.keys(this))\n // }, 3000)\n\n }", "function middleware(req, res, next) {\n\tns.run(() => next());\n}", "function localMiddleware (req, res, next) {\n // Tell the client what Socket.IO namespace to use,\n // trim the leading slash because the cookie will turn into a %2F\n res.setHeader('uibuilder-namespace', node.ioNamespace)\n res.cookie('uibuilder-namespace', uiblib.trimSlashes(node.ioNamespace), {path: node.url, sameSite: true})\n //res.write( '<script>var uibuilderIOnamespace = ' + node.ioNamespace + '</script>')\n next()\n }", "function afterIsomorphicToolsSetup() {\n // require renderingMiddleware after isomorphic tools setup has finished, so that requireing assets works\n const renderingMiddleware = require('./server-rendering').default;\n app.use(renderingMiddleware(isomorphicTools));\n\n // start server\n server.listen(3000, () => {\n var host = server.address().address;\n var port = server.address().port;\n\n console.log('[server] listening at http://%s:%s', host, port);\n });\n}", "function startServer() {\n\tapp.serverInstance = server.listen(config.PORT, config.HOST, function() {\n\t\tlogger.info('Express server listening on %d, in %s mode...', config.PORT, config.ENV);\n\t});\n}", "function setup(format) {\n const regex = /:(\\w+)/g;\n\n // Specific call for starting server\n if (format.match(regex).includes(':start')) {\n const port = format.match(/:port=(\\d+)/).slice(1);\n serverlog(magenta, green, 'Server up and running on port ' + port);\n\n } else {\n // Return logger middleware that allows configurable methods of the request\n // object to be passed and thus logged\n return function logger(req, res, next) {\n const str = format.replace(regex, function(match, property) {\n return req[property];\n });\n serverlog(yellow, green, str);\n next();\n }\n }\n}", "function startHttpServer() {\n var server = http.createServer(httpRequestHandler);\n var port = program.port || httpRequestHandler.get('port');\n\n server.listen(port, function() {\n console.log('\\nPersonalization server listening on port ' + port);\n });\n}", "setupFrontendServer() {\n\t\t// All other requests are served react views\n\t\tthis.frontendRouter.get('/*', this.frontendServer.run.bind(this.frontendServer));\n\n\t\t// Setting up the vhost\n\t\tthis.app.use(vhost(Config.domain, this.frontendRouter));\n\n\t\t// Exposing it without vhost for easier usage\n\t\tthis.app.use(this.frontendRouter);\n\t}", "config() {\n this.app.set('port', 3000);\n this.app.use(morgan_1.default('dev'));\n this.app.use(cors_1.default());\n this.app.use(express_1.default.json());\n this.app.use(express_1.default.urlencoded({ extended: false }));\n }", "constructor() {\n this.app = express();\n this.setupControllers();\n this.middleware();\n }", "_mount() {\n\t\tthis._mergeMiddleware(this._parent);\n\n\t\tthis._requestHandler = new RequestHandler(this);\n\t\tthis._parent._router[this._method](this._path, util.WrapAsyncFunction((req, res) => this._requestHandler.handle(req, res)));\n\t}", "function Server(config, http)\n{\n // Handlebars for the templating engine + layout style\n var viewPath = path.resolve(path.join(__dirname, './views'));\n http.engine('hbs.html', exphbs({\n defaultLayout: 'main',\n extname: '.hbs.html',\n layoutsDir: path.resolve(path.join(__dirname, './views/layouts'))\n }));\n http.set('views', viewPath);\n http.set('view engine', 'hbs.html');\n console.log('view path set to %s', viewPath);\n\n // Favvies\n http.use(favicons(path.join(__dirname, '../../public/icons')));\n\n // Server out static files\n http.use(express.static(config('http.webroot')));\n console.log('static server middleware added');\n}", "start (port) {\n // Listen for and handle incoming HTTP requests\n this.server.on('request', (request, response) => {\n const res = new Response(response)\n this.handleRequest(request, res)\n })\n\n this.server.listen(port)\n }", "function myServer() {\n\tthis.server = server;\n}", "function init(server, options) {\n\tvar that = this;\n\toptions = options || {};\n\tthis.options = options;\n\tthis.server = server;\n\n\t// Initialize hook chains\n\tthis.pre_hooks = {};\n\tthis.post_hooks = {};\n\tthis.finally_hooks = {};\n\tvar hook = new fl.Chain();\n\thook.name = 'default';\n\tthis.pre_hooks.default = hook;\n\thook = new fl.Chain();\n\thook.name = 'default';\n\tthis.post_hooks.default = hook;\n\thook = new fl.Chain();\n\thook.name = 'default';\n\tthis.finally_hooks.default = hook;\n\n\t// dustjs-linkedin template and routing configuration\n\tthis.client_templates = [];\n\tthis.load_dust_templates(this.options.template_dir, this.options.client_prefix, this.options.both_prefix);\n\tserver.get(this.options.client_path, function(req, res) {\n\t\tres.set('Content-Type', 'application/javascript');\n\t\tres.send(that.client_templates.join(' '));\n\t});\n\n\t// Add common/default filters and helpers to dust\n\tthis.add_default_dust_filters();\n\tthis.add_default_dust_helpers();\n\n\t// Load routes from the file system\n\tthis.load_routes(this.options.route_dir);\n\n\t// Add error handler AFTER all routes have been populated\n\tserver.use(function(err, req, res, next) {\n\t\thandle_server_error(err, req, res, next, that);\n\t});\n\n\t// Add shutdown method as our SIGINT handler\n\tprocess.on('SIGINT', this.shutdown.bind(this));\n\n\t// Finally, listen connections\n\tvar localServer = http.Server(server);\n\n\tlocalServer.listen(options.port);\n\tthis.io = sio(localServer);\n//\tthis.options.shutdown.push({\n//\t\tfn : this.io.close,\n//\t\tctx : this.io\n//\t});\n\n\tlogger.module_init(mod_name, mod_version, 'Express server listening on port '+options.port);\n}", "function my_middleware(req, res, next){\n\tconsole.log('Hello Middleware');\n\tnext();\n}", "constructor() {\n _defineProperty(this, \"express\", void 0);\n\n this.express = (0, _express.default)();\n this.middleware();\n this.routes();\n }", "function extendExpress(app) {\t\n\tconsole.log(\" plugin- extendExpress()\");\t\n}", "config() {\n this.app.set(\"PORT\", process.env.PORT || 3000);\n this.app.use(morgan_1.default(\"dev\")); //Miraremos las peticiones en modo desarrollador.\n this.app.use(cors_1.default()); //Permitira que clientes haga peticiones\n this.app.use(express_1.default.json()); //La app entendera json gracias a esto\n this.app.use(express_1.default.urlencoded({ extended: false })); //Permite peticiones por HTML\n }", "serve() {\n this.server.listen(this.port);\n console.log(`Port: ${this.port}`);\n }", "function setupServer() {\r\n //\r\n // Middleware's\r\n //\r\n\r\n // Use HTTP sessions\r\n let session = require('express-session')({\r\n secret: 'session_secret_key',\r\n resave: true,\r\n saveUninitialized: false\r\n });\r\n app.use(session);\r\n\r\n // Use Socket IO sessions\r\n let sharedSession = require(\"express-socket.io-session\")(session, {autoSave: true});\r\n io.use(sharedSession);\r\n\r\n // Parse the body of the incoming requests\r\n let bodyParser = require('body-parser');\r\n app.use(bodyParser.json());\r\n app.use(bodyParser.urlencoded({extended: false}));\r\n\r\n // Set static path to provide required assets\r\n let path = require('path');\r\n app.use(express.static(path.resolve('../client/')));\r\n\r\n //\r\n // Routes\r\n //\r\n\r\n // Authentication view endpoint\r\n app.get('/', function (req, res) {\r\n if (req.session.user) {\r\n res.sendFile(path.resolve('../client/views/profile.html'));\r\n }\r\n else {\r\n res.sendFile(path.resolve('../client/views/auth.html'));\r\n }\r\n });\r\n\r\n // Main game screen\r\n app.get('/play', function (req, res) {\r\n req.session.name = req.session.name || \"\";\r\n\r\n res.sendFile(path.resolve('../client/views/index.html'));\r\n });\r\n\r\n // Join endpoint\r\n app.post('/join', function (req, res) {\r\n req.session.name = (req.session.user ? req.session.user.username : req.body.name) || \"\";\r\n res.json({status: 0});\r\n });\r\n\r\n // Register endpoint\r\n app.post('/register', function (req, res) {\r\n let username = req.body.username;\r\n let password = req.body.password;\r\n\r\n if (!username || !password) {\r\n return res.json({status: 1, error_msg: \"Invalid register request\"});\r\n }\r\n\r\n let userData = {\r\n username: username,\r\n password: password,\r\n highScore: 10\r\n };\r\n\r\n // Try registering the user\r\n User.create(userData, function (error, user) {\r\n if (error || !user) {\r\n res.json({status: 1, error_msg: \"The username already exists\"});\r\n console.log(\"error in registering\", error);\r\n }\r\n else {\r\n req.session.user = user;\r\n req.session.name = user.username;\r\n res.json({status: 0});\r\n console.log(user.username, \"has registered...\");\r\n }\r\n });\r\n });\r\n\r\n // Log in post request endpoint\r\n app.post('/login', function (req, res) {\r\n let username = req.body.username;\r\n let password = req.body.password;\r\n\r\n if (!username || !password) {\r\n return res.json({status: 1, error_msg: \"Invalid login request\"});\r\n }\r\n\r\n // Authenticate user's credentials\r\n User.authenticate(username, password, function (error, user) {\r\n if (error) {\r\n res.json({status: 1, error_msg: error.message});\r\n console.log(\"error in logging in\", error);\r\n }\r\n else {\r\n req.session.user = user;\r\n req.session.name = user.username;\r\n res.json({status: 0});\r\n console.log(user.username, \"has logged in...\");\r\n }\r\n });\r\n });\r\n\r\n // Log out endpoint\r\n app.get('/logout', function (req, res) {\r\n // Destroy session object\r\n if (req.session) {\r\n let username = req.session.user;\r\n\r\n req.session.destroy(function (err) {\r\n if (err) {\r\n res.json({status: 1, error_msg: \"Please try again later!\"});\r\n console.log(\"error in logging out\", error);\r\n }\r\n else {\r\n res.json({status: 0});\r\n console.log(username, \"has logged out...\");\r\n }\r\n });\r\n }\r\n });\r\n}", "function prepareRungServer() {\n const server = http.createServer((req, res) => {\n if (req.method !== 'POST') {\n res.writeHead(404);\n return res.end();\n }\n\n const routes = {\n '/login': ~res.writeHead(200),\n '/metaExtensions/drafts': ~res.writeHead(201)\n };\n\n routes[req.url]();\n return res.end();\n });\n\n return new Promise(server.listen(FAKE_SERVER_PORT, _));\n}", "constructor(router, port) {\n this.server = http.createServer(function(req, res) {\n req.chunks = [];\n req.on('data', function(chunk) {\n req.chunks.push(chunk.toString());\n });\n\n //HANDLES ERRORS FOR CALL\n router.dispatch(req, res, function(err) {\n res.writeHead(err.status, {'Content-Type': 'text/plain'});\n res.end(err.message);\n });\n });\n\n this.port = Number(process.env.PORT || 3000);\n }", "function serverHandler(request, response) {\n try {\n console.log('request received: ' + request.url);\n\n if(request.url === '/') {\n response.writeHead(200, {'Content-Type': 'text/html'});\n response.end(fs.readFileSync('../client/index.html'));\n } else if(request.url === '/webrtc.js') {\n response.writeHead(200, {'Content-Type': 'application/javascript'});\n response.end(fs.readFileSync('../client/webrtc.js'));\n }else if(request.url === '/index2.css') {\n response.writeHead(200, {'Content-Type': 'application/javascript'});\n response.end(fs.readFileSync('../client/index2.css'));\n }\n else{\n request.end();\n }\n } catch (e) {\n response.writeHead(404, {\n 'Content-Type': 'text/plain'\n });\n response.write('<h1>Unexpected error:</h1><br><br>' + e.stack || e.message || JSON.stringify(e));\n response.end();\n }\n}", "function TestHTTPServer(middleware, options) {\n this.options = options || {};\n this.middleware = middleware;\n this.listener = null;\n this.id = ++serverID;\n this.app = express();\n var r1 = express.Router();\n r1.get('/*', middleware);\n this.app.use(r1);\n}", "middlewares() {\n //directorio publico\n this.app.use(express.static('public'));\n\n //convertir los datos que llegan en json\n this.app.use(express.json());\n }", "create () {\n this.server = https.createServer(\n Object.assign({\n IncomingMessage: CherryIncomingMessage,\n ServerResponse: CherryServerResponse\n }, this.options.httpsOptions),\n (req, res) => {\n this.bootstrap(req, res)\n }\n )\n }", "constructor() {\n this.express = express();\n this.middleware();\n this.routes();\n }", "async prepareServer() {\n this.options.server && (this.server = await this.addService('server', new this.ServerTransport(this.options.server))); \n }", "middlewares() {\n this.app.use(express.urlencoded({ extended: true }));\n this.app.use(express.json());\n this.app.use(express.static(resolve(__dirname, 'uploads')));\n this.app.use(cors())\n }", "getMiddleware() {\n const router = express.Router();\n router.options(this.path, (request, response, next) => {\n if (!this.handleAbuseProtectionRequests(request, response)) {\n next();\n }\n });\n router.post(this.path, (request, response, next) => __awaiter(this, void 0, void 0, function* () {\n try {\n if (!(yield this._cloudEventsHandler.processRequest(request, response))) {\n next();\n }\n }\n catch (err) {\n next(err);\n }\n }));\n return router;\n }", "_createServer(){\n if ( this._server === null ){\n // Create a new HTTP server.\n this._server = net.createServer(this._options);\n // Bind event handlers.\n this._bindEventHandlers();\n }\n }", "_createServer() {\n // Listen to the port and save the http native server\n this._server = this._app.listen(this.params.port)\n\n // Keep track of sockets to be able to close \n // all of them when we want to close the server\n this._sockets = {};\n this._nextSocketId = 0;\n this._server.on('connection', (socket) => {\n // Add a newly connected socket\n var socketId = this._nextSocketId++;\n this._sockets[socketId] = socket;\n\n // Remove the socket when it closes\n socket.on('close', () => {\n delete this._sockets[socketId];\n });\n\n });\n }", "function startServer() {\n Http.listen(env.serverPort, () => {\n console.log('Listening at :' + env.serverPort + '...');\n });\n}", "startup(port, ipAddress) {\n // Todo: http.globalAgent.maxSockets, http.globalAgent.maxFreeSockets\n if (_config.https) {\n this.server = https.createServer({\n cert: _config.https.cert,\n key: _config.https.key,\n ca: _config.https.ca,\n ciphers: arsenal.https.ciphers.ciphers,\n dhparam: arsenal.https.dhparam.dhparam,\n rejectUnauthorized: true,\n });\n logger.info('Https server configuration', {\n https: true,\n });\n } else {\n this.server = http.createServer();\n logger.info('Http server configuration', {\n https: false,\n });\n }\n\n this.server.on('connection', socket => {\n socket.on('error', err => logger.info('request rejected',\n { error: err }));\n });\n\n // https://nodejs.org/dist/latest-v6.x/\n // docs/api/http.html#http_event_checkexpectation\n this.server.on('checkExpectation', this.routeRequest);\n\n this.server.on('request', this.routeRequest);\n\n this.server.on('checkContinue', this.routeRequest);\n\n this.server.on('listening', () => {\n const addr = this.server.address() || {\n address: ipAddress || '[::]',\n port,\n };\n logger.info('server started', { address: addr.address,\n port: addr.port, pid: process.pid });\n });\n if (ipAddress !== undefined) {\n this.server.listen(port, ipAddress);\n } else {\n this.server.listen(port);\n }\n }", "function next() {\n\t\thttpServer( opts );\n\t}", "registerHttpServer() {\n this.application.container.singleton('Adonis/Core/Server', () => {\n const { Server } = require('../src/Server');\n const Config = this.application.container.resolveBinding('Adonis/Core/Config');\n const Encryption = this.application.container.resolveBinding('Adonis/Core/Encryption');\n const serverConfig = Config.get('app.http', {});\n this.validateServerConfig(serverConfig);\n return new Server(this.application, Encryption, serverConfig);\n });\n }", "start (cb) {\n // Globally intercept 404 errors and return a `res.notFound` rather than the\n // default Express 404 page. This allows a view to be used when added to\n // your views directory at `responses/404.jts`.\n this.app.use((req, res, next) => {\n if (parseUrl(req).pathname === '/favicon.ico') return next()\n res.notFound()\n })\n\n const ready = function () {\n this.app.events.emit('ready')\n if (!cb) return\n\n // If no Mongo connection is configured OR if Mongo has already\n // established a connection, the ready callback is called immediately.\n if (!this.app.mongo || this.app.mongo.connection.readyState === 1) {\n return cb(null, this.server)\n }\n\n this.app.mongo.connection.once('connected', () => cb(null, this.server))\n }.bind(this)\n\n try {\n this.server.listen(this.app.get('port'), () => {\n this.app.log.info()\n this.app.log.info(`Server running on port ${this.server.address().port} in ${this.app.get('env')} mode.`)\n this.app.log.info('To shut down press <CTRL> + C at any time.')\n this.app.log.info()\n\n if (!this.app.config.waitForReady) {\n return ready()\n }\n\n // If the launch of the server involves asynchronous activities it may\n // be helpful to enable `waitForReady` in your `app.config` settings.\n // Once all asynchronous activies have been completed, simply call\n // `app.events.emit('ready');` and your callback will fire. This can be\n // useful when testing asynchronous hooks. If you need to delay binding\n // to port see `.startWhenReady()` below.\n this.app.events.once('ready', () => cb(null, this.server))\n })\n } catch (err) {\n cb(err)\n }\n return this.app\n }", "function main () {\n let app = express(); // Export app for other routes to use\n let handlers = new HandlerGenerator();\n const port = process.env.PORT || 8000;\n app.use(bodyParser.urlencoded({ // Middleware\n extended: true\n }));\n app.use(bodyParser.json());\n // Routes & Handlers\n app.post('/login', handlers.login);\n app.get('/', middleware.checkToken, handlers.index);\n app.listen(port, () => console.log(`Server is listening on port: ${port}`));\n}", "serve() {\n\t\tconst server = new Server(this);\n\t\tconst serverConfig = this._config.devServer;\n\n\t\tserver.logServer('/log');\n\n\t\tif (serverConfig.enableRawProxy) {\n\t\t\tserver.rawProxy('/proxy');\n\t\t}\n\n\t\tconst proxyMap = serverConfig.proxy;\n\t\tObject.keys(proxyMap)\n\t\t\t.forEach((path) => {\n\t\t\t\tserver.proxy(path, proxyMap[path]);\n\t\t\t});\n\n\t\tlet staticFiles = {};\n\t\tfor (const entity of this._config.include) {\n\t\t\tif (entity.static) {\n\t\t\t\tstaticFiles = Object.assign(staticFiles, entity.static);\n\t\t\t}\n\t\t}\n\n\t\tlogger.silly(`Serving static files: \\n${JSON.stringify(staticFiles, null, '\\t')}`);\n\n\t\tfor (const [customPath, filePath] of Object.entries(staticFiles)) {\n\t\t\tconst alias = `/${customPath.replace(/^\\//, '')}`;\n\t\t\tconst absolutePath = this._pathHelper.resolveAbsolutePath(filePath);\n\n\t\t\tif (fs.existsSync(absolutePath)) {\n\t\t\t\tserver.serveStatic(alias, absolutePath);\n\t\t\t} else {\n\t\t\t\tlogger.warn(`Can't serve static path ${kleur.green(alias)} from ${kleur.underline(absolutePath)}`);\n\t\t\t}\n\t\t}\n\n\t\tthis._codeSource.watch();\n\n\t\tserver.start(serverConfig.port)\n\t\t\t.then((addresss) => {\n\t\t\t\tlogger.output(`Server started at ${kleur.underline(addresss)}`);\n\t\t\t}, (err) => {\n\t\t\t\tlogger.error(`Error starting server: ${err.toString()}`);\n\t\t\t\tlogger.debug(err.stack);\n\t\t\t});\n\t}", "listen() {\n this.session.on('changed', this[cookieChangedHandler]);\n ipcMain.on('open-web-url', this[openSessionWindowHandler]);\n ipcMain.handle('cookies-session-get-all', this[getAllCookiesHandler]);\n ipcMain.handle('cookies-session-get-domain', this[getDomainCookiesHandler]);\n ipcMain.handle('cookies-session-get-url', this[getUrlCookiesHandler]);\n ipcMain.handle('cookies-session-set-cookie', this[setCookieHandler]);\n ipcMain.handle('cookies-session-set-cookies', this[setCookiesHandler]);\n ipcMain.handle('cookies-session-remove-cookie', this[removeCookieHandler]);\n ipcMain.handle('cookies-session-remove-cookies', this[removeCookiesHandler]);\n app.on('certificate-error', this[handleCertIssue]);\n }", "function createServer() {\n var server = http.createServer(function (request, response) {\n var method = request.method;\n var url = request.url;\n var cookies = new Cookies(request, response);\n // Determining if this is a connection from an existing client or a new one\n var sessionId = cookies.get('sessionId');\n if ( typeof sessionId == 'undefined' ) {\n sessionId = uuid.v4();\n cookies.set('sessionId', sessionId, {path:'/'});\n }\n\n if ( this[method] instanceof Function ) {\n this[method](url, request, response);\n }\n\n\n if ( request.url == \"/favicon.ico\" ) return response.end();\n //console.log('requesting ', request.url);\n var filePath = '.' + request.url.split(\"?\")[0];\n if ( filePath == './' )\n filePath = './index.html';\n\n var extname = path.extname( filePath );\n var contentTypes = { '.js': 'text/javascript', '.css': 'text/css' };\n var contentType = contentTypes[extname] || 'text/html';\n\n fs.exists( filePath, function( exists ) {\n if ( exists ) {\n console.log(\"Serving file:\", filePath );\n fs.readFile(filePath, function( error, content ) {\n if ( error ) {\n response.writeHead( 500 );\n response.end();\n }\n else {\n response.writeHead( 200, { 'Content-Type': contentType } );\n response.end(content, 'utf-8');\n }\n });\n }\n else {\n console.log( \"File not found:\", filePath );\n response.writeHead(404);\n response.end();\n }\n });\n });\n server.listen.apply(server, arguments);\n}", "start() {\n\t\tlet self = this;\n\t\tthis.app.listen(this.app.get(\"port\"), () => {\n\t\t\tconsole.log(`Server Listening for port: ${self.app.get(\"port\")}`);\n\t\t});\n\t}", "function server () {\n return http.createServer(function (req, res) {\n var pathname = url.parse(req.url).pathname\n pathname = pathname === '/' ? '/index.html' : pathname\n const ext = path.extname(pathname)\n\n console.log(JSON.stringify({url: pathname, type: 'static'}))\n\n if (ext === '.css') res.setHeader('Content-Type', 'text/css')\n if (ext === '.js') res.setHeader('Content-Type', 'application/javascript')\n\n router.match(pathname, function (err, body) {\n if (err) {\n err = (typeof err === 'object') ? err.toString() : err\n const ndj = JSON.stringify({level: 'error', url: pathname, message: err})\n console.log(ndj)\n }\n if (isStream(body)) return body.pipe(res)\n res.end(body)\n })\n })\n}", "fireUpEngines() {\n const httpServer = http.createServer(this.app);\n httpServer.listen(this.configuration.port);\n console.log(`TreeHouse HTTP NodeJS Server listening on port ${this.configuration.port}`);\n\n // HTTPS - Optional\n if (this.configuration.https) {\n const httpsServer = https.createServer(this.getHttpsCredentials(), this.app);\n httpsServer.listen(this.configuration.https.port);\n console.log(`TreeHouse HTTPS NodeJS Server listening on port ${this.configuration.https.port}`);\n }\n }", "_cliHandlerStart()\n\t\t{\n\t\t\tif(process.stdout.isTTY)\n\t\t\t{\n\t\t\t\tkeypress(process.stdin);\n\t\t\t\tprocess.stdin.on('keypress', this._keypressHandler);\n\t\t\t\tprocess.stdin.setRawMode(true);\n\t\t\t\tprocess.stdin.resume();\n\t\t\t}\n\t\t}", "config() {\n this.app.set('port', process.env.PORT || 3000); // si hay port set toma ese, si no va al 3000\n this.app.use(morgan_1.default('dev'));\n this.app.use(cors_1.default());\n this.app.use(express_1.default.json()); // met para poder aceptar json de apps clientes (antes body parser)\n this.app.use(express_1.default.urlencoded({ extended: false })); // por si queremos enviar desde html form \n }" ]
[ "0.6300785", "0.6186253", "0.6150104", "0.61436576", "0.6127923", "0.60946846", "0.6089851", "0.60636204", "0.60511065", "0.60152376", "0.5985307", "0.5980225", "0.5950251", "0.5947655", "0.5933516", "0.593279", "0.5930175", "0.59157693", "0.59107006", "0.5880162", "0.5877274", "0.5829835", "0.5796189", "0.5794758", "0.57475644", "0.5730898", "0.5725734", "0.5711333", "0.5709189", "0.5702836", "0.5687491", "0.5680113", "0.5664865", "0.56438905", "0.5634882", "0.5629082", "0.56215394", "0.5569814", "0.55660236", "0.55599564", "0.5533542", "0.55242825", "0.552066", "0.5514585", "0.549095", "0.5489992", "0.548933", "0.54852015", "0.5483764", "0.54593533", "0.5445116", "0.5444931", "0.54332995", "0.5431479", "0.5427599", "0.5416333", "0.5409295", "0.540539", "0.5404171", "0.5390888", "0.5385405", "0.5384796", "0.53704035", "0.53692263", "0.536784", "0.5335438", "0.5335424", "0.5309084", "0.5301385", "0.5296491", "0.5287757", "0.5287569", "0.5277453", "0.5275189", "0.52737874", "0.5271347", "0.5263283", "0.5261853", "0.52491874", "0.5226742", "0.5214685", "0.5206301", "0.5204036", "0.51945436", "0.5192198", "0.5190028", "0.5185207", "0.51851416", "0.51849324", "0.51811755", "0.5180389", "0.517799", "0.51672477", "0.51666075", "0.5160495", "0.5159643", "0.515567", "0.5147309", "0.5143558", "0.5142997" ]
0.67672527
0
get_List() is used to Display the entire users list Input : A reference to the response object Output: A json object which contains userdetails is sent as response
function get_List(request,response) { // If the session is not active then // Send the api-status as false // and set msg as'login_error' if(!(request.session.userName)) { var responseToSend={}; responseToSend.apiStatus=false; responseToSend.msg='login_error'; // Append the same to the log file fs.appendFile('log',"\nAPI:get_List\nOUTPUT:\n" ,function() { fs.appendFile('log',"response:"+JSON.stringify(responseToSend)+"\n------------------------------------------------------------------------------",function(){console.log("OUTPUT from get_List Written to log file"); // Send the response to the server response.send(responseToSend);}); }); } else { // Data before sending to the server fs.appendFile('log',"\n URL :/get_List - API NAME :get_List METHOD TYPE : GET" ,function() { // Once the API's details are logged now append the input and output information for the same file fs.appendFile('log',"\nINPUT:\n" ,function() { fs.appendFile('log',"request.session.userName:"+request.session.userName,function() { // Connect to the DB and extract all the details of logged-in users connection.query('select * from project.customer WHERE mobilenumber='+connection.escape(request.session.userName) ,function(err, rows,result) { if(err) { // Send 0 if unable to connect response.send(new Boolean(0)); response.end(); } else { // If there is no error in connecting to DB // create a json object of the result and // send the same as response var row=rows[0]; // Once the API's details are logged now append the input and output information for the same file fs.appendFile('log',"\nOUTPUT:\n" ,function() { fs.appendFile('log',"response:"+JSON.stringify(row)+"\n------------------------------------------------------------------------------",function(){console.log("OUTPUT from get_List Written to log file");}); }); response.send(row); } }); }); }); }); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getList(){\n\t\t// call ajax\n\t\tlet url = 'https://final-project-sekyunoh.herokuapp.com/get-user';\n\t\tfetch(url)\n\t\t.then(checkStatus)\n\t\t.then(function(responseText) {\n\t\t\tlet res = JSON.parse(responseText);\n\t\t\tlet people = res['people'];\n\t\t\tdisplayList(people);\n\t\t})\n\t\t.catch(function(error) {\n\t\t\t// show error\n\t\t\tdisplayError(error + ' while getting list');\n\t\t});\n\t}", "getUserList(data){\nreturn this.post(Config.API_URL + Constant.USER_GETUSERLIST, data);\n}", "function getUserList() {\n \n return userList;\n }", "static async list(req, res) {\n try {\n const users = await UserService.list();\n res.status(200).send({ success: true, data: users });\n } catch (err) {\n res.status(500).send(errorResponse);\n }\n }", "function getUsers(){\n\t\t\tgetUsersService.getUserList().then(function(data){\n\t\t\t\tlc.listOfUser = data;\n\t\t\t})\n\t\t\t.catch(function(message){\n\t\t\t\texception.catcher('getUserList Service cannot succeed')(message);\n\t\t\t});\n\t\t}", "function fetch() {\n $scope.isLoading = true;\n $http.post(url+'/api/user/getUserList', {\n // skip: $scope.searchParams.begin,\n skip: $scope.searchParams.limit,\n page: $scope.searchParams.pageNum - 1\n })\n .success(function (data) {\n $scope.isLoading = false;\n console.log('fetch userList from server success:', data);\n $scope.data_store = data.instances.list;\n $scope.userList = $scope.data_store;\n $scope.searchParams.total = data.instances.pageNum;\n\n })\n .error(function (data) {\n $scope.isLoading = false;\n alert('Internal server error');\n console.log('got error:', data);\n });\n }", "function listOfUsers() {\n request.get('https://slack.com/api/users.list?token='+\n process.env.Apptoken+'&pretty=1',function (err,requ,response)\n {\n var data= JSON.parse(response);\n usersLists=data.members;\n });//end of get users.list function\n}", "function listUsers() {\n gapi.client.directory.users.list({\n 'customer': 'my_customer',\n 'maxResults': 100,\n 'orderBy': 'email',\n 'viewType': \"domain_public\"\n }).then(function(response) {\n var users = response.result.users;\n var menu = document.getElementById('menu-main');\n menu.className += \" show-toggle\";\n //appendPre('Directory Loaded, you may now Show Directory <a href=\"link\"> test </a>');\n if (users && users.length > 0) {\n for (i = 0; i < users.length; i++) {\n //console.log(user);\n var user = users[i];\n userlist.push(user)\n /*appendPre('-' + user.primaryEmail + ' (' + user.name.fullName + ')');\n if (user.organizations){\n appendPre(user.organizations[0].title);\n };\n if (user.thumbnailPhotoUrl){\n appendPre(user.thumbnailPhotoUrl)\n }*/\n }\n } else {\n appendPre('No users found.');\n }\n });\n }", "async function listUsers() {\r\n let res = await request\r\n .get(reqURL(config.routes.user.list))\r\n .withCredentials()\r\n .set(\"Content-Type\", \"application/json\")\r\n .set(\"Accept\", \"application/json\")\r\n .auth(\"team\", \"DHKHJ98N-UHG9-K09J-7YHD-8Q7LK98DHGS7\");\r\n log(`listUsers:${util.inspect(res.body)}`);\r\n return res.body\r\n}", "function listUsers() {\n $listUsers.empty();\n\n if (event) event.preventDefault();\n\n var token = localStorage.getItem('token');\n $.ajax({\n url: '/users',\n method: 'GET',\n beforeSend: function beforeSend(jqXHR) {\n if (token) return jqXHR.setRequestHeader('Authorization', 'Bearer ' + token);\n }\n }).done(function (users) {\n showUsers(users, 0, 10);\n });\n }", "function getUserList(uid, data) {\n return new Promise((resolve, reject) => {\n adminWebModel.getUserList(data).then((result) => {\n if (result) {\n let token = jwt.sign({ uid: uid }, key.JWT_SECRET_KEY, {\n expiresIn: timer.TOKEN_EXPIRATION\n })\n \n resolve({ code: code.OK, message: '', data: { 'token': token, 'totalpage': Math.ceil(result.count / Number(data.row_count)), 'userlist': result.rows } })\n }\n }).catch((err) => {\n if (err.message === message.INTERNAL_SERVER_ERROR)\n reject({ code: code.INTERNAL_SERVER_ERROR, message: err.message, data: {} })\n else\n reject({ code: code.BAD_REQUEST, message: err.message, data: {} })\n })\n })\n }", "function GetUserList() {\r\n\t\treturn $.ajax({\r\n\t\t\turl: '/api/usuarios/listar',\r\n\t\t\ttype: 'get',\r\n\t\t\tdataType: \"script\",\r\n\t\t\tdata: { authorization: localStorage.token },\r\n\t\t\tsuccess: function(response) {\r\n\t\t\t\tconst usuarios = JSON.parse(response);\r\n\t\t\t\t//console.log(usuarios); //<-aqui hago un console para ver lo que devuelve\r\n\t\t\t\tusuarios.forEach(user => {\r\n\t\t\t\t\ttablaUsuarios.row.add({\r\n\t\t\t\t\t\t\"cedulaUsuario\": user.cedulaUsuario,\r\n\t\t\t\t\t\t\"nombreCUsuario\": user.nombreCUsuario,\r\n\t\t\t\t\t\t\"emailUsuario\": user.emailUsuario,\r\n\t\t\t\t\t\t\"nickUsuario\": user.nickUsuario,\r\n\t\t\t\t\t}).draw();\r\n\t\t\t\t});\r\n\r\n\t\t\t}\r\n\t\t});\r\n\t}", "function GenerateUserNameList() {\n $http.get(config.baseUrlApi + 'HMLVTS/GenerateUserNameList')\n\n .then(function (response) {\n console.log(\"GenerateUserNameList\", response);\n createSelect(response.data.result, 'username');\n });\n }", "function getUsers() {\n\tvar apiurl = ENTRYPOINT;\n\treturn $.ajax({\n\t\turl: apiurl,\n\t\tdataType:DEFAULT_DATATYPE\n\t}).always(function(){\n\t\t//Remove old list of users, clear the form data hide the content information(no selected)\n\t\t$(\"#user_list\").empty();\n\t\t$(\"#mainContent\").hide();\n\n\t}).done(function (data, textStatus, jqXHR){\n\t\tif (DEBUG) {\n\t\t\tconsole.log (\"RECEIVED RESPONSE: data:\",data,\"; textStatus:\",textStatus)\n\t\t}\n\t\t//Extract the users\n \tvar users = data.collection.items;\n\t\tfor (var i=0; i < users.length; i++){\n\t\t\tvar user = users[i];\n\t\t\t//Extract the nickname by getting the data values. Once obtained\n\t\t\t// the nickname use the method appendUserToList to show the user\n\t\t\t// information in the UI.\n\t\t\t//Data format example:\n\t\t\t// [ { \"name\" : \"nickname\", \"value\" : \"Mystery\" },\n\t\t\t// { \"name\" : \"registrationdate\", \"value\" : \"2014-10-12\" } ]\n\t\t\tvar user_data = user.data;\n\t\t\tfor (var j=0; j<user_data.length;j++){\n\t\t\t\tif (user_data[j].name==\"nickname\"){\n\t\t\t\t\tappendUserToList(user.href, user_data[j].value);\n\t\t\t\t}\t\t\t\n\t\t\t} \n\t\t}\n\t\t//Set the href of #addUser for creating a new user\n\t\tsetNewUserUrl(data.collection.href)\n\t}).fail(function (jqXHR, textStatus, errorThrown){\n\t\tif (DEBUG) {\n\t\t\tconsole.log (\"RECEIVED ERROR: textStatus:\",textStatus, \";error:\",errorThrown)\n\t\t}\n\t\t//Inform user about the error using an alert message.\n\t\talert (\"Could not fetch the list of users. Please, try again\");\n\t});\n}", "list(req, res) {\n\n return User\n .findAll({})\n .then(users => res.status(200).send(users))\n .catch(error => res.status(400).send(error));\n }", "function getUserList() {\n userService.getUsers()\n .then(function (users) {\n var result = users.filter(function (u) {\n return u.Id !== vm.current.details.ownerId;\n });\n vm.ownerForm.users = result;\n });\n }", "async function getList(ctx) {\n console.log('user get list');\n const ret = [\n {name: 'zhangsan'},\n {name: 'lisi'},\n {name: 'wangwu'},\n ];\n\n // const users = await dao.getList();\n\n ctx.body = new Success(ret);\n\n // ctx.body = {\n // code: 500,\n // message: 'db error'\n // };\n}", "function getUsers(data){\n users = JSON.parse(data).results;\n renderUsers();\n}", "async function getUsers() {\n const response = await api.get(`/users/?_sort=id&_order=desc`);\n\n if (response.data) {\n setCompletedListUsers(response.data);\n setListUsers(response.data);\n refreshCountPages(response.data);\n }\n }", "function usersListRefresh()\n{ \n\t$.ajax({ url:\"http://localhost/tchat/API/index.php?action=listUsers\",\n\t\t\ttype:\"GET\"\n\t \n\t\t}).done(function(response)\n\t{\n\t\t//console.log(response);\n $('#userList ul').empty();\n\t\tfor (var i = 0; i < response.length; i++) \n\t\t{\n\t\t\t//console.log(i);\n\t\t\t$('#userList ul').append('<li>' + response[i].userNickname + '</li>');\n\t\t}\t\n\t});\t\n}", "function listUsers() {\n $scope.isDataUserReady = false;\n $http({\n method: 'GET',\n url: baseUrl + 'admin/user_bank/list',\n data: {},\n headers: { 'Authorization': 'Bearer ' + localStorage.getItem('jeton') }\n }).then(function successCallback(response) {\n $scope.bankUsers = response.data.bank_list;\n $scope.isDataUserReady = true;\n // //console.log(\"$scope.bankUsers \",$scope.bankUsers);\n }).catch(function(err) {\n if (err.status == 500 && localStorage.getItem('jeton') != '' && localStorage.getItem('jeton') != null && localStorage.getItem('jeton') != undefined) {\n deconnectApi.logout(sessionStorage.getItem(\"iduser\")).then(function(response) {\n $location.url('/access/login');\n $state.go('access.login');\n }).catch(function(response) {});\n };\n });\n }", "function getAllUsers(){\n //Request all user\n $.ajax({\n method: \"GET\",\n url: SERVER_URL+getUserURL(),\n data:{\"sort\":sortedBy,\n \"items_per_page\":USER_PER_PAGE,\n \"page\":currentPage,\n \"queryType\":searchType,\n \"query\":searchQuery},\n headers: {\"Authorization\": \"Bearer \" + Cookies.get(\"token\")}\n })\n .done(function( msg ) {\n //Check if not error\n if(typeof msg.error != \"undefined\"){\n //Error\n alert(\"Gagal : \" + msg.error.text);\n }else {\n //Berhasil\n\n //Empty the list\n $(\"#userList\").empty();\n var isiList = \"\";\n\n pageCount = Math. ceil(msg.total / USER_PER_PAGE)\n\n $.each(msg.data,function(index, value){\n isiList += `<span onclick=\"getUserData('`+ value.id +`');\" id=\"user-`+value.id+`\"\n class=\"list-group-item list-group-item-action\">` + value.name + `</span>`;\n });\n\n //Append to location\n $(\"#userList\").append(isiList);\n\n //check apakah ada yang sudah diselect\n if(argsId!=\"\"){\n if(!isNaN(argsId)){\n getUserData(argsId);\n }\n }\n }\n\n }).fail(function( jqXHR, textStatus ) {\n //Error dalam pengiriman\n alert( \"Connection or server failure: \" + textStatus + \" / \" + jqXHR.statusText );\n });\n}", "function _getUsers() {\n // var usersList = JSON.parse(localStorage.getItem('lsUsersList'));\n // if (usersList == null) {\n // usersList = users; //Lista de jugadores quemados\n // }\n // return usersList;\n return $http.get('http://localhost:3000/api/get_all_users');\n }", "function listUsers(){\r\n\t$('#listUsers').html('');\r\n\t$('#loadMaskDiv').mask('Loading...');\r\n\t $.ajax({\r\n \t\ttype: \"get\",\r\n \t\turl: \"../userManagement/list.htm\",\r\n dataType: \"json\",\r\n \t\tsuccess: function(response){\r\n \t\t\tvar tempHtml = listUsersResponse(response);\t\r\n \t\t\t$('#listUsers').append(tempHtml);\r\n \t\t\t$('#listUsersTable').dataTable({ responsive: true});\r\n \t\t\t$('#loadMaskDiv').unmask();\r\n \t\t\treturn false;\r\n\t \t},\r\n error: function(response){\r\n \t$('#loadMask').mask(response.status+\",\"+response.statusText);\r\n \treturn false;\r\n }\r\n });\r\n}", "function userlist() {\r\n console.log('Inside factory now');\r\n var deferred = $q.defer();\r\n\r\n $http.get(userUrl + '/user/list')\r\n .then (\r\n function(response) {\r\n deferred.resolve(response.data);\r\n },\r\n function(errResponse) {\r\n deferred.reject(errResponse);\r\n }\r\n );\r\n return deferred.promise;\r\n }", "list(req, res) {\n this.__readData(__data_source)\n .then(lists => {\n \n \n res.json({ type: \"success\", data: this.__formatter(lists) });\n })\n .catch(err => res.status(412).json({type:\"error\", data:[], message:\"No Data Found\"}));\n }", "function getUserList(){\r\n var userListforGet = [];\r\n for(var i=0;i<chatAppUsers.length;i++){\r\n userListforGet.push(chatAppUsers[i].currentUser);\r\n }\r\n return userListforGet;\r\n}", "function GetUsers() {\n UserApi.getUser().then(function (response) {\n $scope.user = response.data;\n }), function () {\n aler(\"Unable to load users info\");\n }\n }", "queryLists() {\n fetch(\"https://deco3801-oblong.uqcloud.net/wanderlist/get_bucketlist_belonging_to_user/\" + this.state.userData.id)\n .then(response => response.json())\n .then(obj => this.loadLists(obj));\n }", "function userDirectoryList_Handler() {\n $.ajax({\n type: 'GET',\n contentType: 'application/json',\n url: '/users',\n success: function(response) {\n var listUsers = response;\n populateuserdata(response);\n var results = document.getElementById(\"userlist\");\n var lastStatusCode = \"\";\n if (results != null) {\n for (var i = 0; i < listUsers.length; i++) {\n\n results.innerHTML += '<p class=\"media-body pb-3 mb-0 small lh-125 border-bottom border-gray\"> <strong class=\"d-block text-gray-dark class=\"media-body pb-3 mb-0 small lh-125 border-bottom border-gray\" ><img src=\"../images/user-holder.png\" class=\"mr-2 rounded\"><span onclick=\"javascript:getChatPrivate(' + i + ');\" id=\"' + listUsers[i].username + '\"> ' + listUsers[i].username + '</span> <span class=\"label label-success\" style=\"color:#blue\">' + listUsers[i].onlineStatus + ' </span><span class=\"label label-primary\">' + listUsers[i].lastStatusCode + ' </span></strong></p>';\n }\n }\n }\n });\n}", "function listUsers(req, res) {\n if (req == null || req.query == null) {\n return utils.res(res, 400, 'Bad Request');\n }\n\n if (req.user_id == null) {\n return utils.res(res, 401, 'Invalid Token');\n }\n\n try {\n // Pagination\n const range = JSON.parse(req.query.range);\n const r0 = range[0], r1 = range[1] + 1;\n\n // Sort\n const sorting = JSON.parse(req.query.sort);\n const sortPara = sorting[0];\n const sortOrder = sorting[1];\n\n // Filter\n const filter = JSON.parse(req.query.filter);\n } catch (err) {\n return utils.res(res, 400, 'Please provide appropriate range, sort & filter arguments');\n }\n\n\n let qFilter = JSON.parse(req.query.filter);\n let filter = {};\n if (!(qFilter.user_id == null) && typeof (qFilter.user_id) === 'string') filter['user_id'] = { $regex: qFilter.user_id, $options: 'i' };\n\n // Fetch User lists\n models.User.find(filter, 'user_id name email age university total_coins cyber_IQ role')\n .lean()\n .exec(function (err, users) {\n if (err) {\n return utils.res(res, 500, 'Internal Server Error');\n }\n\n if (users == null) {\n return utils.res(res, 404, 'Users do not Exist');\n }\n users.map(u => {\n u['id'] = u['user_id'];\n delete u['user_id'];\n delete u['_id'];\n if (!u['university']) {\n u['university'] = 'NA';\n }\n return u;\n });\n\n // Pagination\n const range = JSON.parse(req.query.range);\n const len = users.length;\n const response = users.slice(range[0], range[1] + 1);\n const contentRange = 'users ' + range[0] + '-' + range[1] + '/' + len;\n\n // Sort\n const sorting = JSON.parse(req.query.sort);\n let sortPara = sorting[0] || 'name';\n let sortOrder = sorting[1] || 'ASC';\n if (sortOrder !== 'ASC' && sortOrder != 'DESC') sortOrder = 'ASC';\n\n res.set({\n 'Access-Control-Expose-Headers': 'Content-Range',\n 'Content-Range': contentRange\n });\n return utils.res(res, 200, 'Retrieval Successful', utils.sortObjects(response, sortPara, sortOrder));\n })\n}", "function getAllUsers() {\n\t\t// url (required), options (optional)\n\t\t/*\n\t\tfetch('/snippets/all') // Call the fetch function passing the url of the API as a parameter\n\t\t.then(function(resp) {\n\t\t\treturn resp.json()\n\t\t}) // Transform the data into json\n\t\t.then(function(data) {\n\t\t\tconsole.log(JSON.parse(data));\n\t\t\t// Your code for handling the data you get from the API\n\t\t\t//_bindTemplate(\"#entry-template\", data, '#sample-data');\n\t\t})\n\t\t.catch(function(errors) {\n\t\t\t// This is where you run code if the server returns any errors\n\t\t\tconsole.log(errors);\n\t\t});\n\t\t*/\n\n\t\t$.ajax({\n\t\t\ttype: 'GET', \t\t// define the type of HTTP verb we want to use (POST for our form)\n\t\t\turl: '/users/all', \t// the url where we want to POST\n\t\t\tdataType: 'json', \t// what type of data do we expect back from the server\n\t\t\tencode: true\n\t\t})\n\t\t// using the done promise callback\n\t\t.done(function(data) {\n\t\t\t_bindTemplate(\"#entry-template\", data, '#sample-data');\n\t\t});\n\t}", "list (req, res) {\n const data = this._getTodoData(req.user.username)\n\n res.json(data.items)\n }", "function adminViewUserList(url){\n var method = \"GET\";\n var httpRequest = createHttpRequest(method, url);\n\n httpRequest.onreadystatechange = function(){\n if (httpRequest.readyState == 4 && httpRequest.status == 200) {\n var httpResponse = JSON.parse(httpRequest.response);\n var userViewSelect = document.getElementById(\"userViewSelect\");\n\n // Remove old entries, if any\n var length = userViewSelect.options.length;\n for (i = 0; i < length; i++) {\n userViewSelect.options[0] = null;\n }\n // Create default entry\n var defaultOption = document.createElement('option');\n defaultOption.text = \"Select the Resource\";\n defaultOption.disabled = true;\n defaultOption.selected = true;\n userViewSelect.appendChild(defaultOption);\n\n // Create other entries based on data\n outerloop:\n for (var key in httpResponse) {\n innerloop:\n for (var subkey in httpResponse[key]) {\n var options = document.createElement('option');\n if (subkey == \"firstName\") {\n options.value = httpResponse[key]['id'];\n options.innerHTML = httpResponse[key][subkey];\n userViewSelect.appendChild(options);\n break innerloop;\n }\n }\n }\n\n }\n }\n httpRequest.onerror = onError;\n sendHttpRequest(httpRequest, method, url, \"application/json\", null);\n}", "function getUserNames() {\n $.get(\"/api/userNames\", function(data) {\n var rowsToAdd = [];\n for (var i = 0; i < data.length; i++) {\n rowsToAdd.push(createUserNameRow(data[i]));\n }\n renderUserNameList(rowsToAdd);\n nameInput.val(\"\");\n });\n }", "function List(req, res) {\n let userId = req.params.userId;\n UsersModel.findById(userId, (err, user) => {\n if (err) {\n return res.status(422).json({\n 'status': false,\n 'message': 'An Error Occured'\n })\n }\n return res.status(200).send(user)\n })\n}", "function fetchUsersList() {\r\n // var url = \"usersList?teamName=\" + $scope.teamName;\r\n var url = \"usersList?teamName=\" + $scope.teamName;\r\n httpServerService.makeHttpRequest(url, \"get\")\r\n .then(function(response) {\r\n if (response.status == 200) {\r\n console.log(\"users list loaded\" + response.data);\r\n var usersData = response.data;\r\n $scope.users = usersData.users;\r\n $scope.managers = usersData.managers;\r\n\r\n var userEmail = usersService.getUserObject().email;\r\n\r\n var users = $scope.users;\r\n // set the flag for the label style of the teamrole\r\n for (var i = 0; i < users.length; i++) {\r\n if (users[i].teamrole == \"Manager\") {\r\n users[i].label = \"label-success\";\r\n } else if (users[i].teamrole == \"Reviewer\") {\r\n users[i].label = \"label-info\";\r\n } else if (users[i].teamrole == \"User\") {\r\n users[i].label = \"label-default\";\r\n } else if (users[i].teamrole == \"A\") {\r\n users[i].label = \"label-primary\";\r\n } else {\r\n users[i].label = \"label-Warning\";\r\n }\r\n\r\n if (users[i].email == userEmail) {\r\n users[i].disableDelete = true;\r\n };\r\n\r\n if (users.length == 0) {\r\n $scope.noRecords = true;\r\n $scope.noRecordsText = \"No users found\";\r\n } else {\r\n $scope.noRecords = false;\r\n $scope.noRecordsText = \"\";\r\n }\r\n }\r\n } else {\r\n $scope.showErrorMsg = true;\r\n $scope.errorMsg = \"cannot fetch users list\";\r\n }\r\n })\r\n }", "function userList(req, res) {\n const obj = {};\n\n if (req.body.filterData && req.body.filterData.favourites && req.body.filterData.favourites === true) {\n obj.is_favourite = req.body.filterData.favourites;\n }\n if (req.body.filterData && req.body.filterData.divisions && req.body.filterData.divisions !== \"ALL\" && req.body.filterData.divisions !== \"\") {\n obj.division_id = req.body.filterData.divisions;\n }\n if (req.body.filterData && req.body.filterData.groups && req.body.filterData.groups !== \"ALL\" && req.body.filterData.groups !== \"\") {\n obj.group = req.body.filterData.groups;\n }\n if (req.body.filterData && req.body.filterData.groups && req.body.filterData.startswith !== \"ALL\" && req.body.filterData.startswith !== \"\") {\n obj.name = new RegExp(`^${req.body.filterData.startswith}`, \"i\");\n }\n let skipdata = 0;\n let limitdata = 0;\n if (req.body.filterData.skip && req.body.filterData.skip !== null && parseInt(req.body.filterData.skip) > 0) {\n skipdata = req.body.filterData.skip;\n }\n if (req.body.filterData.limit && req.body.filterData.limit !== null && parseInt(req.body.filterData.limit) > 0) {\n limitdata = req.body.filterData.limit;\n }\n\n const select = \"placeofSupply status_inward status_outward name normalized_name mobile_no is_favourite email_id\";\n\n CustomerModel.find(obj, select).sort({normalized_name: \"asc\"}).skip(skipdata).limit(limitdata)\n .exec((err, data) => {\n if (err) {\n res.status(499).send({message: errorhelper.getErrorMessage(err)});\n } else {\n res.json(data);\n }\n });\n}", "function getPersonList() {\n\n personListLogic.getpersonListDetails().then(function (response) {\n appLogger.log(response);\n $scope.personList = response;\n\n }, function (err) {\n appLogger.log(err);\n appLogger.error('ERR' + err);\n\n });\n\n\n }", "async listUsers(req, res, next) {\n try {\n const users = await UsersService.listUsers();\n res.status(HTTPStatus.OK);\n res.json(users);\n } catch (error) {\n next(extendError(error, { task: 'Controller/listUsers' }));\n }\n }", "function getUsers(event) {\n\n if ( document.getElementById('former') !== null ) {\n clearFields();\n }\n \n //Get Users\n http.get('https://jsonplaceholder.typicode.com/users', function (error, users) {\n if (error) {\n console.log(error)\n } else {\n console.log(users);\n users = JSON.parse(users);\n let output = '';\n users.forEach(user => {\n output += `\n <div class=\"card card-body mb-2\">\n <h5>Name : ${user.name}</h4>\n <p>Id : ${user.id}</p>\n <p>Website : ${user.website}</p>\n <h6> Company: </h6>\n <ul>\n <li>Name : ${user.company.name}</li>\n <li>Catchphrase : ${user.company.catchPhrase}</li>\n </ul>\n </div>\n `;\n });\n document.getElementById('output').innerHTML = output;\n }\n });\n event.preventDefault();\n\n}", "getUserList() {\n return this.http.get(this.url + '/cesco/getlanguages', this.httpOptions);\n }", "async function getUserList() {\n\n // Connection properties\n var options = {\n method: 'GET',\n uri: conf.API_PATH + `5808862710000087232b75ac`,\n json: true\n };\n\n return (await request(options)).clients;\n}", "function getUsers() {\r\n console.log(\"getUsers called...\");\r\n doAjaxCall(`${apiURL}/users`,'GET'); \r\n\r\n}", "function pullUserData(){\n var xmlHttp = null;\n xmlHttp = new XMLHttpRequest();\n xmlHttp.onreadystatechange = function() {\n if (xmlHttp.responseText && xmlHttp.status == 200 && xmlHttp.readyState == 4) {\n var obj = jQuery.parseJSON( xmlHttp.responseText );\n $.each(obj, function() {\n FirstName[FirstName.length] = this['firstName'];\n LastName[LastName.length] = this['lastName'];\n if(h[this['_id']] != null){\n ID[ID.length] = h[this['_id']];\n }else{\n ID[ID.length] = \"Not Found\";\n }\n \n });\n }\n };\n xmlHttp.open(\"GET\", \"https://mydesigncompany.herokuapp.com/users\", true);\n //xmlHttp.open(\"GET\", \"https://infinite-stream-2919.herokuapp.com/users\", true);\n xmlHttp.send(null);\n }", "function userRequest() {\n $.getJSON('/users/userlist', function (data) {\n\n // For each item in our JSON, do something like render some HTML to the DOM\n $.each(data, function () {\n // mock up some html\n });\n });\n}", "getAllUsers() {\n return Api.get(\"/admin/user-list\");\n }", "function getList() {\n vm.loading = true;\n\n api.send({x: 'x', y: 'y'});\n\n api.response(function (message) {\n var data = JSON.parse(message.data);\n vm.loading = false;\n\n vm.list = {\n data: data,\n error: undefined\n };\n });\n }", "function _list() {\n document.getElementById('result').innerHTML = ''; \n document.getElementById('data').innerHTML = ''; \n if (_logged && ifConnected) {\n document.getElementById('result').innerHTML = ''; \n document.getElementById('data').innerHTML = ''; \n request = getRequestObject() ;\n request.onreadystatechange = function() {\n if (request.readyState == 4) {\n objJSON = JSON.parse(request.response);\n var txt = \"<table class='table' style='margin-left: auto;margin-right: auto;width: 30%;'>\";\n txt += \"<thead><tr>\";\n txt += \"<th scope='col'>#</th>\";\n txt += \"<th scope='col'>id</th>\";\n txt += \"<th scope='col'>login</th>\";\n txt += \"<th scope='col'>password</th>\";\n txt += \"</tr></thead>\";\n txt += \"<tbody>\";\n for ( var id in objJSON ) {\n txt += \"<tr>\";\n txt += \"<td>\" + id + \"</td>\";\n for ( var prop in objJSON[id] ) { \n if ( prop !== '_id')\n { \n txt += \"<td>\" + objJSON[id][prop] + \"</td>\";\n }\n else\n { \n txt += \"<td>\" + objJSON[id][prop]['$oid'] + \"</td>\";\n } \n }\n txt += \"</tr>\";\n }\n txt += \"</tbody>\";\n txt += \"</table>\";\n document.getElementById('result').innerHTML = txt;\n }\n }\n request.open(\"GET\", \"http://pascal.fis.agh.edu.pl/~8goral/projekt2/rest/list\", true);\n request.send(null);\n } else {\n document.getElementById('data').innerHTML = \"<h1 class='display-4 text-center' style='margin-left: auto;margin-right: auto;width: 40%;'>To reach this option you first need to be logged as a user!</h1>\";; \n }\n \n}", "function getAllUsers(){\n $.get(\"/getAllUsers\", function(users){\n let output =\n \"<table class='table table-striped table-bordered'>\" +\n \"<tr>\" +\n \"<th>Username</th>\" +\n \"</tr>\";\n\n for (const user of users){\n output +=\n \"<tr>\" +\n \"<td>\" + user.username + \"</td>\" +\n \"</tr>\";\n }\n output += \"</table>\";\n $(\"#allUsers\").empty().html(output);\n });\n }", "static getUsers() {\n const req = new Request('/api/users/', {\n method : 'GET',\n headers : this.requestHeaders()\n });\n return fetch(req).then(res => this.parseResponse(res))\n .catch(err => {\n throw err;\n });\n }", "async function getUserObject() {\n\n let users = await fetch(\"/userendpoint\");\n let userObject = await users.json();\n\n await getUserNameList(userObject)\n }", "async getUserList(number) {\n try {\n const result = await this.axiosInstance.get(\n `/users?limit=${number}&offset=0`\n );\n return result;\n } catch (err) {\n helpMeInstructor(err);\n return err;\n }\n }", "function listUsers (req, res) {\n promiseResponse(userStore.find({}), res);\n}", "function listUsers(api, query) {\n return api_1.GET(api, '/users', { query })\n}", "function showAllUsers() {\r\n getUsers().then(function(result){\r\n users=[];\r\n for(var i=0;i<result.length;i++){\r\n let user = {\r\n id: result[i].ID,\r\n name:result[i].Name,\r\n currentCredit: result[i].Credit_amount,\r\n email: result[i].Email,\r\n address: \"\",\r\n phone: result[i].phone\r\n }\r\n users.push(user);\r\n \r\n }\r\n renderUsers();\r\n })\r\n}", "function retrieve_all_users(){\n\tlet params = {\n\t\t\t\t method: \"GET\",\n\t\t\t\t url: \"/api/admin/all/\"\n \t\t\t\t}\n\t$.ajax(params).done(function(data) {\n\t\tvar allUsers = '<div style=\"border:1px solid black\"><h3>All users</h3><table><tr><th>Username</th>'+\n\t\t'<th>First Name</th><th>Last Name</th><th>e-mail</th><th>Account Type</th><th>Last Login</th></tr>';\n\t\tconsole.log(data[\"users\"].length);\n\t\tfor(i=0;i<data[\"users\"].length;i++){\n\t\t\tallUsers += \"<tr><th>\"+data[\"users\"][i].username+\"</th><th>\"+\n\t\t\tdata[\"users\"][i].firstName+\"</th><th>\"+data[\"users\"][i].lastName+\n\t\t\t\"</th><th>\"+data[\"users\"][i].email+\"</th><th>\"+data[\"users\"][i].userType+\n\t\t\t\"</th><th>\"+data[\"users\"][i].lastLogin+\"</th></tr>\";\n\t\t}\n\t\tallUsers+= \"</table>\";\n\t\t$(\"#allUsers\").html(allUsers);\n\t});\n}", "function userList() {\n let jsonFileRead = fs.readFileSync(path.join(__dirname, '../data/users.json'), 'utf-8')\n return JSON.parse(jsonFileRead)\n}", "function outputUsers(users) {\n userList.innerHTML = '';\n users.forEach(user=>{\n const li = document.createElement('li');\n li.innerText = user.username;\n userList.appendChild(li);\n });\n }", "function outputUsers(users) {\n userList.innerHTML = '';\n users.forEach(user=>{\n const li = document.createElement('li');\n li.innerText = user.username;\n userList.appendChild(li);\n });\n }", "function outputUsers(users) {\n userList.innerHTML = '';\n users.forEach(user=>{\n const li = document.createElement('li');\n li.innerText = user.username;\n userList.appendChild(li);\n });\n }", "function getUsers(){\n fetch('users.json')\n .then((res) => res.json())\n .then((data) => {\n let output = `<h2 class=\"bb-4\">Users</h2>`;\n data.forEach((user) => {\n output += `\n <ul class=\"list-group mb-3\">\n <li class=\"list-group-item\">Id: ${user.id}</li>\n <li class=\"list-group-item\">Name: ${user.name}</li>\n <li class=\"list-group-item\">Email: ${user.email}</li>\n </ul>\n `;\n });\n document.getElementById('output').innerHTML = output;\n \n })\n .catch((err) => console.log(err));\n}", "function getUserList(trail){\n TrailClient\n .getUserList(trail)\n .then(function(response){\n if(!response.data.users){\n vm.alert = \"No users have favorited this trail yet!\";\n }\n else{\n vm.alert = null;\n vm.trail.userList = response.data.users;\n }\n })\n }", "function loadInfo() {\n var options = {};\n options.url = urlUser;\n options.type = \"GET\";\n options.dataType = \"json\";\n options.success = function (data) {\n $(\"#user-list\").empty();\n data.forEach(function (element) {\n var userInfo = \"<table><td><li>\" + element.id + \"-\" + element.name + \"</li></td>\";\n\n userInfo += \"<td>\";\n element.addresses.forEach(function (addr) {\n userInfo += \"<li>\"\n + addr.id\n + \"-\"\n + addr.name\n + \"-\"\n + addr.cityData.name\n + \"-\"\n + addr.cityData.stateData.name\n + \"-\"\n + addr.cityData.stateData.countryData.name\n + \"</li>\";\n });\n userInfo += \"</td>\";\n\n $(\"#user-list\").append(userInfo);\n });\n };\n options.error = function () {\n $(\"#msg\").html(\"Error while calling the Web API!\");\n };\n $.ajax(options);\n}", "function getUsers(request, response) {\n User.find({}, function(err, users) {\n if(err) {\n response.status(500).json({message: \"No users were found.\"});\n }\n if(!users) {\n response.status(404).json({message: \"No users were found.\"});\n }\n var userList = [];\n users.forEach(function(element) {\n userList.push({name: element.fullName, userId: element.userId});\n })\n\n response.status(200).send(userList);\n })\n}", "retrieveUsers() {\n\n this.__updateToken__()\n return fetch(`${this.url}/users`, {\n\n headers: {\n authorization: `Bearer ${this.__userToken__}`\n }\n })\n .then(response => response.json())\n .then(response => {\n if (response.error) throw Error(response.error)\n\n return response\n })\n }", "function getUserList(){\r\n var ret = [];\r\n for(var i=0;i<clients.length;i++){\r\n ret.push(clients[i].username);\r\n }\r\n return ret;\r\n}", "function outputUsers(users) {\r\n userList.innerHTML = '';\r\n users.forEach((user) => {\r\n const li = document.createElement('li');\r\n li.innerText = user.username;\r\n userList.appendChild(li);\r\n });\r\n}", "async getUsers() {\n let res = await fetch('/users', {credentials: 'include', headers: {'Content-Type': 'application/json'}})\n let v = await res.json()\n return v\n }", "fullList(req, res) {\n res.status(200).send(list);\n }", "list() {\n this._followRelService(\"list\", \"List\");\n }", "function getUsers () {\n\t$.ajax({\n\t\ttype: 'POST',\n\t\turl: 'Project',\n\t\tdata: {\n\t\t\t'domain': 'project',\n\t\t\t'action': 'getUsers',\n\t\t}, complete: function (data) {\n\t\t\tconsole.log(\"RESPONSE JSON FOR getUsers() = \",data.responseJSON);\n\t\t\tif (data.responseJSON) {\n\t\t\t\tusers = data.responseJSON;\n\t\t\t\tconsole.log(\"USERS = \",users);\n\t\t\t\tcreateDropdown(data.responseJSON);\n\t\t\t\tgetTasks();\n\t\t\t}\n\t\t}\n\t\t\n\t});\t\n}", "users() {\r\n\t\treturn API.get(\"pm\", \"/list-users\");\r\n\t}", "requestList() {\r\n fetch('https://localhost:44374/group/list')\r\n .then(response => response.json())\r\n .then(data => this.recievedList(data))\r\n }", "function getAllUsers(){\n \n\n return fetch(\"http://localhost:3000/users\")\n .then((resp) => resp.json())\n .then(function(users) {\n users.forEach(function(user) {\n \n postContainer.innerHTML += renderSingleProfile(user);\n }); \n\n return users \n } );\n \n}", "function outputUsers(users) {\n elim();\n let ul = document.createElement(\"ul\");\n ul.setAttribute(\"id\", \"users\");\n document.getElementById(\"list\").appendChild(ul);\n users.forEach(user=>{\n const li = document.createElement('li');\n li.className = 'list-group-item';\n li.innerText = user.username;\n ul.appendChild(li);\n });\n }", "userList() {\r\n const users= auth.users;\r\n return (\r\n <ol>\r\n {users.map(users => <li>{users}</li>)}\r\n </ol>\r\n );\r\n }", "function getGistUsers() {\n ListService\n .getListData()\n .then(function(response) {\n console.log('response: ', response);\n $scope.gists = response.data;\n $scope.totalItems = $scope.gists.length;\n }, function(error) {\n console.log(error);\n });\n }", "function getMembers() {\n $.get(\"/api/members\", renderMemberList);\n }", "function getMembers() {\n $.get(\"/api/members\", renderMemberList);\n }", "function getUsers() {\n let api = \"../api/Users\";\n\n ajaxCall(\"GET\", api, \"\", getUsersSuccessCB, getErrorCB);\n}", "function getUsernameList() {\r\n\tvar userlist = getUsernames();\r\n\treturn userlist;\r\n}", "function getAllUser(){\n return $http.get(url.user).then( handleSuccess, handleError );\n }", "function outputUsers(users) {\n userList.innerHTML = '';\n users.forEach((user) => {\n const li = document.createElement('li');\n li.innerText = user.username;\n userList.appendChild(li);\n });\n}", "function getUsers() {\n\n intakeTaskAgeDatalayer.getUsersInFirm()\n .then(function (response) {\n self.allUser = response.data;\n }, function (error) {\n notificationService.error('Users not loaded');\n });\n }", "static getAllUsers() {\n return fetch('https://dev-selfiegram.consumertrack.com/users').then(response => {\n return response.json();\n }).catch(error => {\n return error;\n });\n }", "async function getUser() {\r\n const response = await fetch('http://68.7.7.158:8181/api/v2?apikey=*************************&cmd=get_user_names');\r\n const json = await response.json();\r\n return json;\r\n}", "getUserList() {\n this.apiService.postDatawithoutToken('roleuserdata', {\n \"limit\": 30,\n \"skip\": 0\n })\n .subscribe(res => {\n let result = {};\n result = res;\n if (result.status == 'success') {\n this.musicianlist = result.data.musicians_data;\n for (let i of this.musicianlist) {\n this.isfriend[i._id] = 0;\n //this.friendCheck(item._id); //for checking if user already sent friendrequest or not\n }\n this.dancerlist = result.data.dancer_data;\n for (let i of this.dancerlist) {\n this.isfriend[i._id] = 0;\n //this.friendCheck(item._id); //for checking if user already sent friendrequest or not\n }\n this.modellist = result.data.model_data;\n for (let i of this.modellist) {\n this.isfriend[i._id] = 0;\n //this.friendCheck(item._id); //for checking if user already sent friendrequest or not\n }\n this.fanlist = result.data.fan_data;\n for (let i of this.fanlist) {\n this.isfriend[i._id] = 0;\n //this.friendCheck(item._id); //for checking if user already sent friendrequest or not\n }\n }\n });\n }", "getUsersList ({ state }, payload) {\n return new Promise((resolve, reject) => {\n io.get(`users/list`, payload, res => {\n resolve(res.data)\n }).catch(e => {\n reject(e)\n })\n })\n }", "static getUsers() {\n return API.fetcher(\"/user\");\n }", "function getAllUsersController(request, response) {\n const users = model.list()\n\n response.status(httpStatus.OK).json(users);\n}", "function getAllBD() {\r\n con.query(\"SELECT * FROM user\", function (err, result, fields) {\r\n if (err) throw err;\r\n console.log(\"Le retour JSON dans la function\", JSON.stringify(result))\r\n USER_LIST = result\r\n });\r\n\r\n}", "function getUsers(){\n return users;\n}", "function getUsers() {\n fetch(userUrl)\n .then((res) => res.json())\n .then((users) => {\n sortUsers(users);\n displayLeaderBoard();\n })\n .catch((error) => console.error(\"ERROR:\", error));\n }", "function javaGetAllUser(){\n return $http.get(url.javaUser).then( handleSuccess, handleError );\n }", "static async getUsers() {\n return await this.request('users/', 'get');\n }", "function getallusers() {\n\n\t}", "function getUsers() {\n\treturn fetch(userURL).then((resp) => resp.json())\n}", "function getUsers(users) {\n\tconst userList = JSON.parse(users);\n\tgetRepos(userList);\n\tdisplayUser(userList)\n}", "fetchAllUsers() {\n let account = JSON.parse(localStorage.getItem(\"cachedAccount\")).id;\n let url = (\"./admin/admin_getusers.php?allusers=\" + account);\n\n\t\t\tfetch(url)\n\t\t\t.then(res => res.json())\n\t\t\t.then(data => {\n\t\t\t\tthis.userList = data;\n\t\t\t})\n\t\t\t.catch((err) => console.error(err));\n }", "list(req, res) {\n studentDAO.getStudents(db)\n .then(students => {\n res.status(200).json(students)\n })\n .catch(err => {\n console.error(err)\n res.sendStatus(404)\n })\n }" ]
[ "0.82468927", "0.7713392", "0.7444244", "0.73564297", "0.7301959", "0.7292181", "0.7290893", "0.7246679", "0.72433275", "0.72378504", "0.7207516", "0.7146974", "0.709022", "0.70833784", "0.70727235", "0.70722336", "0.70362", "0.70357305", "0.702062", "0.7007316", "0.6979749", "0.69286615", "0.6915115", "0.691508", "0.68949884", "0.68942255", "0.6889454", "0.68755937", "0.68720955", "0.68302846", "0.6825359", "0.6816565", "0.6809114", "0.6794385", "0.6782643", "0.67813975", "0.6758847", "0.67446005", "0.6737369", "0.67372125", "0.67307425", "0.67233574", "0.67142075", "0.6712539", "0.66866827", "0.66746455", "0.665363", "0.664954", "0.6639757", "0.66337866", "0.6633085", "0.6630615", "0.6629277", "0.66261655", "0.6619722", "0.658784", "0.6582836", "0.6580599", "0.6579029", "0.6579029", "0.6579029", "0.65692466", "0.6564071", "0.65576386", "0.6555721", "0.65527153", "0.6545637", "0.65383375", "0.6538034", "0.6532741", "0.65293384", "0.65284795", "0.6523561", "0.65141684", "0.6513716", "0.6513316", "0.6504096", "0.65020055", "0.64927375", "0.64927375", "0.6479789", "0.6460064", "0.6459791", "0.64541477", "0.64427716", "0.64402133", "0.6439739", "0.6438574", "0.6435264", "0.6433674", "0.6419329", "0.6417158", "0.6415548", "0.6412798", "0.64057314", "0.6405701", "0.64047486", "0.63980806", "0.6390615", "0.63848746", "0.63841605" ]
0.0
-1
[END apps_script_slides_image_add_image] [START apps_script_slides_image_main] Adds images to a slides presentation.
function main() { var images = [ 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png', 'http://www.google.com/services/images/phone-animation-results_2x.png', 'http://www.google.com/services/images/section-work-card-img_2x.jpg', 'http://gsuite.google.com/img/icons/product-lockup.png', 'http://gsuite.google.com/img/home-hero_2x.jpg' ]; var [title, subtitle] = deck.getSlides()[0].getPageElements(); title.asShape().getText().setText(NAME); subtitle.asShape().getText().setText('Google Apps Script\nSlides Service demo'); images.forEach(addImageSlide); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function addRemainingImageSlides(imageArray) {\n imageArray.forEach(src => {\n const img = `<img src=\"${src}\" alt=\"Photo from the 2021 KCC Foundation scholarship reception\">`;\n // Insert additional slides into both slider-instances\n $('#galleryTrack').slick('slickAdd', img); // The `...slick('slickAdd')` method takes a string of HTML as 2nd arg\n $('#galleryNav').slick('slickAdd', img);\n });\n}", "function main() {\n var images = [\n 'http://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png',\n 'http://www.google.com/services/images/phone-animation-results_2x.png',\n 'http://www.google.com/services/images/section-work-card-img_2x.jpg',\n 'http://gsuite.google.com/img/icons/product-lockup.png',\n 'http://gsuite.google.com/img/home-hero_2x.jpg'\n ];\n var [title, subtitle] = presentation.getSlides()[0].getPageElements();\n title.asShape().getText().setText(NAME);\n subtitle.asShape().getText().setText('Google Apps Script\\nSlides Service demo');\n images.forEach(addImageSlide);\n}", "function addImage() {\n myPresentation.getCurrentSlide().addImage(inTxt.value);\n inTxt.value = \"\";\n}", "function addImage(image) {\n\t\t\tif (typeof image !== \"undefined\") {\n\t\t\t\timagesList.push(image);\n\t\t\t}\n\t\t}", "function addImages(newImages) {\n if (!newImages.length) return;\n\n var max = 20;\n if (images.length > max) {\n // truncate to last n items\n images = images.slice(max*-1);\n }\n // add new images\n images = images.concat(newImages);\n }", "function addImage(x, y, sizeX, sizeY, image) {\n\tvar w = new MultiWidgets.JavaScriptWidget();\n\n\tw.setLocation(x, y);\n\tw.setWidth(sizeX);\n\tw.setHeight(sizeY);\n\tw.img = new MultiWidgets.ImageWidget();\n\tw.img.addCSSClass(\"ImageW\");\n\n\tif (w.img.load(image)) {\n\t w.img.addOperator(new MultiWidgets.StayInsideParentOperator());\n \tw.img.setLocation(x,y);\n \tw.img.setWidth(sizeX);\n\t w.img.setHeight(sizeY);\n\t w.addChild(w.img);\n \tw.img.raiseToTop();\n\t}\n\n\troot.addChild(w);\n\tw.raiseToTop();\n}", "function plusSlides(num) {\n //add or minus by 1 to slideIndex depending on\n //whether the user clicks right or left on the image slides,\n //(-1 left ,+1 right)\n slideIndex += num;\n //and pass it as an arguement to displaySlides()\n displaySlides(slideIndex);\n}", "function addImage(imageSrc) {\n imageArray.push(imageSrc);\n return this;\n }", "function nextImage () {\n slideIndex = slideIndex + 1\n showSlides(slideIndex)\n}", "function addImage(image) {\n\n\t\t\timages.push(image);\n\n\t\t\tif (!renderTimer) {\n\n\t\t\t\tstartRenderTimer();\n\n\t\t\t}\n\n\t\t\tif (!isWatchingWindow) {\n\n\t\t\t\tstartWatchingWindow();\n\n\t\t\t}\n\n\t\t}", "function addImage(image) {\n\n images.push(image);\n\n if (!renderTimer) {\n\n startRenderTimer();\n\n }\n\n if (!isWatchingWindow) {\n\n startWatchingWindow();\n\n }\n\n }", "function Addimage(image){\n //add to dog-image-container using insertAdjacent 'afterend'\n const dogContainer = document.getElementById(\"dog-image-container\");\n //also create a new element for img\n let newImageElement = document.createElement('img');\n // add that image onto the new element\n newImageElement.src = image\n //add the new element onto dog-image-container child node\n dogContainer.appendChild(newImageElement);\n}", "function addSlide() {\r\n showSlides(slideIndex += 1);\r\n}", "function addImageWithCaption(filename, captionText, captionTextSize, active) \n{\n\n\t//Add Quotes!\n\t//captionText = '\"' + captionText + '\"';\n\n\t/*\n\t\tAdd the Structure (active item for first shown): \n\n\t\t<div class=\"active item\">\n\t <div class=\"carousel-caption\">\n\t <h1>Penalty</h1>\n\t </div>\n\t <img src=\"web/image/harbaugh/penalty.jpg\" alt=\"\">\n\t </div>\n\t*/\n\tvar imageUrl = urlForFilename(filename);\n\n\t//Start with?\n\tvar itemCSSClass = active ? \"active item\" : \"item\";\n\tvar itemDiv = $('<div/>', {\n\t\t\"class\": itemCSSClass\n\t});\n\n\tvar carouselCaptionDiv = $('<div/>', {\n\t\t\"class\": \"carousel-caption\"\n\t})\n\n\tvar caption = $('<h1/>', {\n\t\t//Shorten Text\n\t\t\"class\": textSizeCSSClass(captionTextSize),\n\t\t//For FitText\n\t\ttext: captionText\n\t})\n\n\n\t//Caption -> Caption Div\n\tcarouselCaptionDiv.append(caption);\n\n\tvar image = $(\"<img/>\", {\n\t\tsrc:imageUrl\n\t});\n\n\t//Put the Caption and Image inside item\n\titemDiv.append(carouselCaptionDiv);\n\titemDiv.append(image);\n\n\t//Add the Item\n\t$(CAROUSEL_INNER_SELECTOR).append(itemDiv);\n\n}", "function addBootstrapPhotoGallery(images) {\n // TODO: MODULE_ADVENTURE_DETAILS\n // 1. Add the bootstrap carousel to show the Adventure images\n\n}", "function addSlide(src, className = 'next') {\n const image = document.createElement('img')\n image.src = src\n\n imagesWrapper.appendChild(image)\n\n setTimeout(function() { image.classList.add(className) }, 0)\n}", "function creatImgs(imgs){\n imgs.forEach( img =>{\n const image = document.createElement(\"img\")\n image.src = img\n imgContainer.appendChild(image)\n})\n}", "function addImages() {\n var images = ['heroImage', 'legacyLogo'];\n var img = null;\n for (var i = 0; i < images.length; i++) {\n var key = companyInfo['key'];\n if (companyInfo[images[i]].length > 0) {\n var url = 'https://media.licdn.com/media' + companyInfo[images[i]];\n img = $('<img class=\"recruiting-token-image\" id=\"' + images[i] + '-' + key + '\">');\n $(img).attr('src', url);\n img.data('file', null);\n img.data('name', images[i] + '-' + key);\n img.data('saved', false);\n img.data('scraped', true);\n createThumbnail(img, 'company-image-container');\n }\n }\n}", "function addSlide(target, style) {\n var i = target.length;\n target.push({\n img: 'asstes/images/carousel/image_'+i+'.png'\n });\n }", "function addPicture() {\n\n\tif (isPhotoGalleryOpen) {\n\t\treturn;\n\t}\n\n\tisPhotoGalleryOpen = true;\n\n\tTi.Media.openPhotoGallery({\n\t\tmediaTypes: [Ti.Media.MEDIA_TYPE_PHOTO],\n\t\tsuccess: function(e) {\n\t\t\tisPhotoGalleryOpen = false;\n\n\t\t\t// FIXME: https://jira.appcelerator.org/browse/TIMOB-19764\n\t\t\t// We need to wait for the photo gallery to close or our preview actions won't work\n\t\t\tsetTimeout(function() {\n\n\t\t\t\t// Create a unique filename\n\t\t\t\tvar filename = Ti.Platform.createUUID() + ((Alloy.Globals.logicalDensityFactor === 1) ? '' : '@' + Alloy.Globals.logicalDensityFactor + 'x') + '.jpg';\n\n\t\t\t\t// Create the file under the applicationDataDirectory\n\t\t\t\tvar file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, filename);\n\n\t\t\t\t// Write a square version of the selected media to the file\n\t\t\t\tfile.write(e.media.imageAsThumbnail(Alloy.Globals.detailSize));\n\n\t\t\t\t// Add the model to the collection\n\t\t\t\tAlloy.Collections.picture.create({\n\n\t\t\t\t\t// Set the time the picture was added\n\t\t\t\t\ttime: moment().format(),\n\n\t\t\t\t\t// Set the filename (the full path changes between builds)\n\t\t\t\t\tfilename: filename\n\t\t\t\t});\n\n\t\t\t}, 500);\n\t\t},\n\t\tcancel: function(e) {\n\t\t\tisPhotoGalleryOpen = false;\n\t\t},\n\t\terror: function(e) {\n\t\t\tisPhotoGalleryOpen = false;\n\n\t\t\talert(e.error || 'Unknown Error');\n\t\t}\n\t});\n}", "function add_image(image_url) {\r\n fabric.Image.fromURL(image_url, function (oImg) {\r\n canvas.add(oImg);\r\n // canvas.sendToBack(oImg);\r\n }, { crossOrigin: 'Anonymous' });\r\n}", "function add_image(image_url) {\r\n fabric.Image.fromURL(image_url, function (oImg) {\r\n canvas.add(oImg);\r\n // canvas.sendToBack(oImg);\r\n }, { crossOrigin: 'Anonymous' });\r\n}", "function addImagesToPage() {\n // number of indicators the carousel currently has\n let num_carousel_indicators = 0;\n // checks to see if there is actually image data for the team\n if (image_data[selected_team] !== undefined) {\n // if so, loops through each image\n for (let image_id in image_data[selected_team]) {\n // src for the image, either a url or local file\n let src = image_data[selected_team][image_id];\n // adds the image\n $(\".carousel-inner\").append(`\n <div class=\"carousel-item item item-` + num_carousel_indicators + `\">\n <img class=\"carousel-image\" alt=\"` + selected_team + `\" name=\"` + image_id + `\" src=\"` + src + `\" height=\"250px\" />\n </div>\n `);\n // adds the indicator\n $(\".carousel-indicators\").append(`\n <li data-target=\"#myCarousel\" data-slide-to=\"` + num_carousel_indicators + `\" class=\"indicator indicator-` + num_carousel_indicators + `\"></li>\n `);\n // if this is the first image added, the indicator and image are active\n if (num_carousel_indicators == 0) {\n $(\".indicator-\" + num_carousel_indicators).addClass(\"active\");\n $(\".item-\" + num_carousel_indicators).addClass(\"active\");\n }\n num_carousel_indicators += 1;\n }\n }\n}", "function addImgToDom(image){\n let imgContainer = document.getElementById(\"dog-image-container\");\n let newImage = document.createElement(\"img\");\n newImage.src = image;\n imgContainer.appendChild(newImage);\n}", "function AddImage(ImageID,ImageThumb,ImageMain,ImagePage,ImageNumber,ImageLink,ImageTags){\r\n\tLoaded_Images[ImageID] = {};\r\n\tLoaded_Images[ImageID]['status'] = 'waiting';\r\n\tLoaded_Images[ImageID]['id'] = ImageID\r\n\tLoaded_Images[ImageID]['thumb'] = ImageThumb\r\n\tLoaded_Images[ImageID]['main'] = ImageMain\r\n\tLoaded_Images[ImageID]['page'] = ImagePage\r\n\tLoaded_Images[ImageID]['number'] = ImageNumber\r\n\tLoaded_Images[ImageID]['link'] = ImageLink\r\n\tLoaded_Images[ImageID]['filename'] = ImageMain.match(/\\/[0-9a-zA-Z]{1,}.[a-z]{3,4}\\?/)[0].replace('/','').replace('?','')\r\n\tLoaded_Images[ImageID]['tags'] = ImageTags\r\n}", "function nextImage(){\r\n\t\t\tif (i<image.length) {\r\n\t\t\t\ti= i+1;\r\n\t\t\t}else{\r\n\t\t\t\ti = 1;\r\n\t\t\t}\r\n\t\t\t slider_content.innerHTML = \"<img class=imgslide src=\"+image[i-1]+\" >\";\r\n\r\n\t\t}", "function insertImage() {\n let img = document.createElement(\"img\");\n let section = document.getElementById(\"imageSection\");\n img.src = \"https://source.unsplash.com/random\";\n img.style.height = \"300px\";\n img.style.width = \"auto\";\n section.appendChild(img);\n}", "function addNextImage(imageKeys, files, done) {\n var imageKey = imageKeys[0];\n if (imageKey) {\n // Add normal resolution\n getImage(imageKey, function(error, buffer) {\n if (error) {\n done(error);\n } else {\n if (buffer) {\n files[imageKey + \".png\"] = buffer;\n }\n // Add high resolution\n getImage(imageKey + \"2x\", function(error, buffer) {\n if (error) {\n done(error);\n } else {\n if (buffer)\n files[imageKey + \"@2x.png\"] = buffer;\n addNextImage(imageKeys.slice(1), files, done);\n }\n });\n }\n });\n } else\n done();\n }", "function addImg(msg){\n msg.forEach(imgSrc => { \n const imgList = document.querySelector('#dog-image-container')\n let img = document.createElement('img') \n img.src = imgSrc\n imgList.appendChild(img)\n }); \n \n}", "function addImages(imgName) {\r\n for (var i = 0; i < imgName.length; i++) {\r\n let isHiddenClass = i === 0 ? '' : 'isHidden';\r\n imgWrapper.innerHTML = imgWrapper.innerHTML + \"<img class='displayImage \" + isHiddenClass + \"' src='images/\" + imgName[i] + \"'>\";\r\n }\r\n}", "function AddNewSlide() {\n myPresentation.addSlide(myPresentation.getCurrentSlideIndex() + 1);\n //myPresentation.setCurrentSlideIndex(myPresentation.getCurrentSlideIndex() + 1);\n updateSlideselector();\n goToNextSlide();\n}", "function addCustomImageSlides(rows){\n let pages = \"\";\n for (let row of rows){\n // If location is tumormap or pathway, replace that slide + summary item instead of adding a new one\n if( (row['location'] == 'tumormap') || (row['location'] == 'pathway')){\n let boxname = row['location'];\n let title = document.getElementById(boxname + \"_title\");\n let img = document.getElementById(boxname + \"_img\");\n let caption = document.getElementById(boxname + \"_caption\");\n \n title.innerHTML = row['title'];\n img.src = row['img'];\n caption.innerHTML = row['caption'];\n \n } else {\n pages += '<div class=\"page\">';\n pages += '<h4 class=\"ui top center aligned inverted header\">' + row['title'] + '</h4>';\n pages += '<div><img src=\"' + row[\"img\"] + '\" style=\"width:9.9in;height:5.5in;\">';\n pages += '<div class=\"ui center very basic segment imgcaption\">'\n pages += row[\"caption\"];\n pages += '</div></div></div>';\n }\n }\n return pages;\n }", "function plusSlide(n){\n slideIndex = slideIndex + n;\n // wraparound when end of images is reached\n if(slideIndex > numSlides-1) {\n slideIndex = 0;\n }\n if(slideIndex < 0) {\n slideIndex = 3;\n }\n showSlide(slideIndex);\n}", "function plusSlides(n) { // parameter holds slideIndex\n showSlides(slideIndex += n);\n} // end function", "function plusSlide() {\n showSlides(slideIndex += 1);\n}", "processImages(jq) {\n const maxWidth = ui.dom.messagePane.width() - 30;\n const maxHeight = ui.dom.messagePane.height() - 20;\n\n jq.find('img').wrap(function() {\n return $('<a></a>').attr('href', this.src);\n }).after(function() {\n return $('<span class=\"image-alt\"></span>')\n .text('[image:' + visual.ellipsis(this.src, 64) + ']');\n });\n\n jq.find('img').addClass('rescale').on('load', function() {\n visual.rescale($(this), maxWidth, maxHeight);\n });\n\n if (!config.settings.markup.images) {\n jq.find('img').css('display', 'none').next().css('display', 'inline');\n }\n }", "function addImagesAction(state) {\n api.setAddImagesMenu(state);\n}", "function load_img(slide) {\n if ($(slide).find('img').length === 0) {\n //console.log('loading img into next figure');\n $(slide).prepend('<img alt=\"\" src=\"' + $(slide).attr('data-load-on-demand') + '\">');\n }\n }", "function addPostImage(ImageArray, postId) {\n const id = `preview${postId}`;\n const preview = document.querySelector(`#${id}`);\n ImageArray.forEach(element => {\n const div = document.createElement('div');\n const img = document.createElement('img');\n img.classList.add('feed-image');\n img.src = element;\n div.appendChild(img);\n preview.appendChild(div);\n })\n}", "function imgSlider(img) {\n slide.src = img;\n}", "function imgSlider(img) {\n slide.src = img;\n}", "loadImage() {\n this.imagesLoaded++;\n if (this.imagesLoaded >= this.slides.length) { this.playSlideshow() }\n }", "function displayImage(image) {\n var img = document.createElement(\"IMG\");\n img.src = image.url; \n img.style = \"margin: 15px\";\n document.getElementById('root').appendChild(img);\n}", "loadImage() {\n this.imagesLoaded++;\n if (this.imagesLoaded >= this.slides.length) {\n this.playSlideshow();\n }\n }", "nextImage(){\r\n\t\tthis.changeSlide(this.currentSlide+1);\r\n\t}", "function addImages(filename, filepath, noSpaceName) {\n this.filename = filename;\n this.filepath = filepath;\n this.noSpaceName = noSpaceName;\n this.countShow = 0;\n this.countClicks = 0;\n this.clicksOverViews = function () {\n var percentClick = this.countClicks / this.countShow;\n return percentClick;\n }\n}", "function createImage(promo, nombre) {\n var img = document.createElement('img');\n\n img.setAttribute('src', 'assets/images/' + promo + '/' + nombre + '.jpg');\n\n /* subImagesContainer.appendChild(img); */\n imagesContainer.appendChild(img);\n}", "function addImage(e){\n\t\t \n \t\tvar file = e.target.files[0],\n \t\timageType = /image.*/;\n\t\n \t\tif (!file.type.match(imageType)){\n\t\t \t\t$('#imgImagen').attr(\"src\",\"http://placehold.it/500x300&text=[ad]\");\n\t\t \t \tdocument.getElementById('fileImagen').value ='';\n\t\t \t\tif($('#imagenName').val() != 0){\n\t\t\t \t\t$('#imgImagen').attr(\"src\",URL_IMG + \"app/event/max/\" + $('#imagenName').val())\n\t\t \t\t} else {\n\t\t\t\t\t$('#lblPublicityImage').addClass('error');\n\t\t\t \t\t$('#alertImage').empty();\n\t\t\t \t\t$('#alertImage').append(\"Selecione una imagen\");\n\t\t\t \t\t$('#alertImage').show();\n\t\t \t\t}\n \t\t\treturn;\n\t \t\t}\n \t\t\t//carga la imagen\n \t\tvar reader = new FileReader();\n \t\treader.onload = fileOnload;\n \t\treader.readAsDataURL(file);\n \t}", "function nextImage(){\r\n if(i < images.length){\r\n i += 1;\r\n }else{\r\n i = 1;\r\n }\r\n slider_content.innerHTML = \"<img src=\"+images[i-1]+\".jpg>\";\r\n}", "function add_img(url_end) {\r\n return \"http://i.imgur.com/\" + url_end;\r\n }", "function addImage(src, type, doc, page, x, y, width, height, link, func) {\n let img = new Image();\n img.src = baseURL + src;\n img.addEventListener('load', function(event) {\n let url = getDataUrl(img, type);\n height = height? height: width * img.height / img.width;\n x = x < 0? -x - width: x;\n y = y < 0? -y - height: y;\n doc.setPage(page);\n doc.addImage(url, type, x, y, width, height);\n if (link)\n {\n let options = {url: link};\n doc.link(x, y, width, height, options);\n }\n });\n }", "function addImage (data) {\n var element = document.createElement('div');\n element.innerHTML = '<img src=\"' + data +'\" />';\n\n var container = document.getElementById('data--container');\n container.appendChild(element);\n }", "function loadCarouselImages() \n{\n\n\tIMAGES = randomizeArray(IMAGES);\n\t\n\t//Imported IMAGES & CAPTIONS\n\t//From images.js\n\tSTART_INDEX = 0;\n\n\tfor(var i=0; i < IMAGES.length; i++)\n\t\taddImageWithCaption(IMAGES[i][1], IMAGES[i][2], IMAGES[i][0], START_INDEX == i);\n}", "function plusSlides(n) {\n slideIndex += n;\n showSlides(slideIndex);\n}", "function add_img() {\n var i, URL, imageUrl, id, file,\n files = gId('type_file').files; // all files in input\n if (files.length > 0) {\n for (i = 0; i < files.length; i++) {\n file = files[i];\n if (!file.type.match('image.*')) { //Select from files only pictures\n continue;\n }\n // Create array Images to be able to choose what pictures will be uploaded.\n // You cannot change the value of an <input type=\"file\"> using JavaScript.\n Images.push(file);\n URL = window.URL;\n if (URL) {\n var imageUrl = URL.createObjectURL(files[i]); // create object URL for image \n var img_block = document.createElement(\"div\");\n img_block.className = \"img_block\";\n gId('photo_cont').appendChild(img_block)\n var img_story = document.createElement(\"img\")\n img_story.className = \"img_story\";\n img_story.src = imageUrl;\n img_block.appendChild(img_story);\n var button_delete = document.createElement(\"button\"); // create button to delete picture\n button_delete.className = \"button_3\";\n var x = document.createTextNode(\"x\");\n button_delete.appendChild(x)\n img_block.appendChild(button_delete);\n }\n }\n gId('photo_cont').style.display = 'inline-block';\n }\n}", "function handleAdd(){\n\n if(newImageUrl!==\"\"){\n \n setimages([ newImageUrl, ...images\n\n \n ]\n )\n setNewImageUrl(\"\")\n\n \n }\n }", "function plusSlides(n) {\n\tshowSlides(slideIndex += n);\n}", "function addSlides () {\n vm.carousel.slides = [\n {'id':0, 'titulo': 'Bienvenido', 'image': 'images/productos/cacique.jpg'}\n ];\n promotion.queryFresh(\n function success (data) {\n vm.listpromotion = data;\n var count = 1;\n vm.listpromotion.forEach(function(promocion){\n promocion.dire = vm.ApiUrl + '/images/'+ promocion.url;\n console.log(promocion.dire);\n vm.carousel.slides.push({\n 'id':count,\n 'descripcion':promocion.descripcion,\n 'titulo':promocion.titulo,\n 'image': promocion.dire\n });\n count++;\n });\n\n\n }, function error (error) {\n }\n );\n }", "insertImagesAsFigures(files) {\n // TODO: we would need a transaction on archive level, creating assets,\n // and then placing them inside the article body.\n // This way the archive gets 'polluted', i.e. a redo of that change does\n // not remove the asset.\n const editorSession = this.getEditorSession();\n const paths = files.map(file => {\n return this.archive.addAsset(file);\n });\n const sel = editorSession.getSelection();\n if (!sel || !sel.containerPath) return;\n editorSession.transaction(tx => {\n importFigures(tx, sel, files, paths);\n });\n }", "function cardSliderImagesMarkup(data) {\n return slides.insertAdjacentHTML('afterbegin', imagesTemplate(data));\n}", "function addSlide(i, data) {\n vm.slides.push({\n image: 'assets/images/carousel/c' + i + '.png',\n text: data.mensaje,\n title: data.titulo\n });\n }", "function displayImage(){\n\t//Function always displays the image in the \"0\" value of the array\n\tcurrentImage.image = \"galleryImages/\" + imageFiles[0];\n}", "function plusSlides(n) {\n // Increment or decrement slideIndex and display\n showSlides(slideIndex += n);\n}", "function addImage(leftImg, rightImg) {\r\n\tif(leftDiv.firstChild) {\r\n\t\tleftDiv.removeChild(leftDiv.firstChild)\r\n\t}\r\n\tif(rightDiv.firstChild) {\r\n\t\trightDiv.removeChild(rightDiv.firstChild)\r\n\t}\r\n\r\n\tleftDiv.appendChild(leftImg)\r\n\trightDiv.appendChild(rightImg)\r\n}", "function plusSlides(n) {\n\tshowSlides((slideIndex += n));\n}", "addImageToField(image) {\n\t\tconst list = getArrayFromField(this.imagesField);\n\t\tlist.push(image);\n\t\tconsole.log('addImageToField -- list: ');\n\t\tconsole.log(list);\n\t\tsaveArrayToField(this.imagesField, list);\n\t}", "function newImage(curId, afterID, title, src) {\n\t\t//Create image container\n\t\tvar div = document.createElement('div');\n\t\tdiv.id = \"image\" + curId;\n\t\tdiv.style.display = \"none\";\n\t\tdiv.classList.add(\"imageDiv\");\n\n\t\t// Insert template into container\n\t\tdiv.innerHTML = [{ id: curId }].map(ImageTemplate).join('');\n\n\t\t// Show image container\n\t\tdiv.style.display = \"block\";\n\n\t\t// Insert container with text after choosed id\n\t\tvar parent = document.getElementById('articleParent'); \n\t\t//parent.insertBefore(div, document.getElementById(afterID).nextSibling);\n\t\tparent.insertBefore(div, afterID);\n\n\t\t// Get img tag\n\t\tvar img = document.getElementById('img' + curId);\n\n\t\t// Load image into img tag\n\t\timg.src = src;\n\n\t\t// Set title\n\t\tdocument.getElementById('imgtitle' + curId).innerText = title;\n\t}", "function addBootstrapPhotoGallery(images) {\n // TODO: MODULE_ADVENTURE_DETAILS\n // 1. Add the bootstrap carousel to show the Adventure images\n\n // parent\n // carousel\n // ol\n // li....\n // carouselInner\n // a\n // prevBtn\n // a\n // nextBtn\n\n let parent = document.getElementById(\"photo-gallery\");\n parent.textContent = \"\";\n\n let carousel = document.createElement(\"div\");\n carousel.id = \"imageCarousel\";\n carousel.className = \"carousel slide\";\n carousel.setAttribute(\"data-ride\", \"carousel\");\n\n parent.appendChild(carousel);\n\n let ol = document.createElement(\"ol\");\n ol.className = \"carousel-indicators\";\n for (let i = 0; i < images.length; ++i) {\n let li = document.createElement(\"li\");\n li.setAttribute(\"data-target\", \"#imageCarousel\");\n li.setAttribute(\"data-slide-to\", `${i}`);\n\n if (i == 0) {\n li.className = \"active\";\n }\n ol.appendChild(li);\n }\n\n carousel.appendChild(ol);\n\n let carouselInner = document.createElement(\"div\");\n carouselInner.className = \"carousel-inner\";\n for (let i = 0; i < images.length; ++i) {\n let div = document.createElement(\"div\");\n div.className = \"carousel-item\";\n let img = document.createElement(\"img\");\n img.className = \"d-block w-100 img-fluid activity-card-image\";\n img.src = images[i];\n img.alt = `slide-${i + 1}`;\n\n if (i == 0) {\n div.className = \"carousel-item active\";\n }\n div.appendChild(img);\n carouselInner.appendChild(div);\n }\n carousel.appendChild(carouselInner);\n\n let prevBtn = document.createElement(\"a\");\n prevBtn.setAttribute(\"data-slide\", \"prev\");\n prevBtn.className = \"carousel-control-prev\";\n prevBtn.href = \"#imageCarousel\";\n prevBtn.role = \"button\";\n $(prevBtn)\n .append(`<span class=\"carousel-control-prev-icon\" aria-hidden=\"true\"></span>\n <span class=\"sr-only\">Previous</span>`);\n\n let nextBtn = document.createElement(\"a\");\n nextBtn.setAttribute(\"data-slide\", \"next\");\n nextBtn.className = \"carousel-control-next\";\n nextBtn.href = \"#imageCarousel\";\n nextBtn.role = \"button\";\n $(nextBtn)\n .append(`<span class=\"carousel-control-next-icon\" aria-hidden=\"true\"></span>\n <span class=\"sr-only\">Next</span>`);\n\n carousel.appendChild(prevBtn);\n carousel.appendChild(nextBtn);\n\n parent.appendChild(carousel);\n}", "function addImg (image) {\n jCooper.images.headshot2 = (image);\n console.log(jCooper.images.headshot2)\n}", "function plusSlides(n) {\n showSlides(slideIndex += n);\n}", "function nextImage(event)\n\t\t{\n\t\t\t//check that the counter does not exceed our array size\n\t\t\tif(x == (data.images.length - 1))\n\t\t\t{\n\t\t\t\tx = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tx++;\n\t\t\t}\n\t\t\t//create another block of code containing the next image in line\n\t\t\t//set the pages gallery tag to our new data\n\t\t\tvar info = '';\n\t\t\tinfo += '<p><img src = \"' + currentImage[x] + '\"alt=\"' + currentDescription[x] + '\"></p>';\n\t\t\tinfo += '<h3>' + currentTitle[x] + '</h3>';\n\t\t\tinfo += '<p>' + currentDescription[x] + '</p>';\n\t\t\tdocument.querySelector('#gallery article').innerHTML = info;\n\t\t}", "function plusSlides(n) {\n showSlides(slideIndex += n);\n}", "function plusSlides(n) {\n showSlides(slideIndex += n);\n}", "function plusSlides (n) {\n showSlides(slideIndex += n)\n}", "function addImage(imegSrc, parent){\n//\tvar elem = document.createElement(\"img\");\n//\tvar elem = imegSrc;\n//\telem.setAttribute(\"src\", imegSrc);\n\tparent.appendChild(imegSrc);\n}", "function insertImages() {\n 'use strict';\n\n coinImage.src = 'img/coin.png';\n coin.appendChild(coinImage);\n headCoinImage.src = 'img/head-coin.png';\n headCoin.appendChild(headCoinImage);\n tailCoinImage.src = 'img/tail-coin.png';\n tailCoin.appendChild(tailCoinImage);\n}", "function nextImage() {\n imageNumber++;\n if (imageNumber === artCollection.length) {\n imageNumber = 0;\n }\n imageElement.src = artCollection[imageNumber];\n updateDescriptions();\n}", "function addImage(){\n\t\t\tlet htmlContent = '';\n\t\t\tdata = JSON.parse(this.responseText);\n\t\t\tconsole.log(data.results);\n\n\t\t\tif(data && data.results && data.results[1]){\n\t\t\t\tconst firstImage = data.results[1];\n\t\t\t\thtmlContent = `<figure>\n\t\t\t\t<img src=\"${firstImage.urls.regular}\" alt=${searchText}>\n\t\t\t\t<figcaption>${searchText} by ${firstImage.user.name} </figcaption>\n\t\t\t\t</figure>\n\t\t\t\t`\n\t\t\t}else{\n\t\t\t\thtmlContent = `<div class=\"error-no-image\">No Image available</div>`\n\t\t\t}\n\t\t\tresultContainer.insertAdjacentHTML('afterbegin', htmlContent);\n\t\t}", "function setImage(){\n document.slideshow.src = images[i];\n}", "function gallery(){\r\n\r\n showName();\r\n\r\n\r\n //create the images to display in the gallery\r\n\r\n for (i = 1; i <= 60; i++){\r\n\r\n //create a string adding the images directory and looping through the filename numbers\r\n\r\n //loop through images 1-9 due to the extra character space added after the number 9\r\n if (i < 10){\r\n var mySlides = \"../static/javapic/images/pdxcg_0\" + i + \".jpg\";\r\n\r\n }\r\n\r\n //loop through all image after the number 9\r\n if(i > 9){\r\n var mySlides = \"../static/javapic/images/pdxcg_\" + i + \".jpg\";\r\n\r\n\r\n //ignore missing file 42 and keep going\r\n if( i===42){\r\n continue;\r\n }\r\n }\r\n\r\n //create an <li> in javascript\r\n var li = document.createElement(\"LI\");\r\n\r\n //create an image in javascript\r\n var img = document.createElement(\"IMG\");\r\n img.setAttribute(\"src\", mySlides);\r\n\r\n //place the image in the <li> \r\n li.appendChild(img);\r\n\r\n //place the <li> in the gallery\r\n document.getElementById(\"gallery\").appendChild(li);\r\n\r\n \r\n }\r\n\r\n}", "function addImage(url, urlToImage, element) {\r\n // use placeholder image if urlToImage is invalid\r\n if (urlToImage == null) { urlToImage = 'placeholder.png' }\r\n\r\n // create the link\r\n let wrapper = document.createElement('a');\r\n wrapper.href = url;\r\n wrapper.target = '_blank';\r\n\r\n // create the image\r\n let image = document.createElement('img');\r\n image.classList.add('image');\r\n image.src = urlToImage;\r\n\r\n // wrap up\r\n wrapper.appendChild(image);\r\n element.appendChild(wrapper);\r\n}", "function createImages()\n{\n\tlargeImg.src = imgArray[0];\n\t\n\tfor (var i = 0; i < imgArray.length; i++)\n\t{\n\t\tfourImgsDiv.innerHTML += \"<img src='\" + imgArray[i] + \"'>\";\n\t}\n}", "function plusSlides(n) {\n showSlides(slideIndex += n)\n}", "function addImg(props, show)\n\t{\n\t\tshow = (typeof show === \"undefined\") ? false : show;\n\t\t\n\t\t$('.buttons button').each(function(){\n\t\t\t$(this).removeClass('hide');\n\t\t\t$(this).prop('disabled', false);\n\t\t});\n\t\t\n\t\tvar labelText = props['data-filter-name'];\n\t\t\n\t\tvar div = $('<div />', {'class': 'img-thumbnail'});\n\t\tvar img = $('<img />', props);\n\t\tvar label = $('<p />', {'class': 'img-label'}).text(labelText.capitalize());\n\t\t\n\t\timg.appendTo(div);\n\t\tlabel.appendTo(div);\n\t\tdiv.appendTo('#img-list');\n\t\t\n\t\tif (show){\n\t\t\t$('#img-container').empty();\n\t\t\tdelete props['id'];\n\t\t\tdelete props['class'];\n\t\t\tprops['class'] = 'img-instapy';\n\t\t\t$('<img />', props).appendTo('#img-container');\n\t\t}\n\t\t$('#img-list').fadeIn();\n\t\t$('#img-container').fadeIn();\n\t}", "function insertImg(range, src, imageId) {\n if (range) {\n range.deleteContents();\n var divContainer = document.createElement(\"div\");\n divContainer.setAttribute('class', 'divImageHolder');\n\n var img = document.createElement(\"img\");\n img.setAttribute('src', src);\n img.setAttribute('alt', 'img');\n img.setAttribute('id', imageId);\n\n divContainer.appendChild(img);\n\n range.deleteContents();\n range.insertNode(divContainer);\n\n }\n}", "plusSlides(n) {\n return this.showSlides(this.slideIndex += n);\n }", "function placeImages(myDoc,imageList,progressWindow){\n\tvar processStatusLog = progressWindow.processStatus.text;\n\tvar myHeight = myDoc.documentPreferences.pageHeight;\n\tvar myWidth = myDoc.documentPreferences.pageWidth;\n\tfor (var x = 0; x < imageList.length; x++){\n\t\tvar targetPage = myDoc.pages.item(imageList[x].name);\n\t\tvar targetPageBounds = targetPage.bounds;\n\t\tprogressWindow.processStatus.text = processStatusLog + \"Creating frame for page \" + imageList[x].name + \"...\";\n\t\tvar targetFrame = targetPage.rectangles.add({\n\t\t\tgeometricBounds:[0, 0, myHeight, myWidth],\n\t\t\ttopLeftCornerOption:CornerOptions.NONE,\n\t\t\ttopRightCornerOption:CornerOptions.NONE,\n\t\t\tbottomLeftCornerOption:CornerOptions.NONE,\n\t\t\tbottomRightCornerOption:CornerOptions.NONE\n\t\t})\n\t\ttargetFrame.move(undefined,[targetPageBounds[1],0]);\n\t\tif (!targetFrame.isValid){\n\t\talert(\"Failed to create image frame for page \" + targetPage.name);\n\t\texit();\n\t\t} else {\n\t\t\tprogressWindow.processStatus.text = processStatusLog + \"Placing image for page \" + imageList[x].name + \"...\";\n\t\t\ttargetFrame.place(imageList[x].path);\n\t\t\ttargetFrame.fit(FitOptions.FILL_PROPORTIONALLY);\n\t\t}\n\t}\n\tprogressWindow.processStatus.text = processStatusLog + \"Created frames for each page and placed images\\r\\n\";\n}", "function plusSlides(n) {\n previousIndex = slideIndex;\n showSlides(slideIndex += n);\n}", "function insertImageOnSpreadsheet() {\n var oscar = SpreadsheetApp.getActive();\n var oscar_sheet = oscar.getSheetByName(oscar_sheet_name)\n var fileId = '1czq5D7RTLErTZ3HwRJTuACsi44VIVwRV';\n var img = DriveApp.getFileById(fileId).getBlob();\n \n oscar_sheet.insertImage(img, 1, 1);\n}", "function createImage(promo,nombre){\n var img = document.createElement('img');\n\n img.setAttribute('src','assets/images/'+ promo + '/'+ nombre +'.jpg'); \n imagesContainer.appendChild(img);\n}", "function setMain(){\r\n var slides = document.getElementById(\"slides\");\r\n var mainImage = document.createElement(\"img\");\r\n var whichImage = Math.floor(Math.random()*6)\r\n mainImage.src= thumbImages[whichImage];\r\n slides.appendChild(mainImage);\r\n mainImage.className = \"mainImage\";\r\n}", "function setImages(slide, icon, background) {\n \n \n // Setup global variables\n var iconFolder = DriveApp.getFolderById(settingsArray[6][3]).getFilesByName(icon)\n var backgroundFolder = DriveApp.getFolderById(settingsArray[6][4])\n var backgroundImages = []\n var ui = SpreadsheetApp.getUi() // Grab UI for alerts\n \n // Edit sport icon (bottom image)\n if (iconFolder.hasNext()) { // If icon image exists:\n slide.getImages()[1].replace(iconFolder.next()) // Replace placeholder with icon\n } else { // Else:\n slide.getImages()[1].remove() // Remove image\n }\n \n \n // Edit background image\n if (backgroundFolder.getFoldersByName(background).hasNext()) { // If a folder for the team exists:\n backgroundFolder = backgroundFolder.getFoldersByName(background).next().getFiles() // Get files from folder\n if (backgroundFolder.hasNext()) { // If images in folder exist:\n while (backgroundFolder.hasNext()) { // While there are images:\n backgroundImages.push(backgroundFolder.next()) // Add image to an intermediary array\n }\n slide.getImages()[0].replace(backgroundImages[Math.floor(Math.random() * Math.floor(backgroundImages.length))], true) // Set background to random image from array\n }\n } else { // If folder for the team doesn't exist\n backgroundFolder = backgroundFolder.createFolder(background).getFiles() // Create a folder\n }\n \n}", "function showPic() {\r\n var nextImage = document.createElement(\"img\");\r\n nextImage.src = \"img/roles/\" + rolePics[0].fileName;\r\n nextImage.id = rolePics[0].id;\r\n nextImage.alt = rolePics[0].altText;\r\n document.querySelector(\".DnD__toDrag-img\").appendChild(nextImage);\r\n}", "function incImg() {\r\n\t\t\tloaded++;\r\n\t\t\tif(loaded == slides.length) {\r\n\t\t\t\tfor(var i = 0; i < slides.length; i++) {\r\n\t\t\t\t\tjbl.slides[i] = {\r\n\t\t\t\t\t\telement: slides[i],\r\n\t\t\t\t\t\twidth: img.width,\r\n\t\t\t\t\t\theight: img.height\r\n\t\t\t\t\t};\r\n\t\t\t\t\tvar sposx = -Math.round((img.width - $(slide).width()) / 2);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tpostaction();\r\n\t\t\t}\r\n\t\t}", "function showSliderImages(){\n\n document.querySelector('.slider').innerHTML = `\n <div class=\"container_slide_images_about_me\">\n <img class=\"mySlides\" src=\"/images/1.jpg\" alt=\"me\">\n <img class=\"mySlides\" src=\"/images/2.jpg\" alt=\"me\">\n <img class=\"mySlides\" src=\"/images/3.jpg\" alt=\"me\">\n <img class=\"mySlides\" src=\"/images/4.jpg\" alt=\"me\">\n <img class=\"mySlides\" src=\"/images/5.jpg\" alt=\"me\">\n <img class=\"mySlides\" src=\"/images/6.jpg\" alt=\"me\">\n <img class=\"mySlides\" src=\"/images/7.jpg\" alt=\"me\">\n <img class=\"mySlides\" src=\"/images/8.jpg\" alt=\"me\">\n </div>`\n \n}", "function addAdditionalImages(urlArray) {\r\n var freeUrlInputs = [];\r\n // getting free inputs (inf url and file inputs are empty)\r\n $(\".additional_image_file\").each(function() {\r\n var url = $(this).siblings(\"input.additional_image_url\").val();\r\n var file = $(this).val();\r\n if (\r\n file == \"\" && // new local file\r\n url == \"\" && // or url\r\n // image can be already set\r\n !$(this).parents(\"div.control-group.span6\").find(\".controls .rmAddPic\").size() > 0\r\n ) {\r\n freeUrlInputs.push($(this).siblings(\"input.additional_image_url\").attr('id'))\r\n }\r\n });\r\n\r\n if (urlArray.length > freeUrlInputs.length) {\r\n return \"Недостаточно мест для изображений\";\r\n }\r\n\r\n for (var i = 0; i < urlArray.length; i++) {\r\n var img = document.createElement(\"img\");\r\n img.src = urlArray[i];\r\n $(img).addClass('img-polaroid').css({\r\n width: '50px',\r\n 'max-heigth': '100%'\r\n });\r\n $(\"#\" + freeUrlInputs[i]).val(urlArray[i]);\r\n $(\"#\" + freeUrlInputs[i]).parents(\"div.control-group.span6\").find(\".controls\").html(img);\r\n }\r\n return true;\r\n }", "function createImage(imageLink) {\n\n // create a tag in memory\n let newImg = $('<img>', {\n 'src': imageLink\n });\n newImg.addClass(\"images\");\n // append it to the grid\n $('#image-grid').append(newImg);\n}", "function photoSlideshow(){\n\tvar image = document.getElementById(\"image\");\n\timageCounter++;\n\tif(imageCounter > total){\n\t\timageCounter = 1;\n\t}\n\timage.src = \"../images/slide\" + imageCounter + \".jpg\";\n}", "function insertImageLinksToDocs() {\n let images = document.getElementsByClassName(GDOCS_IMG_OBJECT_CLASS);\n\n // Insert image anchor into each parent container\n for (let image of images) {\n // skip if the imageContainer already has the imageLink object added by this plugin\n const imageContainer = image.closest(`.${GDOCS_IMG_CONTAINER_CLASS}`);\n if (imageContainer.querySelector(\".imageLink\") != null) return;\n\n // insert imageLink object\n const imageURL = image.getElementsByTagName(\"image\")[0].getAttribute(\"xlink:href\");\n const imageHTML = `<a href=\"${imageURL}\" target=\"_blank\" class=\"imageLink\"></a>`;\n imageContainer.insertAdjacentHTML(\"afterbegin\", imageHTML);\n }\n}", "function plusSlides(n) {\n Slides(slideIndex += n);\n}" ]
[ "0.6982767", "0.6752146", "0.6639319", "0.6127675", "0.6099954", "0.6085157", "0.59212434", "0.5917827", "0.5899497", "0.5898721", "0.5837645", "0.58013916", "0.5795272", "0.5741586", "0.5716087", "0.57125163", "0.56856376", "0.5669663", "0.5610368", "0.56024754", "0.5598941", "0.5598941", "0.5563916", "0.55482775", "0.5511631", "0.55022484", "0.54883826", "0.54811984", "0.54712796", "0.54607517", "0.54538006", "0.5418809", "0.54171807", "0.5417118", "0.5397644", "0.5391178", "0.5378164", "0.5372383", "0.5346955", "0.5343491", "0.5343491", "0.5303082", "0.5302357", "0.52942437", "0.5293868", "0.52748007", "0.52744114", "0.5273681", "0.5255183", "0.52439976", "0.52402884", "0.52386934", "0.5234043", "0.5228957", "0.52277684", "0.5220089", "0.52162635", "0.5216133", "0.5214462", "0.5212147", "0.5202318", "0.5195866", "0.5194822", "0.51863545", "0.518603", "0.5184996", "0.5175764", "0.5172715", "0.51718843", "0.51699847", "0.515661", "0.5150412", "0.5150412", "0.51467526", "0.5145028", "0.51434326", "0.5138364", "0.512822", "0.512502", "0.5124506", "0.5120781", "0.51144373", "0.5113311", "0.5104157", "0.50871164", "0.50741845", "0.5058014", "0.5053485", "0.50506157", "0.5039556", "0.50372005", "0.5035513", "0.50320166", "0.5023011", "0.50129783", "0.5008395", "0.5003689", "0.5001605", "0.49930397", "0.49868423" ]
0.6363399
3
The driver application features an array of image URLs, setting of the main title & subtitle, and creation of individual slides for each image.
function main() { var images = [ 'http://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png', 'http://www.google.com/services/images/phone-animation-results_2x.png', 'http://www.google.com/services/images/section-work-card-img_2x.jpg', 'http://gsuite.google.com/img/icons/product-lockup.png', 'http://gsuite.google.com/img/home-hero_2x.jpg' ]; var [title, subtitle] = presentation.getSlides()[0].getPageElements(); title.asShape().getText().setText(NAME); subtitle.asShape().getText().setText('Google Apps Script\nSlides Service demo'); images.forEach(addImageSlide); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function main() {\n var images = [\n 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png',\n 'http://www.google.com/services/images/phone-animation-results_2x.png',\n 'http://www.google.com/services/images/section-work-card-img_2x.jpg',\n 'http://gsuite.google.com/img/icons/product-lockup.png',\n 'http://gsuite.google.com/img/home-hero_2x.jpg'\n ];\n var [title, subtitle] = deck.getSlides()[0].getPageElements();\n title.asShape().getText().setText(NAME);\n subtitle.asShape().getText().setText('Google Apps Script\\nSlides Service demo');\n images.forEach(addImageSlide);\n}", "function setup_slideshow() {\n slide_count = img_array.length;\n current_slide_index = 0;\n set_current_slide(img_array[0].src);\n play();\n}", "function addRemainingImageSlides(imageArray) {\n imageArray.forEach(src => {\n const img = `<img src=\"${src}\" alt=\"Photo from the 2021 KCC Foundation scholarship reception\">`;\n // Insert additional slides into both slider-instances\n $('#galleryTrack').slick('slickAdd', img); // The `...slick('slickAdd')` method takes a string of HTML as 2nd arg\n $('#galleryNav').slick('slickAdd', img);\n });\n}", "function createSlides( arr, container ) {\n\n var gal = container.querySelector(\".gallry > .slides\");\n\n // array has slides in it?\n if ( arr.length > 0 ) {\n for ( var i = 0; i < arr.length; i++ ) {\n\n var fig = document.createElement(\"FIGURE\"); // create figure element\n // create new element\n gal.appendChild( fig );\n }\n displaySlide( arr, container );\n }\n else {\n console.log(\"createSlides function needs an array to be passed in as param\");\n }\n }", "function showSlide()\r\n{\r\n // create objects\r\n const image1 = {file: \"ocean_beach_2.jpg\", description: \"Ocean Beach\", alt: \"Ocean Beach\"};\r\n const image2 = {file: \"back_beach_sorrento.jpg\", description: \"Sorrento Back Beach\", alt: \"Sorrento Back Beach\"};\r\n const image3 = {file: \"ocean_beach.jpg\", description: \"Ocean Beach\", alt: \"Ocean Beach\"};\r\n \r\n // using an array\r\n const images = [image1, image2, image3];\r\n \r\n // limit slideshow\r\n if (slideIndex >= images.length)\r\n {\r\n slideIndex = 0; // reset to the start\r\n }\r\n if (slideIndex === -1)\r\n {\r\n slideIndex = images.length-1; // reset to last slide \r\n }\r\n\r\n // display the slide\r\n const slideImage = document.querySelector(\".slides img\");\r\n slideImage.src = \"ICTWEB431_AE_Pro_1of2_SR1/\" + images[slideIndex].file;\r\n slideImage.alt = images[slideIndex].alt;\r\n\r\n // slides[slideIndex - 1].style.display = \"block\";\r\n\r\n // display description\r\n const description = document.querySelector(\".description\");\r\n description.innerHTML = images[slideIndex].description;\r\n\r\n // display the slide dot as the current dot\r\n // remove the class active from all dots\r\n const dotsList = document.getElementsByClassName(\"dot\");\r\n\r\n for (let i = 0; i < dotsList.length; i++)\r\n {\r\n dotsList[i].classList.remove(\"active\");\r\n }\r\n \r\n // set the class for the slide as \"active\" \r\n dotsList[slideIndex].classList.add(\"active\");\r\n\r\n}", "function setImage(){\n document.slideshow.src = images[i];\n}", "function addBootstrapPhotoGallery(images) {\n // TODO: MODULE_ADVENTURE_DETAILS\n // 1. Add the bootstrap carousel to show the Adventure images\n\n}", "function showImagesGallery(array) {\n\n //Inicio las variables en la primera posicion para activar esta posicion\n let htmlContentToAppend = `<div div class=\"carousel-item active\"><img src=\"` + array[0] + `\" class=\"d-block w-100\" alt=\"\"></div>`;\n let htmlContentSlide = `<li data-target=\"#carouselExampleIndicators\" data-slide-to=\"0\" class=\"active\"></li>`;\n\n for (let i = 1; i < array.length; i++) {\n let imageSrc = array[i];\n\n htmlContentSlide += `<li data-target=\"#carouselExampleIndicators\" data-slide-to=\"` + i + `\" class=\"active\"></li>`\n\n htmlContentToAppend += `\n <div class=\"carousel-item\">\n <img src=\"` + imageSrc + `\" class=\"d-block w-100\" alt=\"\">\n </div> \n `\n }\n document.getElementById(\"slides\").innerHTML = htmlContentSlide;\n document.getElementById(\"carrusel\").innerHTML = htmlContentToAppend;\n\n\n}", "function makeGallery(imageArray){\n\n\t}", "function start_loadImages()\n {\n methods.loadImages(\n function() {\n methods.getDataURI();\n run_app();\n },\n imagesRack.imgList\n );\n }", "function initialize_app_pictures() {\n //create an image and set the source\n current_app_index = 0;\n current_preview_index = 1; //assuming more than one image in apps_array\n\n for(var i = 1; i < image_array.length; i++){\n image_array[i].css('left','200%');\n }\n image_array[0].addClass('curr_app visible').css('left','0%');\n image_array[1].addClass('curr_preview visible').css('left','100%');\n}", "function loadCarouselImages() \n{\n\n\tIMAGES = randomizeArray(IMAGES);\n\t\n\t//Imported IMAGES & CAPTIONS\n\t//From images.js\n\tSTART_INDEX = 0;\n\n\tfor(var i=0; i < IMAGES.length; i++)\n\t\taddImageWithCaption(IMAGES[i][1], IMAGES[i][2], IMAGES[i][0], START_INDEX == i);\n}", "loadImage() {\n this.imagesLoaded++;\n if (this.imagesLoaded >= this.slides.length) {\n this.playSlideshow();\n }\n }", "function addCustomImageSlides(rows){\n let pages = \"\";\n for (let row of rows){\n // If location is tumormap or pathway, replace that slide + summary item instead of adding a new one\n if( (row['location'] == 'tumormap') || (row['location'] == 'pathway')){\n let boxname = row['location'];\n let title = document.getElementById(boxname + \"_title\");\n let img = document.getElementById(boxname + \"_img\");\n let caption = document.getElementById(boxname + \"_caption\");\n \n title.innerHTML = row['title'];\n img.src = row['img'];\n caption.innerHTML = row['caption'];\n \n } else {\n pages += '<div class=\"page\">';\n pages += '<h4 class=\"ui top center aligned inverted header\">' + row['title'] + '</h4>';\n pages += '<div><img src=\"' + row[\"img\"] + '\" style=\"width:9.9in;height:5.5in;\">';\n pages += '<div class=\"ui center very basic segment imgcaption\">'\n pages += row[\"caption\"];\n pages += '</div></div></div>';\n }\n }\n return pages;\n }", "function startslides() {\n\tif(imgSearch) {\n\t\timgSearch.startSlides();\n\t}\n}", "loadImage() {\n this.imagesLoaded++;\n if (this.imagesLoaded >= this.slides.length) { this.playSlideshow() }\n }", "function createImages()\n{\n\tlargeImg.src = imgArray[0];\n\t\n\tfor (var i = 0; i < imgArray.length; i++)\n\t{\n\t\tfourImgsDiv.innerHTML += \"<img src='\" + imgArray[i] + \"'>\";\n\t}\n}", "function initSlidesImages(){\n\n\t\t\t\t\t\t\t\t\t// $('#ContentSliderItem').css('width', (items.length*width)+'px')\n\t\t\t\t\t\t\t\t\t$('#ContentSliderItem').css('width', (items.length)*560+'px')\n\n\t\t\t\t\t\t\t\t\tvar btnNext = $('#btnNextB')\n\t\t\t\t\t\t\t\t\tvar btnPrev = $('#btnPrevB')\n\n\t\t\t\t\t\t\t\t\tbtnNext.on('click', nextSlideB)\n\t\t\t\t\t\t\t\t\tbtnPrev.on('click', prevSlideB)\n\t\t\t\t\t\t\t\t}", "function schoolSlides() {\n return ['00-school/00-TITLE.md', '00-school/speaker-jef.md'];\n}", "function displaySlide( arr, container ) {\n //console.log(container);\n var el = container.querySelectorAll(\".gallry .slides > figure\");\n\n // if elements created and variable successful\n if (el) {\n for ( var i = 0; i < arr.length; i++ ) {\n // clear out all active class assignments\n el[i].classList.remove(\"active\");\n // set default active state\n if ( arr[i].active ) {\n el[i].classList.add(\"active\");\n Velocity( el[i], { left: \"0%\" }, { display: \"block\" }, { duration: prefs.timing, easing: prefs.easing });\n }\n else if ( i < currentSlide( arr ).index() ) {\n Velocity( el[i], { left: \"-100%\" }, { display: \"none\" }, { duration: prefs.timing, easing: prefs.easing });\n }\n else {\n Velocity( el[i], { left: \"100%\" }, { display: \"none\" }, { duration: prefs.timing, easing: prefs.easing });\n }\n\n if (arr[i].backgroundPosition !== undefined) {\n el[i].style.backgroundSize = arr[i].size;\n el[i].style.backgroundPosition = arr[i].backgroundPosition;\n }\n else {\n el[i].style.backgroundSize = \"cover\";\n el[i].style.backgroundPosition = \"center\";\n }\n\n // this conditional currently requires 2x assets to be available. If no 2x assets are available,\n // no fallback images are provided.\n if (prefs.retina) {\n // do some device sniffing to determine if the screen is retina display or not\n if (window.devicePixelRatio > 1.5) {\n var str = arr[i].src;\n var first = str.slice(0, str.length - 4); // get first part of string\n var last = str.slice(str.length - 4, str.length); // get .jpg, .png, .svg, .gif files --- must be 4 character file extension\n el[i].style.backgroundImage = \"url('\" + first + \"_2x\" + last + \"')\"; // defining gallery slide image via arr.src prop\n }\n else {\n // if the device pixel ratio doesnt match up, use the 1x asset\n el[i].style.backgroundImage = \"url('\" + arr[i].src + \"')\"; // defining gallery slide image via arr.src prop\n }\n }\n // if prefs.retina is false, use the 1x image asset.\n else {\n el[i].style.backgroundImage = \"url('\" + arr[i].src + \"')\"; // defining gallery slide image via arr.src prop\n }\n\n el[i].classList.add( arr[i].name, \"slide\" ); // cycle through array.name values to assign as class to element\n el[i].style.backgroundRepeat = \"no-repeat\";\n el[i].style.height = \"100%\";\n el[i].style.margin = \"0\";\n }\n }\n else {\n console.log(\"Check el element is assigned to correct querySelectorAll value.\");\n }\n }", "function displayPhotos() {\n loader.hidden = true;\n photos.forEach((photo) => {\n // Create Unspalsh page Link for the image\n const imageLink = document.createElement(\"a\");\n imageLink.setAttribute(\"href\", photo.links.html);\n imageLink.setAttribute(\"target\", \"_blank\");\n\n // Create image element\n const img = document.createElement(\"img\");\n img.setAttribute(\"src\", photo.urls.regular);\n img.setAttribute(\"alt\", photo.alt_description);\n img.setAttribute(\"title\", photo.alt_description);\n\n imageLink.appendChild(img);\n imageContainer.appendChild(imageLink);\n\n //event listner for image\n img.addEventListener(\"load\", imageLoaded);\n });\n}", "function initializeSlider() { // Invoked only when the page is loaded in the browser\r\n\thero.style.backgroundImage = 'url(\"' + backgroundImg[0] + '\")'; // The hero image is the first one in the array\r\n\tfor (var j = 0; j < backgroundImg.length; j++) {\r\n\t\tpictures[j].style.backgroundImage = 'url(\"' + backgroundImg[j] + '\")'; // Set the images in the preview \r\n\t}\r\n\tupdateSlider(0, 4); // Always shows the first 5 images\r\n}", "initSlideshow() {\n this.imagesLoaded = 0;\n this.currentIndex = 0;\n this.setNextSlide();\n this.slides.each((idx, slide) => {\n $('<img>').on('load', $.proxy(this.loadImage, this)).attr('src', $(slide).attr('src'));\n });\n }", "initSlideshow() {\n this.imagesLoaded = 0;\n this.currentIndex = 0;\n this.setNextSlide();\n this.slides.each((idx, slide) => {\n $(\"<img>\")\n .on(\"load\", $.proxy(this.loadImage, this))\n .attr(\"src\", $(slide).attr(\"src\"));\n });\n }", "function gallery(){\r\n\r\n showName();\r\n\r\n\r\n //create the images to display in the gallery\r\n\r\n for (i = 1; i <= 60; i++){\r\n\r\n //create a string adding the images directory and looping through the filename numbers\r\n\r\n //loop through images 1-9 due to the extra character space added after the number 9\r\n if (i < 10){\r\n var mySlides = \"../static/javapic/images/pdxcg_0\" + i + \".jpg\";\r\n\r\n }\r\n\r\n //loop through all image after the number 9\r\n if(i > 9){\r\n var mySlides = \"../static/javapic/images/pdxcg_\" + i + \".jpg\";\r\n\r\n\r\n //ignore missing file 42 and keep going\r\n if( i===42){\r\n continue;\r\n }\r\n }\r\n\r\n //create an <li> in javascript\r\n var li = document.createElement(\"LI\");\r\n\r\n //create an image in javascript\r\n var img = document.createElement(\"IMG\");\r\n img.setAttribute(\"src\", mySlides);\r\n\r\n //place the image in the <li> \r\n li.appendChild(img);\r\n\r\n //place the <li> in the gallery\r\n document.getElementById(\"gallery\").appendChild(li);\r\n\r\n \r\n }\r\n\r\n}", "function load_apps_info() {\n //identify carousel container\n var $carousel_container = $('.apps_carousel'); \n //set up the gathered images\n for(var i = 0; i < apps_array.length; i++){\n //not sure about adding 'real' class here\n image_array.push($('<img>').addClass('real').attr('src', apps_array[i].picture_source));\n $('#image_container').append(image_array[i]);\n }\n //initialize pictures\n initialize_app_pictures();\n //add the number links to the number bar\n create_number_links();\n //initialize the link buttons and modal\n update_modal_and_links(current_app_index);\n}", "function main(){\n\t//Initialice with first episode\n\tvar sel_episodes = [1]\n\t//collage(); //Create a collage with all the images as initial page of the app\n\tpaintCharacters();\n\tpaintEpisodes();\n\tpaintLocations(sel_episodes);\n}", "function showSlides() {\n slideIndex++;\n showSlidesByClick(slideIndex);\n}", "loadImages(): void {\n let self = this;\n let items = this.getState().items;\n for (let i = 0; i < items.length; i++) {\n let item: ItemType = items[i];\n // Copy item config\n let config: ImageViewerConfigType = {...item.viewerConfig};\n if (_.isEmpty(config)) {\n config = makeImageViewerConfig();\n }\n let url = item.url;\n let image = new Image();\n image.crossOrigin = 'Anonymous';\n self.images.push(image);\n image.onload = function() {\n config.imageHeight = this.height;\n config.imageWidth = this.width;\n self.store.dispatch({type: types.LOAD_ITEM, index: item.index,\n config: config});\n };\n image.onerror = function() {\n alert(sprintf('Image %s was not found.', url));\n };\n image.src = url;\n }\n }", "function setupsteps() {\n\t\tsteps = [];\n\t\tfor (var i = 0; i < imgarray.length; i++) {\n\t\t\tsteps.push(new zoom_img(imgarray[i]));\n\t\t}\n\t}", "function setMain(){\r\n var slides = document.getElementById(\"slides\");\r\n var mainImage = document.createElement(\"img\");\r\n var whichImage = Math.floor(Math.random()*6)\r\n mainImage.src= thumbImages[whichImage];\r\n slides.appendChild(mainImage);\r\n mainImage.className = \"mainImage\";\r\n}", "function nextImage () {\n slideIndex = slideIndex + 1\n showSlides(slideIndex)\n}", "function displayPhotos() {\n loadedImages = 0;\n // set totalImages to the length of the array\n totalImages = photosArray.length;\n // Run function for each obj in photosArray\n photosArray.forEach((photo) => {\n // Create a link to unsplash\n const link = document.createElement(\"a\");\n // link.setAttribute(\"href\", photo.links.html);\n // link.target = \"_blank\";\n setAttributes(link, {\n href: photo.links.html,\n target: \"_blank\",\n });\n // Create an image tag to hold the image\n const image = document.createElement(\"img\");\n // image.src = photo.urls.regular;\n // image.setAttribute(\"alt\", photo.alt_description);\n // image.title = photo.alt_description;\n setAttributes(image, {\n src: photo.urls.regular,\n alt: photo.alt_description,\n title: photo.alt_description,\n });\n // Event Listener, check when each image has loaded\n image.addEventListener(\"load\", imageLoaded);\n // Put image into link, and then put both into the imageContainer\n link.appendChild(image);\n imageContainer.appendChild(link);\n });\n}", "function displaySlides(num) {\n var i;\n\n //saving all slideImages to variable as an [array]\n var slides = document.getElementsByClassName(\"slideImages\");\n //saving all thumbnail images to variable as an [array]\n var thumbs = document.getElementsByClassName(\"thumbnails\");\n\n // allows the user to move forwards and\n // backwards infinitely in a circular manner.\n // by checking if the argument \"num\" is within slides.length\n if (num > slides.length) {\n slideIndex = 1;\n }\n if (num < 1) {\n slideIndex = slides.length;\n }\n\n // Iterate through slides array and set all images to display:none\n //(without this for loop, images will be displayed incorrectly\n // , as they will remain on the screen)\n for (i = 0; i < slides.length; i+=1) {\n slides[i].style.display = \"none\";\n }\n //Selects image from slides array based on slideIndex - 1\n //(i.e image 9 will have an index of 8)\n // and changes the images display property to block,\n // and displays it in the center of the screen\n slides[slideIndex - 1].style.display = \"block\";\n}", "function slideShow (containerCount, imgsPerContainer) {\n for (let container = 0; container < containerCount; container++) {\n window.setInterval(function () {\n const id = `container-${container}`;\n const imgNum = Math.floor(Math.random() * imgsPerContainer) + container * imgsPerContainer;\n const imgNumPath = `http://letsmaketheworldabetterplace.org/img/${imgNum}.jpg`;\n document.getElementById(id).setAttribute('src', imgNumPath);\n }, 1000 + container * 333); // repeat forever, changing image name every 2-4 seconds\n }\n }", "function renderPosters(movielist) {\n\n var baseURL = \"https://image.tmdb.org/t/p/\";\n var imageSize = \"w500\";\n // console.log(\"in function renderPosters\", movielist);\n\n var posterURLArray = [];\n\n\n\n // create URL Array\n for (let i = 0; i < movielist.length; i++) {\n // console.log(movielist[i]['poster_path']);\n var posterPath = movielist[i]['poster_path'];\n var fullPath = baseURL + imageSize + posterPath;\n posterURLArray.push(fullPath);\n }\n\n console.log(posterURLArray);\n\n // print pictures to DIV movielist\n for (let i = 0; i < posterURLArray.length; i++) {\n var anchorTag = $(\"<a>\");\n anchorTag.addClass(\"carousel-item\");\n\n var imageTag = $(\"<img>\");\n imageTag.attr(\"src\", posterURLArray[i]);\n imageTag.attr(\"alt\", \"somethingOutOFcourtesy\");\n imageTag.addClass(\"posterImg\");\n\n anchorTag.append(imageTag);\n $(\"#movieList\").append(anchorTag);\n console.log(\"appended?\", anchorTag);\n }\n\n // initialize carousel for materialcss\n $('.carousel').carousel();\n\n}", "function showSlides(n, interactedGalleryId) {\n for (let slideCounter = 0; slideCounter < galleries.length; slideCounter++) {\n // current gallery id, for example \"div1\"\n const currentGalleryId = 'div' + slideCounter;\n\n // the current gallery within the loop\n let gallery = document.querySelector('#div' + slideCounter);\n\n // all the slides in this gallery\n let slides = gallery.querySelectorAll('.mySlides');\n\n // get the thumbnails of this gallery\n let thumbs = gallery.querySelectorAll('.demo');\n\n // only apply this rule when it's the currently interacted gallery\n // as in: I've pressed prev or next on this gallery\n if (interactedGalleryId === currentGalleryId && n > slides.length) {\n slideIndex[slideCounter] = 1;\n }\n\n // only apply this rule when it's the currently interacted gallery\n // as in: I've pressed prev or next on this gallery\n if (interactedGalleryId === currentGalleryId && n < 1) {\n slideIndex[slideCounter] = slides.length;\n }\n\n // set all slides to display 'none'\n for (let i = 0; i < slides.length; i++) {\n slides[i].style.display = 'none';\n }\n\n // set all thumbs from \" active\" to \"\"\n for (let i = 0; i < thumbs.length; i++) {\n thumbs[i].className = thumbs[i].className.replace(' active', '');\n }\n\n // grab the correct slide and set it to \"block\"\n slides[slideIndex[slideCounter] - 1].style.display = 'block';\n // grab the correct thumb and set it to \" active\"\n thumbs[slideIndex[slideCounter] - 1].className += ' active';\n }\n}", "function displayPhotos() {\n totalImages = photosArray.length;\n /* runs function for each object in the photosArray */\n photosArray.forEach((photo) => {\n /* <a> for Unsplash */\n const item = document.createElement(\"a\");\n setAttributes(item, {\n href: photo.links.html,\n target: \"_blank\",\n });\n /* Create image for photos */\n const img = document.createElement(\"img\");\n setAttributes(img, {\n src: photo.urls.regular,\n alt: photo.alt_description,\n title: photo.alt_description,\n });\n /* Event listener for finished loading */\n img.addEventListener(\"load\", imageLoad)\n /* puts image inside anchor then both inside imageContainer */\n item.appendChild(img);\n imageContainer.appendChild(item);\n });\n}", "function startView() {\n // LOOP THROUGH ARRAY OF LINKS AND DISPLAY IMAGE\n $links.each(function(index, item) {\n\n // Each time an image link is clicked, use that image link to\n // to create an image and display it in the viewer\n $(item).click(function(event) {\n event.preventDefault();\n currentIndex = index;\n var link = event.currentTarget;\n\n $viewer.show();\n createImage(link);\n });\n })\n\n\n\n // CLOSE GALLERY VIEWER\n // ----------------------------------------\n\n $closeviewer.on('click touch', function(event) {\n event.stopPropagation();\n $viewer.fadeOut(200);\n });\n\n // Close gallery viewer container on click anywhere within the container\n $viewer.click(function() {\n $viewer.fadeOut(200);\n });\n\n // Prevent image container from closing on click by preventing bubbling\n $imageviewer.click(function(event) {\n event.stopPropagation();\n });\n\n\n // SWIPING CAPABILITIES\n // ----------------------------------------\n\n // SWIPE UP/DOWN - Closes gallery viewer\n $viewer.swipe({\n swipeDown: function() {\n $viewer.fadeOut(200);\n }\n });\n\n $viewer.swipe({\n swipeUp: function() {\n $viewer.fadeOut(200);\n }\n });\n\n // SWIPE LEFT - Displays next image\n $viewer.swipe({\n swipeLeft:function() {\n nextImage();\n }\n });\n\n // SWIPE RIGHT - Displays previous image\n $viewer.swipe({\n swipeRight:function() {\n prevImage();\n }\n });\n\n // TAP - Displays next image\n $imageviewer.swipe({\n tap:function(event) {\n event.preventDefault();\n event.stopPropagation();\n nextImage();\n }\n });\n\n\n // NEXT/PREVIOUS BUTTONS\n // ----------------------------------------\n\n // NEXT BUTTON - Displays next image\n $next.click(function(event) {\n event.stopPropagation();\n\n nextImage();\n });\n\n\n\n // PREVIOUS BUTTON - Displays previous image\n $prev.click(function(event) {\n event.stopPropagation();\n\n prevImage();\n });\n\n\n // ARROWS LEFT/RIGHT - Switch images\n // ----------------------------------------\n\n $(document).keydown(function(e) {\n switch(e.which) {\n case 37: // left\n prevImage();\n e.preventDefault(); // prevent the default action (scroll / move caret)\n break;\n\n case 39: // right\n nextImage();\n e.preventDefault(); // prevent the default action (scroll / move caret)\n break;\n }\n });\n}", "function nextImage(){\r\n\t\t\tif (i<image.length) {\r\n\t\t\t\ti= i+1;\r\n\t\t\t}else{\r\n\t\t\t\ti = 1;\r\n\t\t\t}\r\n\t\t\t slider_content.innerHTML = \"<img class=imgslide src=\"+image[i-1]+\" >\";\r\n\r\n\t\t}", "function displayPhotos () {\r\n imagesLoaded=0;\r\n totalImages = photosArray.length;\r\n// run function for each for each object in photosArray\r\n photosArray.forEach((photo) => {\r\n // create <a> to link to unsplash\r\n const item = document.createElement('a');\r\n // item.setAttribute('href', photo.links.html)\r\n // item.setAttribute('target', '_blank');\r\n setAttributes(item, {\r\n href: photo.links.html,\r\n target: '_blank'\r\n })\r\n // create <img> for photo\r\n const img = document.createElement('img');\r\n // img.setAttribute('src', photo.urls.regular);\r\n // img.setAttribute('alt', photo.alt_description);\r\n // img.setAttribute('title', photo.alt_description);\r\n setAttributes(img, {\r\n src : photo.urls.regular,\r\n alt: photo.alt_description,\r\n title: photo.alt_description\r\n })\r\n // add eventlistener, check when each load is finished\r\n img.addEventListener('load', imageLoaded);\r\n // put <img> inside <a> and put both inside of imageContainer\r\n item.appendChild(img);\r\n imageContainer.appendChild(item);\r\n })\r\n }", "function displayPhotos(){\n //13 reset imagesLoaded = 0\n imagesLoaded = 0;\n //10 \n totalImages = photosArray.length;\n //Run Function for eache pbject in photosArray\n photosArray.forEach((photo) => {\n //Create <a> to link to Unsplash\n const item = document.createElement('a');\n // item.setAttribute('href' , photo.links.html);\n // item.setAttribute('target' , '_blank');\n setAttributes(item, {\n href: photo.links.html,\n target: '_blank'\n });\n // Create <img> for photos\n const img = document.createElement('img');\n // img.setAttribute('src' , photo.urls.regular);\n // img.setAttribute('alt' , photo.alt_description);\n // img.setAttribute('title' , photo.alt_description);\n setAttributes(img, {\n src: photo.urls.regular,\n alt: photo.alt_description,\n title: photo.alt_description\n });\n //7 Event Listener, Check when each if finished loading\n img.addEventListener('load', imageLoaded);\n // Put <img> inside <a>, then put both inside imageContainer Element\n item.appendChild(img);\n imageContainer.appendChild(item);\n\n });\n}", "function addImages() {\n var images = ['heroImage', 'legacyLogo'];\n var img = null;\n for (var i = 0; i < images.length; i++) {\n var key = companyInfo['key'];\n if (companyInfo[images[i]].length > 0) {\n var url = 'https://media.licdn.com/media' + companyInfo[images[i]];\n img = $('<img class=\"recruiting-token-image\" id=\"' + images[i] + '-' + key + '\">');\n $(img).attr('src', url);\n img.data('file', null);\n img.data('name', images[i] + '-' + key);\n img.data('saved', false);\n img.data('scraped', true);\n createThumbnail(img, 'company-image-container');\n }\n }\n}", "getSliderImages()\n {\n const images = [\n { image: slideImg2},\n { image: slideImg4},\n { image: slideImg7},\n { image: slideImg8},\n { image: slideImg7},\n ];\n return images;\n }", "function initPictures() {\nif(DEBUG) alert('initPictures()');\n\tpictures = new DocumentCollection();\n\tpictures.assignEvent(appName);\n\tpictures.load();\n}", "mount() {\n\t\t\tComponents.Slides.getSlides( true, false ).forEach( slide => {\n\t\t\t\tconst img = find( slide, 'img' );\n\n\t\t\t\tif ( img && img.src ) {\n\t\t\t\t\tcover( img );\n\t\t\t\t}\n\t\t\t} );\n\n\t\t\tSplide.on( 'lazyload:loaded', img => { cover( img ) } );\n\t\t}", "function showSlides(n) {\n var i;\n var color = [\"rgb(239,73,48)\", \"rgb(4,136,230)\", \"rgb(26,26,26)\"];\n var path = \"https://jiade-tech2020.en.made-in-china.com/product\";\n var paths = [\n \"/odrEBQJksTWL/China-Jd-20A06-1-Fat-Tire-48V-10-4ah-11-6ah-14-5ah-16ah-Lithium-Battery-Power-Folding-Electric-Bicycle.html\",\n \"/vdRmSkEchahH/China-Jd-20A06-2-Fat-Tire-Foldable-500W-750W-1000W-Electric-Bike-Rear-Motor-with-Lithium-Battery.html\",\n \"/xFRnvaEJTGcb/China-Jd-20A06-3-Folding-Fat-Tire-Ebike-48V-500W-Fold-Ebike-Fat-Tire-Adult-Electric-Bicycle.html\",\n ];\n var slides = document.getElementsByClassName(\"mySlides\");\n var dots = document.getElementsByClassName(\"dot\");\n var action = document.getElementById(\"buy\");\n if (n > slides.length) {\n slideIndex = 1;\n }\n if (n < 1) {\n slideIndex = slides.length;\n }\n for (i = 0; i < slides.length; i++) {\n slides[i].style.display = \"none\";\n }\n for (i = 0; i < dots.length; i++) {\n dots[i].className = dots[i].className.replace(\" active\", \"\");\n }\n slides[slideIndex - 1].style.display = \"block\";\n dots[slideIndex - 1].className += \" active\";\n action.style.backgroundColor = color[slideIndex - 1];\n action.href = path + paths[slideIndex - 1];\n}", "function initializeImageList(imageList) {\n pageObject.imagesList = imageList;\n pageObject.thumbnailList = thumbnailList;\n\n $(\".gallery-holder\").on(\"click tap\", function(evt) {\n $(\".gallery-holder\").css(\"display\", \"none\");\n $(\".gallery-background\").css(\"display\", \"none\");\n Android.handleBackButton();\n });\n\n $(\".gallery-closer-holder\").on(\"click tap\", function(evt) {\n evt.stopPropagation();\n $(\".gallery-holder\").css(\"display\", \"none\");\n $(\".gallery-background\").css(\"display\", \"none\");\n Android.handleBackButton();\n });\n\n $(\".gallery-image-holder img\").on(\"click tap\", function(evt) {\n evt.stopPropagation();\n const screenWidth = $(window).width();\n let index = pageObject.imageListIndex;\n if(evt.clientX < screenWidth / 2) {\n if(index == 0) index = pageObject.imagesList.length;\n openGallery(index - 1);\n } else {\n if(index == imageList.length - 1) index = -1;\n openGallery(index + 1);\n }\n });\n\n // hard codedly assign image sources to each element\n $(\".main-picture-holder img\").attr(\"src\", pageObject.thumbnailList[0]);\n $(\".main-picture-holder img\").css(\"opacity\", 0.0);\n $(\".main-picture-holder img\").on(\"load\", function(evt) {\n $(evt.target).fadeTo(300, 1.0);\n console.log(evt.target);\n });\n $(\".main-picture-holder img\").on(\"click tap\", function(evt) {\n openGallery(0);\n });\n $(\".single_thumbnail img\").each((i, element) => {\n const index = parseInt(i);\n $(element).attr(\"src\", pageObject.thumbnailList[index + 1]);\n $(element).css(\"opacity\", 0);\n $(element).on(\"load\", function(evt) {\n $(evt.target).fadeTo(300, 1.0);\n });\n $(element).on(\"click tap\", (evt) => {\n openGallery(index + 1)\n });\n });\n}", "function createGallery(gallery) {\n let order = gallery.order;\n let COUNT = 3;\n $('#title').append(gallery.title);\n $('#description').append(gallery.description);\n let content = \"\";\n for (var i = gallery.start; i <= gallery.end; i++) {\n if (order) {\n content += `<div class=\"col s12 m6 l4 center-align test\"><img class=\"thumbnail card hoverable responsive-img\" data-filename=\"${gallery.filename}\" data-index=\"${i}\" id=\"i${i}\" src=\"images/${gallery.filename}/${gallery.filename}-${i}.jpg\"></div>`;\n if (i % COUNT === 0 ) {\n $('#imagesOrder').append(`<div class=\"row imageRows\"> ${content} </div>`);\n content = \"\";\n disapearingImages(i);\n\n }\n } else {\n $('#imagesNoOrder').append(`<div class=\"card hoverable\"><div class=\"card-image\"><img class=\"thumbnail\" data-filename=\"${gallery.filename}\" data-index=\"${i}\" id=\"i${i}\" src=\"images/${gallery.filename}/${gallery.filename}-${i}.jpg\"></div></div>`);\n Materialize.fadeInImage(`#i${i}`);\n }\n }\n\n\n setTimeout(function() { Materialize.showStaggeredList('#menuList');}, 1000 );\n setTimeout(function(){$('.tap-target').tapTarget('open');}, 1000000) //timer for home screen for dialog.\n\n $('img').click(function(e) {\n let indexI = parseInt(e.target.getAttribute('data-index'));\n let filename = e.target.getAttribute('data-filename');\n let galleryS = JSON.parse(localStorage.getItem('g'));\n let gallery = findGallery(galleryS, filename);\n let final = generateSlides(gallery, indexI);\n var offset = $(this).offset();\n openGalleryFromPhoto(final.slides, {showHideOpacity: true, index: indexI - 1, getThumbBoundsFn: function(i) { \n var thumbnail = $('#i'+ (i + 1))[0], // find thumbnail\n pageYScroll = window.pageYOffset || document.documentElement.scrollTop,\n rect = thumbnail.getBoundingClientRect(); \n\n return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};\n }});\n });\n\n if (window.innerWidth >= 600) {\n $('.imageRows').addClass('valign-wrapper');\n }\n }", "function displayExampleThumbs() {\n // called from init()\n EXAMPLE_ALBUM.forEach(function(currentImage) {\n // Create thumbnail div elements\n let thumb = document.createElement(\"div\");\n thumb.id = `thumb-${currentImage.albumId}-${currentImage.id}`;\n thumb.classList.add(\"thumb\");\n thumb.style.backgroundImage = `url('${currentImage.url}')`;\n thumb.alt = currentImage.message;\n // Event listener to draw clicked thumb to canvas\n thumb.addEventListener(\"click\", function(event) {\n canvasImage(event.target);\n document.querySelector(\"#message-input\").value = \"\"; // clears custom message input upon new image selected\n });\n // Append thumb to thumbnail div wrapper\n exampleThumbsWrapper.append(thumb);\n });\n}", "function nextImage(event)\n\t\t{\n\t\t\t//check that the counter does not exceed our array size\n\t\t\tif(x == (data.images.length - 1))\n\t\t\t{\n\t\t\t\tx = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tx++;\n\t\t\t}\n\t\t\t//create another block of code containing the next image in line\n\t\t\t//set the pages gallery tag to our new data\n\t\t\tvar info = '';\n\t\t\tinfo += '<p><img src = \"' + currentImage[x] + '\"alt=\"' + currentDescription[x] + '\"></p>';\n\t\t\tinfo += '<h3>' + currentTitle[x] + '</h3>';\n\t\t\tinfo += '<p>' + currentDescription[x] + '</p>';\n\t\t\tdocument.querySelector('#gallery article').innerHTML = info;\n\t\t}", "function displayPhotos() {\r\n imagesLoaded = 0;\r\n totalImage = photoArray.length;\r\n \r\n //run function for each array in photoArray\r\n photoArray.forEach((photo) => {\r\n //create <a> to link to unsplash\r\n const item = document.createElement('a');\r\n // item.setAttribute('href', photo.links.html);\r\n // item.setAttribute('target', '_blank');\r\n setAttributes(item, {\r\n href: photo.links.html,\r\n target: '_blank',\r\n });\r\n //create <img> for photo\r\n const img = document.createElement('img');\r\n // img.setAttribute('src', photo.urls.regular);\r\n // img.setAttribute('alt', photo.alt_description);\r\n // img.setAttribute('title', photo.alt_description);\r\n setAttributes(img, {\r\n src: photo.urls.regular,\r\n alt: photo.alt_description,\r\n title: photo.alt_description,\r\n });\r\n //eventlistener , check when each is finish loading\r\n img.addEventListener('load', imageLoaded);\r\n // put <img> inside <a>, then put both inside image-container\r\n item.appendChild(img);\r\n imageContainer.appendChild(item);\r\n });\r\n}", "createImages() {\n var html = `\n <ul class=\"image-list\">\n ${this._images.map(image => `\n <li class=\"item\" style=\"background-image:url(${image})\" id=\"${image}\">\n </li>`).join('\\n')}\n </ul>\n `;\n\n this.render(html);\n }", "function displayPhotos() {\n // Run the function for each object in photosArray\n photosArray.forEach((photo) => {\n // Create <a> to link to Unsplash\n const item = document.createElement(\"a\");\n setAttributes(item, {\n href: photo.links.html,\n blank: \"_blank\",\n });\n // Create <img> for photo\n const img = document.createElement(\"img\");\n setAttributes(img, {\n src: photo.urls.regular,\n alt: photo.alt_description,\n title: photo.alt_description,\n });\n // Put <img> inside <a> , then put both inside imageContainer ELement\n item.appendChild(img);\n imageContainer.appendChild(item);\n });\n}", "function load_images() {\n data.each(function(frame) {\n var imgs = []\n frame.images.each(function(imgstr) {\n var img = new Image(IMG_WIDTH, IMG_HEIGHT);\n img.src = \"/img/\" + imgstr;\n img.style.float = \"left\";\n imgs.push(img); \n });\n frame['imageobjs'] = imgs;\n }) \n }", "function setupGallery() {\n\t\t if($(\".photogallery\").length) {\n\t\t\tvar globaltitle = $(\".photogallery h2\").text();\n\t\t\t$(\".photogallery h2\").css(\"display\", \"none\");\n\t\t\t$('.photogallery ul').wrap(\"<div class=\\\"scroller\\\"/>\");\n\t\t\t$('.photogallery img').attr(\"width\", \"106\");\n\t\t\t$('.photogallery').append(\"<div class='viewer'></div>\");\n\t\t\t$(\".photogallery .scroller p\").css(\"display\", \"none\");\n\t\t\n\t\t\t$(\".photogallery .scroller img\").each(function() {\n\t\t\n\t\t\t $(this).fadeTo('fast', 0.5);\n\t\t\t\n\t\t\t $(this).click(function() {\n\t\t\t\t$(\".viewer\").html(\"<img src=\\\"\" + $(this).attr(\"src\") + \"\\\"/><p/>\");\n\t\t\t\tif($(this).parent().find(\"p\").text() != \"\") {\n\t\t\t\t $(\".viewer p\").html($(this).parent().find(\"p\").text());\n\t\t\t\t} else {\n\t\t\t\t $(\".viewer p\").html(globaltitle);\n\t\t\t\t}\n\t\t\t\t$(\".photogallery .selected\").fadeTo('slow', 0.5).removeClass(\"selected\");\n\t\t\t\t$(this).addClass(\"selected\").fadeTo('slow', 1.0);\n\t\t\t });\n\t\t\n\t\t\t $(this).hover(function() {\n\t\t\t\t$(this).fadeTo('fast', 1.0);\n\t\t\t }, function() {\n\t\t\t\tif(!$(this).hasClass(\"selected\")) {\n\t\t\t\t $(this).fadeTo('fast', 0.5);\n\t\t\t\t}\n\t\t\t });\n\t\t\n\t\t\t});\n\t\t\taddJScrollPane(\".photogallery .scroller\");\n\t\t\n\t\t\t$(\".photogallery ul li:first img\").click();\n\t\t }\n\t\t}", "function displayPhotos() {\n imagesLoaded = 0;\n totalImages = photosArray.length;\n\n // run function for each object in photosArray\n photosArray.forEach((photo) => {\n // create <a> to link to Unsplash\n const item = document.createElement('a');\n\n // set item attributes\n setAttributes(item, {\n href: photo.links.html,\n target: '_blank',\n });\n\n // create image for photo\n const img = document.createElement('img');\n\n // set image attributes\n setAttributes(img, {\n src: photo.urls.regular,\n alt: photo.alt_description,\n title: photo.alt_description,\n });\n\n // Event listerer, check when each is finished Loading\n img.addEventListener('load', imageLoaded);\n\n // put image inside anchor element <a>, the put both in imageContainer elements\n item.appendChild(img);\n imageContainer.appendChild(item);\n });\n}", "function generateSlides() {\n const parentEle = document.querySelector('#container');\n currentQContent = [dataVizPage[state.q_id], ...sharedContent]\n\n currentQContent.forEach((slide, i) => {\n const slideElement = document.createElement('div');\n //element position absolute\n slideElement.style.zIndex = `-${i}`;\n slideElement.style.position = 'absolute';\n slideElement.classList.add('slide');\n slideElement.setAttribute('id', `slide${state.q_id}-${i}`)\n if (i == 0) {\n slideElement.classList.add('center');\n } else {\n slideElement.classList.add('right');\n }\n slideElement.innerHTML = `${currentQContent[i].slide_text}`;\n parentEle.appendChild(slideElement);\n });\n\n}", "function displayPhotos(){\n imagesLoaded = 0 ;\n totallImages = photosArray.length ;\n photosArray.forEach( photo => {\n\n // Create <a> to link to Unsplash\n const item = document.createElement('a');\n setAttributes(item,{\n href:photo.links.html,\n terget:'_blank'\n });\n // item.setAttribute('href', photo.links.html);\n // item.setAttribute('target','_blank');\n\n //create <img> tag for every image\n const img = document.createElement('img');\n\n setAttributes(img,{\n src: photo.urls.regular,\n alt: photo.alt_description,\n title: photo.alt_description,\n });\n img.addEventListener('load',imageLoaded);\n // img.setAttribute('src',photo.urls.regular);\n // img.setAttribute('alt',photo.alt_description);\n // img.setAttribute('title',photo.alt_description);\n\n //append <img> to <a> and to img container \n item.appendChild(img);\n imageContainer.appendChild(item)\n });\n}", "function constructor() {\n self.getSlides();\n }", "function setNextImages() {\n // Get next scenes list\n let nextScenes = graph.AdjList.get(currentScene);\n\n // Add each scene\n for (let i = 0; i < nextScenes.length; i++) {\n let path = getImagePath(nextScenes[i].name);\n let img = $(\"<img>\").attr(\"src\", path);\n let label = $(\"<p></p>\").text(nextScenes[i].label);\n\n // Creating div to wrap each image (prevents blur overflow) and div to\n // wrap both scene image and text (for nice formatting)\n let blurDiv = $(\"<div></div>\").addClass(\"blurContainer\");\n let sceneDiv = $(\"<div></div>\").addClass(\"sceneDiv\");\n\n // On hover functions to change border color\n blurDiv.hover(function () {\n blurDiv.addClass(\"blurHover\");\n }, function () {\n blurDiv.removeClass(\"blurHover\");\n });\n\n // Add event listener to image\n img.addClass(\"next\");\n img.click(function (event) {\n changeScene(event);\n });\n\n // Building elements and adding them to the page\n blurDiv.append(img);\n sceneDiv.append(blurDiv);\n sceneDiv.append(label);\n $(\"#next-image-div\").append(sceneDiv);\n\n }\n\n}", "function initGalleries() {\n for (let slideCounter = 0; slideCounter < galleries.length; slideCounter++) {\n let gallery = document.querySelector('#div' + slideCounter);\n\n // get the prev and next slide button elements of this gallery\n let nextSlide = gallery.querySelector('.next');\n let prevSlide = gallery.querySelector('.prev');\n\n nextSlide.addEventListener('click', event => {\n const grandMotherElId = event.target.parentElement.parentElement.id;\n const position = grandMotherElId.substring(3, grandMotherElId.length);\n\n slideIndex[position] += 1;\n showSlides(slideIndex[position], grandMotherElId);\n });\n\n prevSlide.addEventListener('click', event => {\n const grandMotherElId = event.target.parentElement.parentElement.id;\n const position = grandMotherElId.substring(3, grandMotherElId.length);\n\n slideIndex[position] -= 1;\n showSlides(slideIndex[position], grandMotherElId);\n });\n }\n showSlides();\n}", "function getImages()\n\t{\n\t\tconsole.log('getImages')\n\t\tarr = []\n\t\tvar ajaxCall = $.get(targetUrl)\n\n\t\tajaxCall\n\t\t.done(function(response)\n\t\t{\t\n\t\t\t$.each(response.images, function(j)\n\t\t\t{\n\t\t\t\t$.each(response.images[j].array, (i)=>\n\t\t\t\t{\n\t\t\t\t\t\n\t\t\t\t\tlet tagArr = response.images[j].array[i].tag\n\t\t\t\t\tlet found = $.inArray(arrayKey, tagArr)\n\t\t\t\t\t//console.log(arrayKey, tagArr, found)\n\t\t\t\t\tif(found != -1)\n\t\t\t\t\t{\n\t\t \t\t\t\tarr.push(response.images[j].array[i])\n\t\t \t\t\t\tslide = \"<img id='slide' src='\" + arr[index].url + \"' alt=''>\" +\n\t\t \t\t\t\t\"<div class='img-title'><h3>\"+ arr[index].title + \"</h3></div>\"\n\t\t \t\t\t}\n\t\t \t\t\t\n\t\t\t\t})\n\t\t\t\t\n\t \t\t}) \n\t\t\tdisplaySlide($('#img-container'), slide)\n\t \t\tarrayLength = arr.length;\n\t\t\t\t\t\n\t\t})\n\t\t.fail(function(err)\n\t\t{\t\t\t\t\n\t\t\tthrow err\n\t\t})\n\n\t}", "function component() {\n const imgArray = [\n img1, img2, img3, img4, img5, img6, img7, img8,\n \"https://images.unsplash.com/photo-1541422348463-9bc715520974?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1651&q=80\",\n \"https://images.unsplash.com/photo-1501883824620-a2c97e2e319c?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1650&q=80\",\n \"https://images.unsplash.com/photo-1538898780761-268f71f67675?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1651&q=80\",\n \"https://images.unsplash.com/photo-1506755594592-349d12a7c52a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2033&q=80\",\n \"https://images.unsplash.com/photo-1520516620562-04b7d17e7500?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1650&q=80\",\n \"https://images.unsplash.com/photo-1460013477427-b0cce3e30151?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1650&q=80\"\n ]\n const i = generateRandomNumber(imgArray)\n return (\n <img alt=\"\" src={imgArray[i]} style={{ width: '30%', maxHeight: \"auto\", borderRadius: \"1pc\" }} />\n )\n}", "function ShowSiteImages(item, images, representative) {\r\n\r\n // Apply the image template to the images data source, placing them under the \"SiteImage\" div.\r\n // We first have to remove any existing images so that we don't add duplicates.\r\n var imageContainer = $('div.SiteImages', item);\r\n imageContainer.append($('#SiteImageTemplate').render(images));\r\n\r\n if (representative) {\r\n $('.SiteImageTimeStamp', imageContainer).hide();\r\n } else {\r\n $('.SiteImageTimeStamp', imageContainer).show();\r\n }\r\n\r\n // Add a loading spinner to each image that is disabled when the image is done loading.\r\n $('.SiteImage', imageContainer).each(function (i, e) {\r\n\r\n // Start the spinner.\r\n var spinner = $(e);\r\n spinner.spin(imageSpinnerOptions);\r\n\r\n // When the image loads, disable the spinner.\r\n $('img', spinner).load(function () {\r\n spinner.spin(false);\r\n })\r\n });\r\n\r\n // Start cycling images, if there were multiple.\r\n // Even if there was only one, we start the process to preserve formatting.\r\n imageContainer.cycle({\r\n fx: 'fade',\r\n next: '.SiteImages',\r\n timeout: 8000,\r\n pause: 1\r\n });\r\n\r\n }", "function createSlideshow(images) {\r\n let currentPosition = 0;\r\n clearInterval(timer);\r\n clearTimeout(deleteFirstPhotoDelay);\r\n\r\n //if there are more then 1 images stwich through the images and loop it\r\n if (images.length < 1) {\r\n document.getElementById(\"slideshow\").innerHTML = `\r\n <div class=\"slide\" style=\"background-image: url('${images[0]}')\"></div>\r\n <div class=\"slide\" style=\"background-image: url('${images[1]}')\"></div>\r\n `;\r\n currentPosition += 2;\r\n if (images.length == 2) {\r\n currentPosition = 0;\r\n }\r\n timer = setInterval(nextSlide, 3000);\r\n }\r\n //else keep the only one image and do nothing\r\n else {\r\n document.getElementById(\"slideshow\").innerHTML = `\r\n <div class=\"slide\" style=\"background-image: url('${images[0]}')\"></div>\r\n <div class=\"slide\"></div>\r\n `;\r\n }\r\n //change the image all 3 sec. and if you change the breed clean the timer and the images lenght\r\n setInterval(nextSlide, 3000);\r\n function nextSlide() {\r\n document\r\n .getElementById(\"slideshow\")\r\n .insertAdjacentHTML(\r\n \"beforeend\",\r\n `<div class=\"slide\" style=\"background-image: url('${images[currentPosition]}')\"></div>`\r\n );\r\n deleteFirstPhotoDelay = setTimeout(function() {\r\n document.querySelector(\".slide\").remove();\r\n }, 1000);\r\n if (currentPosition + 1 >= images.length) {\r\n currentPosition = 0;\r\n } else {\r\n currentPosition++;\r\n }\r\n }\r\n}", "function main() {\n NodeList.prototype.forEach = HTMLCollection.prototype.forEach = Array.prototype.forEach\n\n slideEls = document.querySelectorAll('.presentation > div')\n\n // Specific slide tech\n $('pre, code').each(function(i, block) {\n hljs.highlightBlock(block)\n });\n\n // Set up\n getSlideNumberFromUrlFragment()\n document.querySelector('.presentation').classList.add('visible')\n showSlide(true, true)\n onSlideEnter(slideEls[currentSlideNumber], true)\n\n document.body.addEventListener('keydown', onKeyDown)\n document.body.focus()\n}", "function addBootstrapPhotoGallery(images) {\n // TODO: MODULE_ADVENTURE_DETAILS\n // 1. Add the bootstrap carousel to show the Adventure images\n document.getElementById(\n \"photo-gallery\"\n ).innerHTML = `<div id=\"carouselExampleIndicators\" class=\"carousel slide\" data-ride=\"carousel\">\n <ol class=\"carousel-indicators\">\n <li data-target=\"#carouselExampleIndicators\" data-slide-to=\"0\" class=\"active\"></li>\n <li data-target=\"#carouselExampleIndicators\" data-slide-to=\"1\"></li>\n <li data-target=\"#carouselExampleIndicators\" data-slide-to=\"2\"></li>\n </ol>\n <div class=\"carousel-inner\">\n \n </div>\n <a class=\"carousel-control-prev\" href=\"#carouselExampleIndicators\" role=\"button\" data-slide=\"prev\">\n <span class=\"carousel-control-prev-icon\" aria-hidden=\"true\"></span>\n <span class=\"sr-only\">Previous</span>\n </a>\n <a class=\"carousel-control-next\" href=\"#carouselExampleIndicators\" role=\"button\" data-slide=\"next\">\n <span class=\"carousel-control-next-icon\" aria-hidden=\"true\"></span>\n <span class=\"sr-only\">Next</span>\n </a>\n</div>`;\n\n images.forEach((ele, index) => {\n if (index === 0) {\n //let carousel = document.querySelector(\".carousel-inner\");\n let div = document.createElement(\"div\");\n div.className = \"carousel-item active\";\n div.innerHTML = `<img class=\"img-responsive activity-card-image\" src=\"${ele}\">`;\n document.querySelector(\".carousel-inner\").appendChild(div);\n } else {\n //let carousel = document.querySelector(\".carousel-inner\");\n let div = document.createElement(\"div\");\n div.className = \"carousel-item\";\n div.innerHTML = `<img class=\"img-responsive activity-card-image\" src=\"${ele}\">`;\n document.querySelector(\".carousel-inner\").appendChild(div);\n }\n });\n console.log(images);\n}", "function ImagesInstance(name, filePath, description){\r\n this.name = name;\r\n this.filePath = filePath;\r\n this.description = description;\r\n this.numDisplayed = 0;\r\n this.numClicked = 0;\r\n ImagesInstance.list.push(this);\r\n}", "function slideshow(iii) {\n\t\treturn m(\".col-sm-12.blog-main\",\n\t\t\t[m(\".embed-responsive.embed-responsive-16by9\",\n\t\t\t\tm(\"iframe[frameborder='no'][height='600'][scrolling='no'][src=\" + iii.iframe + \"&autoStart=0&captions=1&navigation=1&playButton=1&randomize=0&speed=3&transition=fade&transitionSpeed=1'][width='800']\")\n\t\t\t),\n\t\t\t\tm(\"a.center-block[href=\" + iii.smugAlbum + \"]\",\n\t\t\t\t\tiii.smugAlbumName && m(\"h4\", \"Link to \" + iii.smugAlbumName + \" Album\")\n\t\t\t\t)\n\t\t\t]);\n\t}", "function addSlides () {\n vm.carousel.slides = [\n {'id':0, 'titulo': 'Bienvenido', 'image': 'images/productos/cacique.jpg'}\n ];\n promotion.queryFresh(\n function success (data) {\n vm.listpromotion = data;\n var count = 1;\n vm.listpromotion.forEach(function(promocion){\n promocion.dire = vm.ApiUrl + '/images/'+ promocion.url;\n console.log(promocion.dire);\n vm.carousel.slides.push({\n 'id':count,\n 'descripcion':promocion.descripcion,\n 'titulo':promocion.titulo,\n 'image': promocion.dire\n });\n count++;\n });\n\n\n }, function error (error) {\n }\n );\n }", "function populateFigures() {\n var filename;\n var currentFig;\n if (figureCount === 3) {\n for (var i = 1; i < 4; i++) {\n filename = \"images/IMG_0\" + photoOrder[i] + \"sm.jpg\";\n currentFig = document.getElementsByTagName(\"img\")[i - 1];\n currentFig.src = filename;\n }\n } else {\n for (var i = 0; i < 5; i++) {\n filename = \"images/IMG_0\" + photoOrder[i] + \"sm.jpg\";\n currentFig = document.getElementsByTagName(\"img\")[i];\n currentFig.src = filename;\n }\n }\n}", "function loadMainImages() {\nvar pg2 = document.getElementById('pg2');\n \n for (var i = 0; i < images.length; i++) {\n var anImage = document.createElement('img');\n anImage.setAttribute('src', images[i]);\n anImage.setAttribute('left', window.innerWidth);\n anImage.setAttribute('top', i*200);\n anImage.classList.add('mainImage');\n\n pg2.appendChild(anImage);\n DOMMainImages.push(anImage);\n anImage.addEventListener('click', function() {\n currentSection = \"aWork\";\n console.log(\"clicked\");\n });\n \n }\n}", "function generateCodeProjectImages(){\n\t//Set Header\n\tvar h2element = document.getElementById('codeProjectHeader');\n\tvar codeProjectHeader = 'Code Projects...';\n\th2element.textContent = codeProjectHeader;\n\n\t// Declare an array with the 3 fileNames\n\tvar codeProjectCollection = ['codeProjectGOT.jpg', 'codeProjectWater.jpg'];\n\n\t$('#codeProject0').attr('src', codeProjectCollection[0]);\n\t$('#codeProject1').attr('src', codeProjectCollection[1]);\n}", "function list(){\n for(var i = 1; i<=imgCount; i++)\n {\n images[i] = \"galleri/\" + dir + \"/medium-\" + i + \".jpg\";\n }\n}", "initSlides() {\n this.container = $(\"[data-slideshow]\");\n this.slides = this.container.find(\"img\");\n this.slides.each((idx, slide) => $(slide).attr(\"data-slide\", idx));\n }", "function slide(){\n index = (index+1)%(bilder.length);\n imgTag.src = bilder[index];\n}", "function Gallery(props) {\n const projects = [\n {\n src: \"./assets/burgerSS.jpg\",\n url: \"https://intense-castle-15409.herokuapp.com/\",\n title: \"Burger app\",\n description:\n \"√ - The Burger App allows you to choose a burger from the burgers listed. You can then save or devour the burger! Click the link and give it a try.\",\n },\n {\n src: \"./assets/project1.jpg\",\n url: \"https://jmuncrief.github.io/p1_location_info/\",\n title: \"City Info\",\n description:\n \"√ - The City Info application allows the user to look up city information using API calls. Perhaps you are visiting a new city and would like to know a few of the activities in the area during your stay. This app is for you then! Click the Project 1 button to proceed to the site.\",\n },\n {\n src: \"./assets/codeQuizSS.jpg\",\n url: \"https://stevensjones.github.io/codeQuizFourthEdition/\",\n title: \"The Code Quiz\",\n description:\n \"√ - The Code Quiz tests the users knowledge of coding related topics with a series of questions. Answer correctly and proceed, but miss a question and you will lose time! Click The Code Quiz button to proceed to the site and give it try.\",\n },\n {\n src: \"./assets/Project2SS.jpg\",\n url: \"https://glacial-taiga-04215.herokuapp.com/\",\n title: \"Game Tracker\",\n description:\n \" √ - The Game Tracker will allow both casual and enthusiast gamers to track games that they want to play, games that they are currently playing, and games that they have played in the past all in one database.\",\n },\n {\n src: \"./assets/readMeGeneratorSS.jpg\",\n url: \"https://github.com/StevenSJones/readMeGenSeventhEdition\",\n title: \"The Readme Generator\",\n description:\n \"√ - The Readme generator is a command line interface app or CLI that creates a readme.md file for your web development project. The readme.md is a necessity if you are creating a site as it tells any user how to operate the site. As a CLI there is not a page to visit, so I provided a link to the Github repository for the project instead.\",\n },\n {\n src: \"./assets/workDaySchedulerSS.jpg\",\n url: \"https://stevensjones.github.io/WorkDayCalenderFifthEdition/\",\n title: \"The Workday Scheduler\",\n description:\n \"√ - The Work Day Scheduler allows you to write out your plans for the work day; 9-5. You can create a todo and then get rid of it when it is comleted. It also has a jumbotron that lights up yellow if you visit the site in the morning hours and blue in the evening.\",\n },\n ]; //here we map over the items in the projects array and return one card for each iteration\n const content = projects.map((project, index) => {\n return (\n <Col key={index}>\n <Project\n title={project.title}\n url={project.url}\n src={project.src}\n description={project.description}\n />\n </Col>\n );\n });\n return (\n <Container>\n <Jumbotron className=\"jumbo-border\">\n <Container>\n <h1 className=\"color-welcome\">Gallery</h1>\n <hr />\n <p>\n This page is dedicated to showcasing 6 varying projects that I\n completed at the University of Arizona web-development program.\n Please take a moment to read a description of each project visit\n each site in turn by pressing the go to site button.\n </p>\n </Container>\n </Jumbotron>\n <Container>\n <Row>{content}</Row>\n </Container>\n </Container>\n );\n}", "function init() {\r\n // Variable for storing the images using the img tag - this is used for on page loading\r\n var numImg = document.getElementById(\"imgHolder\").getElementsByTagName(\"img\")\r\n .length;\r\n // Go through all of the numImg images\r\n for (var i = 1; i <= numImg; i++) {\r\n // Put an Image object in the array spot\r\n newImage[i] = new Image();\r\n // Since there is an image object, if I assign it a .src, it will go out and load it!\r\n newImage[i].src = \"assets/imagesgallery/gallery\" + i + \"big.jpg\";\r\n }\r\n // Set up first caption using the first element in the caption array\r\n document.getElementById(\"cap\").innerHTML = captionArray[0];\r\n}", "prepareSlides () {\n this.slides = this.htmlCollectionToArray(this.$refs.slides.children)\n\n // Probably timeout needed\n if (this.slidesCloned) {\n this.slidesClonedBefore = this.htmlCollectionToArray(this.$refs.slidesClonedBefore.children)\n this.slidesClonedAfter = this.htmlCollectionToArray(this.$refs.slidesClonedAfter.children)\n }\n\n for (const slide of this.slidesAll) {\n slide.classList.add('agile__slide')\n }\n }", "function displayPhotos() {\n // Run function for each object in photoArray\n photoArray.forEach((photo) => {\n // create <a> to link to unsplash\n const div = document.createElement('div');\n div.setAttribute('class', 'image-box');\n\n const item = document.createElement('a');\n setAttributes(item, {\n href: photo.links.html,\n target: '_blank',\n });\n // create <img> for photo\n const img = document.createElement('img');\n setAttributes(img, {\n src: photo.urls.regular,\n alt: photo.alt_description,\n title: photo.alt_description,\n });\n // Put image <img> in <a>, then put both inside imageContainer Element\n div.appendChild(item);\n item.appendChild(img);\n imageContainer.appendChild(div);\n });\n}", "function simulate_advertise_images() {\n display_advertise_images();\n}", "function loadImages() {\n if (surveyLength > 24) {\n surveyEnd();\n }\n\n lastIndex = [];\n\n lastIndex.push(randomIndex1);\n lastIndex.push(randomIndex2);\n lastIndex.push(randomIndex3);\n\n //Re-assigning the variables for each picture\n randomIndexGenerator();\n\n //While loop to prevent double choices AND no prior choice repeats\n while (randomIndex1 === lastIndex[0] || randomIndex1 === lastIndex[1] || randomIndex1 === lastIndex[2] || randomIndex2 === lastIndex[0] || randomIndex2 === lastIndex[1] || randomIndex2 === lastIndex[2] || randomIndex3 === lastIndex[0] || randomIndex3 === lastIndex[1] || randomIndex3 === lastIndex[2] || randomIndex1 === randomIndex2 || randomIndex1 === randomIndex3 || randomIndex2 === randomIndex3) {\n randomIndexGenerator();\n }\n //Makes leftImg's src property equal to the fileName of the indexed item\n leftImg.src = catalogArray[randomIndex1].filePath;\n centerImg.src = catalogArray[randomIndex2].filePath;\n rightImg.src = catalogArray[randomIndex3].filePath;\n\n //Adds 1 to the display tally property of the indexed object\n catalogArray[randomIndex1].tallyDisplayed += 1;\n catalogArray[randomIndex2].tallyDisplayed += 1;\n catalogArray[randomIndex3].tallyDisplayed += 1;\n\n}", "function displayPhotos() {\n // Run function for each object in photosArray\n photosArray.forEach(\n (photo) => {\n // Create <a> that link to Unsplash\n const imageLink = document.createElement('a');\n setAttributes(imageLink, {\n 'href': photo.links.html,\n 'target': '_black',\n });\n // Create <img> for photo\n const image = document.createElement('img');\n setAttributes(image, {\n 'src': photo.urls.regular,\n 'alt': photo.alt_desciption,\n 'title': photo.alt_description,\n });\n // Put <img> inside <a>, then put both inside imageContainer element\n imageLink.appendChild(image);\n imageContainer.appendChild(imageLink);\n }\n )\n}", "function displayPhotos() {\n imagesLoaded = 0;\n totalImages = photosArray.length;\n photosArray.forEach(photo => {\n let desc = photo.alt_description;\n let url = photo.links.html;\n let src = photo.urls.regular;\n\n // anchor for our image\n const item = document.createElement('a');\n setAttributes(item, {\n href: url,\n target: '_blank',\n });\n \n // <img> for our image\n const img = document.createElement('img');\n setAttributes(img, {\n src: src,\n alt: desc,\n title: desc,\n });\n \n // when the image is loaded\n img.addEventListener('load', hasImageLoaded);\n\n // add img to item; add item to image-container\n item.appendChild(img);\n imgContainer.appendChild(item);\n });\n}", "function slide_show() {\n // Set img src to the value of the image at iterator.\n img_element.src = images_list[iterator];\n name_element.innerHTML = names_list[iterator];\n desc_element.innerHTML = desc_list[iterator];\n\n // Update iterator\n if (iterator < images_list.length - 1){\n iterator++;\n } else {\n iterator = 0;\n }\n\n // Call function once time is due.\n setTimeout(\"slide_show()\", time);\n}", "function processData(list) {\n console.log(list); // list is an array of objects \n\n // Generate the set of image\n var imageSetContainer = document.createElement(\"div\");\n imageSetContainer.className = \"imageSet\";\n\n // Generate the Modal Image Gallery\n var modalContainer = document.createElement(\"div\");\n modalContainer.className = \"modal\";\n\n // Generate detailed HTML for the image set\n for (var i = 0; i < list.length; i++) {\n var imageDiv = document.createElement(\"div\");\n imageDiv.className = \"column\";\n var imageSmall = document.createElement(\"img\");\n imageSmall.src = list[i].ImageSmall;\n imageSmall.alt = list[i].Alt;\n imageSmall.className = \"hover-shadow cursor\";\n imageSmall.setAttribute(\"data-index\", i + 1);\n // click on the image on the background to open modal\n imageSmall.onclick = function () {\n openModal(modalContainer);\n currentSlide(modalContainer, this.getAttribute('data-index'));\n };\n\n imageDiv.appendChild(imageSmall);\n imageSetContainer.appendChild(imageDiv);\n }\n\n // Generate detailed HTML for the Modal Image Gallery\n var close = document.createElement(\"span\");\n close.innerHTML = \"&times\";\n close.className = \"close cursor\";\n\n // generate close modal\n close.onclick = function () {\n closeModal(modalContainer);\n };\n modalContainer.appendChild(close);\n\n // generate the modal content\n var modalContent = document.createElement(\"div\");\n modalContent.className = \"modal-content\";\n\n // generate the wide image\n for (var i = 0; i < list.length; i++) {\n var imageDiv = document.createElement(\"div\");\n imageDiv.className = \"mySlides\";\n var numbertextDiv = document.createElement(\"div\");\n numbertextDiv.className = \"numbertext\";\n numbertextDiv.innerHTML = (i + 1) + \" / \" + (list.length);\n var imageWide = document.createElement(\"img\");\n imageWide.src = list[i].ImageWide;\n imageWide.alt = list[i].Alt;\n\n imageDiv.appendChild(numbertextDiv);\n imageDiv.appendChild(imageWide);\n modalContent.appendChild(imageDiv);\n }\n\n // generate prev & next navigation, and caption \n var previous = document.createElement(\"a\");\n previous.className = \"prev\";\n previous.innerHTML = \"&#10094;\";\n //navigate to the previous image\n previous.onclick = function () {\n plusSlides(modalContainer, -1);\n };\n modalContent.appendChild(previous);\n var next = document.createElement(\"a\");\n next.className = \"next\";\n next.innerHTML = \"&#10095;\";\n // navigate to the next image\n next.onclick = function () {\n plusSlides(modalContainer, 1);\n };\n modalContent.appendChild(next);\n var captionContainer = document.createElement(\"div\");\n captionContainer.className = \"caption-container\";\n var caption = document.createElement(\"p\");\n caption.className = \"caption\";\n captionContainer.appendChild(caption);\n modalContent.appendChild(captionContainer);\n\n // generate the bottom images of modal\n for (var i = 0; i < list.length; i++) {\n var imageDiv = document.createElement(\"div\");\n imageDiv.className = \"column\";\n var imageWide = document.createElement(\"img\");\n imageWide.src = list[i].ImageWide;\n imageWide.alt = list[i].Alt;\n imageWide.className = \"demo cursor\";\n imageWide.setAttribute(\"data-index\", i + 1);\n imageWide.onclick = function () {\n currentSlide(modalContainer, this.getAttribute('data-index'));\n };\n imageDiv.appendChild(imageWide);\n modalContent.appendChild(imageDiv);\n }\n\n modalContainer.appendChild(modalContent);\n\n mainContent.appendChild(imageSetContainer);\n mainContent.appendChild(modalContainer);\n\n }", "function loopTitles(){\r\nimageDiv.src = titles[count % titles.length];\r\ncount += 1;\r\n}", "function changeSlide() {\n\n mainSlide.setAttribute(\"src\", slideArray[slideIndex]['url']);\n slideIndex++;\n if (slideIndex >= slideArray.length) {\n slideIndex = 0;\n }\n }", "function fillImages(){\n\tfor (var i = 0; i < planes.length; i++) {\n\t\tvar id = planes[i].id\n\t\tvar search = \"#\" + id + \" .slide-container\"\n\t\t$(search).css(\"background-image\", \"url('\" + buildUrl(id) + \"')\")\n\t\tconsole.log(buildUrl(id, slides[id]))\n\t\t\n\t}\n}", "function displayphotos(){\n imagesLoaded = 0;\n totalImages = photosArray.length;\n console.log('total images = ', totalImages);\n// Run function for each object in photoarray\n photosArray.forEach((photo) => {\n// Create <a> to link to Unsplash\nconst item = document.createElement('a');\nsetAttribute(item,{\n href: photo.links.html,\n target: '_blank',\n});\n//Create <img> for photo\nconst img = document.createElement('img');\nsetAttribute(img,{\nsrc: photo.urls.regular,\nalt: photo.alt_description,\ntitle: photo.alt_description,\n});\nimg.addEventListener('load', imageLoaded);\nitem.appendChild(img);\nimageContainer.appendChild(item);\n});\n}", "function plusSlides(num) {\n //add or minus by 1 to slideIndex depending on\n //whether the user clicks right or left on the image slides,\n //(-1 left ,+1 right)\n slideIndex += num;\n //and pass it as an arguement to displaySlides()\n displaySlides(slideIndex);\n}", "function displayPhotos(photosArray) {\n console.log(2);\n console.log(photosArray);\n photosArray.forEach(photo => {\n console.log(3);\n const item = document.createElement('a');\n // item.setAttribute('href', photo.links.html);\n // item.setAttribute('target', '_blank');\n setAttributes(item, {\n href: photo.links.html,\n target: '_blank'\n });\n const img = document.createElement('img');\n // img.setAttribute('src', photo.urls.regular);\n // img.setAttribute('alt', photo.alt_description);\n // img.setAttribute('title', photo.alt_description);\n setAttributes(img, {\n src:photo.urls.regular,\n alt: photo.alt_description,\n title: photo.alt_description\n });\n // append everything\n item.appendChild(img);\n imgContainer.appendChild(item)\n });\n}", "function displayPhotos() {\n imagesLoaded = 0;\n totalImages = photosArray.length;\n // Run function for each object in photosArray\n photosArray.forEach((photo) => {\n // Create <a> to link to unsplash\n const $item = $(`<a href=\"${photo.links.html}\" target=\"_blank\"></a>`);\n\n // Create <img> for photo\n const $img = $(\n `<img src=\"${photo.urls.regular}\" alt=\"${photo.alt_description}\" title=\"${photo.alt_description}\" />`\n );\n\n // Event Listener, check when each is finished loading\n $img.on('load', imageLoaded);\n\n // Put <img> inside <a> then put both inside imageContainer element\n $item.append($img);\n $imageContainer.append($item);\n });\n }", "function pageSetup() {\r\n document.getElementsByTagName(\"img\")[0].src = figFilename; // assign filename to img element\r\n createEventListener();\r\n}", "setImages() {\n this.img1 = createImage(640, 480);\n this.img2 = createImage(640, 480);\n this.img3 = createImage(640, 480);\n this.img4 = createImage(640, 480);\n }", "function showImagesEventHandler(e) {\n var app = UiApp.getActiveApplication();\n var panel = app.getElementById('panelForImages').clear();\n var info = Utilities.jsonParse(ScriptProperties.getProperty('info'));\n for (i in info) {\n if (info[i][0] == e.parameter.albumListBox) {\n var data = UrlFetchApp.fetch(URL + '/albumid/' + info[i][1], googleOAuth_()).getContentText();\n var xmlOutput = Xml.parse(data, false);\n var photos = xmlOutput.getElement().getElements('entry');\n for (j in photos) {\n panel.add(app.createImage(photos[j].getElement('content').getAttribute('src').getValue()));\n }\n }\n }\n return app;\n}", "prepareSlides () {\n\t\t\tthis.slides = this.htmlCollectionToArray(this.$refs.slides.children)\n\n\t\t\t// Probably timeout needed\n\t\t\tif (this.clonedSlides) {\n\t\t\t\tthis.slidesClonedBefore = this.htmlCollectionToArray(this.$refs.slidesClonedBefore.children)\n\t\t\t\tthis.slidesClonedAfter = this.htmlCollectionToArray(this.$refs.slidesClonedAfter.children)\n\t\t\t}\n\n\t\t\tfor (let slide of this.allSlides) {\n\t\t\t\tslide.classList.add('agile__slide')\n\t\t\t}\n\t\t}", "prepareSlides () {\n\t\t\tthis.slides = this.htmlCollectionToArray(this.$refs.slides.children)\n\n\t\t\t// Probably timeout needed\n\t\t\tif (this.clonedSlides) {\n\t\t\t\tthis.slidesClonedBefore = this.htmlCollectionToArray(this.$refs.slidesClonedBefore.children)\n\t\t\t\tthis.slidesClonedAfter = this.htmlCollectionToArray(this.$refs.slidesClonedAfter.children)\n\t\t\t}\n\n\t\t\tfor (let slide of this.allSlides) {\n\t\t\t\tslide.classList.add('agile__slide')\n\t\t\t}\n\t\t}", "function generateSlidesHTML(index, item) {\n return `<img class=\"slider-image ${index === 0 ? 'showing' : ''}\" src=${item.bg_image} id=\"slide${item.id}\">`\n}" ]
[ "0.7255615", "0.6701538", "0.6493436", "0.62895447", "0.627597", "0.6230609", "0.61865693", "0.6151827", "0.60887355", "0.601292", "0.5989343", "0.5983578", "0.59632605", "0.5953698", "0.5951431", "0.5932212", "0.59025717", "0.58852196", "0.58429545", "0.5817123", "0.58061314", "0.5795724", "0.5794538", "0.57915056", "0.57899976", "0.57677436", "0.5766955", "0.5760065", "0.5758444", "0.57572174", "0.57544875", "0.57245916", "0.57218546", "0.5720749", "0.5720174", "0.5664607", "0.56645405", "0.56574684", "0.56458896", "0.5619432", "0.5610874", "0.5610033", "0.56087554", "0.5607136", "0.55979687", "0.5595215", "0.55922025", "0.5591586", "0.5590314", "0.5586111", "0.5581119", "0.55735147", "0.5571763", "0.5564715", "0.5563161", "0.5541587", "0.5539821", "0.5532702", "0.5525969", "0.5523928", "0.5523499", "0.5518853", "0.5518153", "0.55112183", "0.55091935", "0.5501185", "0.5499431", "0.5497207", "0.54872584", "0.54800034", "0.5479567", "0.54770976", "0.5476147", "0.547185", "0.5468442", "0.54676497", "0.54674524", "0.5466938", "0.546625", "0.5466248", "0.54639995", "0.5460642", "0.54590124", "0.54575586", "0.54575104", "0.5456263", "0.5456103", "0.54538375", "0.54517853", "0.5451384", "0.5449452", "0.54446536", "0.54435337", "0.54426867", "0.54407036", "0.5440036", "0.5438568", "0.5435024", "0.5435024", "0.5434401" ]
0.74116576
0
HTTP Upload Appender for ngLogCustom module Uploads the logs that have a log level >= minLevel to postUrl in the specified interval. No uploads happen if no suitable logs have been produced.
function CatHttpLogAppender($http, $interval, $log, config, HTTP_LOGGER_NAME, LOG_LEVEL_ORDER) { var logger = $log.Logger(HTTP_LOGGER_NAME); if (typeof config.postUrl === 'undefined') { throw new Error('catHttpLogAppenderProvider requires definition of postUrl'); } var logs = []; this.report = function (level, group, message, memorySizes) { logs.push({ level: level, group: group, message: typeof message === 'string' ? message : message.toString(), memorySizes: memorySizes, timestamp: new Date().getTime() }); }; this.flush = function () { var minLevelOrder = LOG_LEVEL_ORDER[config.minLevel]; var logsToSend = []; angular.forEach(logs, function (logEntry) { if (LOG_LEVEL_ORDER[logEntry.level] >= minLevelOrder) { logsToSend.push(logEntry); } }); logs.length = 0; if (logsToSend.length > 0) { return $http.post(config.postUrl, logsToSend, config) .success(function () { logger.debug('Successfully uploaded logs.'); }) .error(function (data, status, headers, config, statusText) { logger.debug('Error uploading logs: ' + status + ' ' + statusText); }); } else { logger.debug('No logs to upload - skipping upload request.'); } }; $interval(this.flush, config.intervalInSeconds * 1000, 0, false); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function _writeLogsToServer(logLevel, loggingUrl) {\n var dataToSend;\n\n dataToSend = {\n logLevel: logLevel\n , logData : app.cache.logData\n };\n app.cache.logData = [];\n $.ajax({\n type: 'POST'\n , url: loggingUrl\n , data: dataToSend\n });\n }", "function sendLogList(logData) {\n var xhr = new XMLHttpRequest(),\n startTime = new Date().getTime();\n\n xhr.onreadystatechange = function () {\n var endTime = new Date().getTime(),\n consumption = endTime - startTime;\n\n if (xhr.readyState == 4) {\n\n // caps the maximum of response time\n if (consumption < config.logIntervalLimit) {\n\n // response time checks if it bigger than logResponseLimit\n // than increase the time of log interval\n if (consumption > config.logResponseLimit) {\n config.logIntervalUse *= 2;\n stopInterval();\n startInterval();\n\n // or decrease the time of log interval\n } else if (config.logIntervalUse > config.logIntervalMin) {\n config.logIntervalUse /= 2;\n stopInterval();\n startInterval();\n }\n }\n }\n };\n xhr.open('POST', config.server + 'rest/widgets/log', true);\n xhr.timeout = 5000;\n xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');\n xhr.send(JSON.stringify(logData));\n\n loggingList.length = 0;\n }", "async function upload(req) {\n const result = await streamUpload(req);\n req.body.image = result.secure_url;\n const logEntry = new LogEntry(req.body);\n const logger = await logEntry.save({\n new: true,\n });\n res.send(logger);\n }", "function sendData() {\n if (logQueue.length === 0) { return; }\n\n var baseUrl = loggerConfig.apiBaseUrl || '';\n\n var logReqCfg = {};\n logReqCfg.url = baseUrl + loggerConfig.apiUrl;\n logReqCfg.headers = {\n 'X-Requested-With': 'XMLHttpRequest'\n };\n logReqCfg.data = {\n device: 'browser',\n appver: loggerConfig.appVersion,\n locale: $locale.id,\n lang: $translate.use(),\n screen: $window.screen.availWidth + 'x' + $window.screen.availHeight,\n logs: logQueue.splice(0, Number.MAX_VALUE) // Send all logs in queue\n };\n\n // Apply sendData interceptors\n // TODO: Consider promises.\n // Current preference is to keep it simple and not introduce any async failures\n // that could interrupt the log request\n angular.forEach(reversedInterceptors, function(interceptor) {\n if (interceptor.sendData) { interceptor.sendData(logReqCfg); }\n });\n\n if (loggerConfig.isStubsEnabled) {\n $log.debug('%cServerLogger => ajax 200 POST ' + logReqCfg.url,\n 'background:yellow; color:blue', 'reqData:', logReqCfg.data);\n saveLogQueue();\n\n } else {\n var request = createXhr();\n request.open('POST', logReqCfg.url, true);\n request.timeout = Math.min(loggerConfig.loggingInterval, 60000);\n request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');\n angular.forEach(logReqCfg.headers, function(val, key) {\n request.setRequestHeader(key, val);\n });\n request.onreadystatechange = function xhrReadyStateChange() {\n if (this.readyState === 4) {\n var success = (this.status >= 200 && this.status < 400);\n if (!success && this.status !== 413) {\n // Put logs back on the front of the queue...\n // But not if the server is complaining the request size is too large\n // via 413 (Request Entity Too Large) error\n $log.debug('sendlog unsuccessful');\n logQueue.unshift.apply(logQueue, logReqCfg.data.logs);\n }\n saveLogQueue();\n }\n };\n request.send(angular.toJson(logReqCfg.data));\n request = null;\n }\n }", "function lemurlog_DoActualUpload_Log()\n{\n // before uploading - scrub the log files\n // remember to remove any search results that match\n // a query where any query term is blacklisted...\n \n lemurlog_upload_service = new lemurlog_uploadService();\n window.openDialog(\"chrome://lemurlogtoolbar/content/upload.xul\", \"LogTB-Upload\", \"chrome=yes,modal=no,centerscreen=yes,status=no,height=400,width=600\", window);\n}", "function postLogs(data, url) {\n makePost(config.backendUrl + url, data);\n\n localStorage.removeItem(\"actions\");\n localStorage.setItem(\"actionNumber\", \"0\");\n}", "function LogController($scope, pubsubService) {\n $scope.myLogEntries = [];\n var logRef = new Firebase('https://bnfirebase.firebaseio.com/log');\n\n logQuery = logRef.limit(5); // only 5 last log-entries\n\n logQuery.on('child_added', function(snapshot) {\n var value = snapshot.val();\n value.id = snapshot.name();\n $scope.myLogEntries.push( value );\n $scope.safeApply();\n });\n\n $scope.$on('log', function() {\n console.log(pubsubService.message);\n $scope.addLogEntry(pubsubService.message.userID,\n pubsubService.message.ticketID,\n pubsubService.message.title,\n pubsubService.message.action);\n }); \n\n $scope.getLogEntries = function() {\n return $scope.myLogEntries;\n }\n\n $scope.addLogEntry = function(userID, ticketID, title, action) {\n var timestamp = (new Date()).toGMTString();\n\n logRef.push({userID: userID,\n ticketID: ticketID,\n title: title,\n action: action,\n timestamp: timestamp\n });\n }\n\n $scope.safeApply = function(fn) {\n var phase = this.$root.$$phase;\n if (phase == '$apply' || phase == '$digest') {\n if (fn && (typeof(fn) === 'function')) {\n fn();\n }\n } else {\n this.$apply(fn);\n }\n };\n}", "watch() {\n this.timer = setInterval(() => this.upload(), (this.config.interval ? this.config.interval : 60000));\n }", "theTransporter(file, log_arr) { \n let payload;\n let { dumpToBacklog, transport_options } = this;\n \n if (!log_arr || log_arr.length < 1)\n return;\n \n try {\n payload = JSON.stringify({\n logs: log_arr\n });\n }\n catch(err) {\n console.log(err);\n return;\n }\n // seting the content length, which is mandatory with http request\n transport_options.headers['Content-Length'] = Buffer.byteLength(payload);\n // using http request for no dependencies\n let request = http.request(transport_options, (res) => {\n res.setEncoding('utf8');\n res.on('data', function (chunk) {\n // delete file once server responds with 200\n // other wise the server had a problem and we\n // need to backlog them\n console.log(\"logs sent!\");\n if (res.statusCode === 200 && JSON.parse(chunk).success === true)\n fs.unlink(file, (err) => {\n if (err) \n console.log(err);\n else\n console.log(`${file}: deleted`);\n });\n else\n dumpToBacklog(file, log_arr);\n\n // end http request\n request.end();\n });\n });\n \n request.write(payload);\n \n request.on('error', (err) => {\n // if there is an error then we dump to backlog\n // so we back log them instead of deleting them\n dumpToBacklog(file, log_arr);\n console.log(err);\n request.end();\n });\n }", "function handleLogUpload(evt) {\n var files = evt.target.files; // FileList object\n\n\t// files is a FileList of File objects. List some properties.\n\tvar output = [];\n\tvar file = files[0];\n\tvar reader = new FileReader();\n\n\t// If we use onloadend, we need to check the readyState.\n\treader.onloadend = function(evt) {\n\t\tif (evt.target.readyState == FileReader.DONE) { // DONE == 2\n\t\t\tparseLogFile(evt.target.result);\n\t\t\t// Validate not working at the moment\n\t\t\t//validateLog(initialBoard, evt.target.result);\n\t\t}\n\t};\n\treader.readAsText(file);\n}", "function sendLogsToServer() {\n IdbRTC.getLog().then((data) => {\n if (data && data.length > 0) {\n let counter = 0, tempArray = [], dynamicLength = data.length;\n while (dynamicLength > 0) {\n /* Length of array which will be added to 'tempArray' */\n let len = dynamicLength >= messagesPerPostCall ? messagesPerPostCall : data.length;\n /* From index for slicing the 'data' */\n let from = counter * messagesPerPostCall;\n /* To index for slicing the 'data' */\n let to = from + len;\n tempArray.push(data.slice(from, to));\n dynamicLength = dynamicLength - len;\n counter++;\n }\n tempArray.map((arr) => {\n /* Double check so as we do not increase 4xx error counts on ES servers. */\n arr.length > 0 && postCall(arr);\n });\n }\n });\n}", "function handleAdminLog(urlParts, response) {\n var file = urlParts.query.file;\n var filePath = config.logging.files.directory + \"/\" + file;\n if(!file.match(/^\\w+\\.log$/)) {\n response.end(\"wrong log file\");\n }\n response.writeHead(200, {\n \"Content-Type\": \"text/plain\",\n \"Cache-Control\": \"no-cache\",\n \"Content-Length\": fs.statSync(filePath).size\n });\n fs.createReadStream(filePath).pipe(response);\n}", "function HttpUploadProgressEvent() { }", "function HttpUploadProgressEvent() { }", "function HttpUploadProgressEvent() { }", "function postEventsToLoggly(parsedEvents) {\n if (!logglyConfiguration.customerToken) {\n if (logglyConfiguration.tokenInitError) {\n console.log('error in decrypt the token. Not retrying.');\n return context.fail(logglyConfiguration.tokenInitError);\n }\n console.log('Cannot flush logs since authentication token has not been initialized yet. Trying again in 100 ms.');\n setTimeout(function () { postEventsToLoggly(parsedEvents) }, 100);\n return;\n }\n\n // get all the events, stringify them and join them\n // with the new line character which can be sent to Loggly\n // via bulk endpoint\n var finalEvent = parsedEvents.map(JSON.stringify).join('\\n');\n\n // creating logglyURL at runtime, so that user can change the tag or customer token in the go\n // by modifying the current script\n // create request options to send logs\n try {\n var options = {\n hostname: logglyConfiguration.hostName,\n path: '/bulk/' + logglyConfiguration.customerToken + '/tag/' + encodeURIComponent(logglyConfiguration.tags),\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Content-Length': finalEvent.length\n }\n };\n\n var req = http.request(options, function (res) {\n res.on('data', function (result) {\n result = JSON.parse(result.toString());\n if (result.response === 'ok') {\n context.succeed('all events are sent to Loggly');\n } else {\n console.log(result.response);\n }\n });\n res.on('end', function () {\n console.log('No more data in response.');\n context.done();\n });\n });\n\n req.on('error', function (e) {\n console.log('problem with request: ' + e.toString());\n context.fail(e);\n });\n\n // write data to request body\n req.write(finalEvent);\n req.end();\n\n } catch (ex) {\n console.log(ex.message);\n context.fail(ex.message);\n }\n }", "doLog(level, parentArgs) {\r\n if (!this.initialized) {\r\n return; // no instance to log\r\n }\r\n\r\n let args = Array.prototype.slice.call(parentArgs);\r\n if (Buffer.isBuffer(args[0])) { // the first argument is \"reqId\"\r\n let reqId = args.shift().toString('base64');\r\n args[0] = reqId + ': ' + args[0];\r\n }\r\n this.instance[level].apply(this.instance, args);\r\n }", "function HttpUploadProgressEvent() {}", "function HttpUploadProgressEvent() {}", "function uploadCurrentChunk(cb){\n\t\n\tvar params = uploadParameters\n\n\ts3.uploadPart(uploadParameters, function(err, data){\n\t\tif(err){\n\t\t\tcb(err)\n\t\t\treturn\n\t\t} else if( currentFileStartTime.getTime() > (new Date()).getTime() - maxLogLife ){\n\t\t\t//If the time is up, go ahead and end the upload\n\t\t\tcompleteCurrentUpload(cb)\n\t\t} else {\n\t\t\tcb(null)\n\t\t}\n\n\t})\n}", "function postToServer(key){\n\tlocalforage.getItem('logs')\n\t.then((logs)=>{\n\t\tlet log = logs[key];\n\t\tlog = formatVolunteers(log);\n\t\tconsole.log(log);\n\t\t$.ajax({\n\t\t\ttype : 'POST',\n\t\t\tcontentType: \"application/json; charset=utf-8\",\n\t\t\turl : \"sample\",\n\t\t\tdataType: 'json',\n\t\t\tdata : JSON.stringify(log),\n\t\t\tsuccess : (response)=>{\n\t\t\t\tconsole.log(response);\n\t\t\t\tlog.submitted = true;\n\t\t\t\talert(\"Upload Success!\");\n\t\t\t\tlocalforage.setItem('logs',logs)\n\t\t\t\t.then(()=>window.location.reload(false));\n\t\t\t},\n\t\t\terror : (response)=>{\n\t\t\t\tconsole.log(response);\n\t\t\t\talert('Upload Failed!');\n\t\t\t\twindow.location.reload(false);\n\t\t\t\t$('.uploadModal').fadeOut(300);\n\n\t\t\t}\n\t\t});\n\n\t})\n}", "function writeLogs() {\n cslogging.loadConfig('./testConfig.json');\n\n // the configFile set the maxSize to be 1K and maxFiles to be 10\n // So we need to write out a bit more then 10*1K of bytes of logs\n var testLogger = cslogging.getLogger('test');\n\n console.log('writing logs!');\n for(var i=0; i < 20; i++) {\n var chr = String.fromCharCode(97 + i);\n var logwriting = createLogWritingFunction(testLogger, chr, 1000);\n\n setTimeout(logwriting, i*100);\n }\n\n}", "function logData (activityType, timestamp, userId, startTS, activityData) {\n /*\n var data = new FormData();\n data.append('activityType', activityType);\n data.append('timestamp', timestamp);\n data.append('userId', userId)\n data.append('startTS', startTS);\n data.append('version', EXT.VERSION); // global variable set by webpack\n data.append('activityData', JSON.stringify(activityData));\n // console.log('in logdata');\n // console.log(activityData)\n var xhr = new XMLHttpRequest();\n // send asnchronus request\n // console.log('sending req, ', activityType);\n xhr.open('post', 'https://super.cs.uchicago.edu/trackingtransparency/activitylog.php', true);\n // xhr.setRequestHeader(\"Content-Type\", \"application/json\")\n xhr.send(data);\n */\n}", "async logDispatch(instance, level, data) {\n //保存到数据库中\n const time = new Date();\n this.send({\n type: \"add_log\",\n name: instance.fileName,\n level,\n data: { time: time.toUTCString(), level, data },\n })\n await instance.logModel.create({ level, data, time });\n }", "upload() {\n const set = super.build()\n if(Object.keys(set).length >= 3){\n this.iot.publish(\"$aws/rules/AssetTelemetryData/\"+this.config.asset+\"/telemetry/data\", JSON.stringify(set), {}, () => {\n super.emit('upload', set)\n })\n }\n }", "function postAllToServer(){\n\tlocalforage.getItem('logs')\n\t.then(async (logs)=>{\n\t\tconsole.log(logs);\n\t\tfor(let key in logs){\n\t\t\tlet curr = logs[key];\n\t\t\tif(!curr.submitted){\n\t\t\t\tawait new Promise((res,rej)=>{\n\t\t\t\t\tcurr = formatVolunteers(curr);\n\t\t\t\t\t$.ajax({\n\t\t\t\t\t\ttype : 'POST',\n\t\t\t\t\t\tcontentType: \"application/json; charset=utf-8\",\n\t\t\t\t\t\turl : \"sample\",\n\t\t\t\t\t\tdataType: 'json',\n\t\t\t\t\t\tdata : JSON.stringify(curr),\n\t\t\t\t\t\tsuccess : (response)=>{\n\t\t\t\t\t\t\tcurr.submitted = true;\n\t\t\t\t\t\t\talert('Upload Success!');\n\t\t\t\t\t\t\tlocalforage.setItem('logs',logs)\n\t\t\t\t\t\t\t.then(res)\n\t\t\t\t\t\t},\n\t\t\t\t\t\terror : (response)=>{\n\t\t\t\t\t\t\talert('Upload Failed!');\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\n\t\t}\n\t\twindow.location.reload(false);\n\t});\n}", "logOnServer(severity, url, lineNr, message) {\n // Can't use client here as we need to send to a different endpoint\n API._fetch(LOGGING_ENDPOINT, [{ severity, url, lineNr, message }])\n }", "function logger(content,level) {\n\n var datestring = new Date().toISOString().split('T')[0];\n var timestring = new Date().toISOString().replace('T',' ');\n\n var filename = datestring+'-server.log';\n var line = timestring + level + content + \"\\n\";\n\n fs.appendFile(filename, line, function (err) {\n if (err) throw err;\n });\n}", "function Logger() {\n this.buffer = [];\n this.plugins = {};\n\n this.url = _DEFAULTS.url;\n this.flushInterval = _DEFAULTS.flushInterval;\n this.collectMetrics = _DEFAULTS.collectMetrics;\n this.logLevels = _DEFAULTS.logLevels;\n this.maxAttempts = _DEFAULTS.maxAttempts;\n}", "function postLog() {\n api(\"POST\", \"/log\", JSON.stringify(logData), (res)=>{/*donothing*/});\n}", "function handlePost (sampleRate) {\n\n // returns post handler function (p) { }\n return function (p) {\n if (validate(p)) {\n if (opts.debug)\n console.log('got start-recording message!', JSON.stringify(p))\n let filename = `${p.sid}.${p.tag}.${Date.now()}.csv`\n let path = join(opts.outdir, filename)\n ongoingRecordings[path] = {\n framesRecorded: 0,\n framesTotal: sampleRate * p.duration,\n }\n emit('post')(p) // emit post\n }\n }\n }", "function ServerLogger(\n loggerConfig, logLevels, interceptorFactories, traceService,\n $locale, $translate, $log, $window, $injector\n) {\n var _this = this;\n var sessionStorageKey = 'ngSpa_serverLogger_log';\n var logQueue = [];\n var sendDataIntervalId = null;\n\n /**\n * Interceptors stored in reverse order. Inner interceptors before outer interceptors.\n * The reversal is needed so that we can build up the interception chain around the\n * log action.\n */\n var reversedInterceptors = [];\n angular.forEach(interceptorFactories, function(interceptorFactory) {\n reversedInterceptors.unshift(angular.isString(interceptorFactory) ?\n $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));\n });\n\n // Start up the periodic flush of the log queue to server\n startInterval();\n\n // Load unsent logs from previous page load\n if ($window.sessionStorage) {\n try {\n logQueue = angular.fromJson($window.sessionStorage.getItem(sessionStorageKey) || '[]');\n } catch (ex) {}\n if (!Array.isArray(logQueue)) {\n logQueue = [];\n }\n }\n\n // Bulk send logs on interval\n this.startInterval = startInterval;\n function startInterval() {\n if (sendDataIntervalId || !loggerConfig.isLoggingEnabled) { return; }\n sendDataIntervalId = $window.setInterval(sendData, loggerConfig.loggingInterval);\n }\n\n this.stopInterval = function() {\n $window.clearInterval(sendDataIntervalId);\n sendDataIntervalId = null;\n };\n\n // Exposes this.error(), this.info(), and this.debug() functions\n angular.forEach(['error', 'info', 'debug'], function(fnName) {\n _this[fnName] = function(message, meta) {\n _this.log(message, meta, fnName);\n };\n });\n\n this.trackError = function(error) {\n var meta = {\n type: error.type || 'exception',\n message: error.message,\n stack: traceService.print({e: error}),\n name: error.name\n };\n if (error.data) {\n meta.data = error.data;\n }\n this.error(error.message, meta);\n };\n\n this.trackMetric = function(name, metric) {\n this.info('metric:' + name, {\n type: 'metric',\n name: name,\n metric: metric\n });\n };\n\n this.trackEvent = function(name, data) {\n this.info('event:' + name, {\n type: 'event',\n name: name,\n data: data\n });\n };\n\n this.trackAjax = function(httpObj, timing) {\n this.info(\n 'ajax ' + httpObj.status + ' ' + httpObj.config.method + ' ' + httpObj.config.url, {\n type: 'ajax',\n status: httpObj.status,\n method: httpObj.config.method,\n reqUrl: httpObj.config.url,\n timing: timing\n });\n };\n\n this.trackStateChange = function(level, event, toState, toParams, fromState, fromParams) {\n var toUrl = toState.url || '-none-';\n var toName = toState.name || toState.to || '';\n var message = 'route:' + event + ' -> ' + toUrl + ' (' + toName + ')';\n var nowTime = (new Date()).getTime();\n var meta = {\n type: 'route',\n event: event,\n from: fromState.name,\n to: toState.name\n };\n if (event === 'start') {\n fromState.startTime = nowTime;\n } else if (fromState.startTime) {\n meta.timing = nowTime - fromState.startTime;\n }\n this.log(message, meta, level);\n };\n\n this.log = function(message, meta, level) {\n if (!loggerConfig.isLoggingEnabled) { return; }\n\n meta = angular.extend({}, meta);\n\n // Proxy to console log\n if (loggerConfig.isConsoleLogEnabled) {\n $log[level].call($log, 'ServerLogger: ' + message, meta);\n }\n\n // Filter logs based on log level or excluded types\n if ((loggerConfig.loggingLevel <= logLevels[level.toUpperCase()]) &&\n (loggerConfig.excludeTypes.indexOf(meta.type || '') === -1)\n ) {\n level = validateLogLevel(level);\n var logItem = {\n time: (new Date()).getTime(),\n loc: $window.location.href,\n msg: message,\n meta: meta,\n level: level\n };\n\n addLogToQueue(logItem);\n }\n };\n\n function validateLogLevel(level) {\n if (!level || !logLevels[level.toUpperCase()]) {\n level = 'debug';\n }\n return level;\n }\n\n function addLogToQueue(logItem) {\n // Apply log interceptors\n angular.forEach(reversedInterceptors, function(interceptor) {\n if (interceptor.log) { interceptor.log(logItem); }\n });\n\n logQueue.push(logItem);\n saveLogQueue();\n }\n\n function saveLogQueue() {\n // Drop older items off back of stack per max buffer size\n if (logQueue.length > loggerConfig.maxBufferSize) {\n logQueue.splice(0, logQueue.length - loggerConfig.maxBufferSize);\n }\n\n if ($window.sessionStorage) {\n try {\n $window.sessionStorage.setItem(sessionStorageKey, angular.toJson(logQueue));\n } catch (ex) {\n if (loggerConfig.isConsoleLogEnabled) { $log.warn(ex); }\n }\n }\n }\n\n /**\n * Sends queue of log items to server in bulk.\n * WARNING: Do not use $http or else logger interceptor error handling\n * and request logging can wack things out.\n */\n function sendData() {\n if (logQueue.length === 0) { return; }\n\n var baseUrl = loggerConfig.apiBaseUrl || '';\n\n var logReqCfg = {};\n logReqCfg.url = baseUrl + loggerConfig.apiUrl;\n logReqCfg.headers = {\n 'X-Requested-With': 'XMLHttpRequest'\n };\n logReqCfg.data = {\n device: 'browser',\n appver: loggerConfig.appVersion,\n locale: $locale.id,\n lang: $translate.use(),\n screen: $window.screen.availWidth + 'x' + $window.screen.availHeight,\n logs: logQueue.splice(0, Number.MAX_VALUE) // Send all logs in queue\n };\n\n // Apply sendData interceptors\n // TODO: Consider promises.\n // Current preference is to keep it simple and not introduce any async failures\n // that could interrupt the log request\n angular.forEach(reversedInterceptors, function(interceptor) {\n if (interceptor.sendData) { interceptor.sendData(logReqCfg); }\n });\n\n if (loggerConfig.isStubsEnabled) {\n $log.debug('%cServerLogger => ajax 200 POST ' + logReqCfg.url,\n 'background:yellow; color:blue', 'reqData:', logReqCfg.data);\n saveLogQueue();\n\n } else {\n var request = createXhr();\n request.open('POST', logReqCfg.url, true);\n request.timeout = Math.min(loggerConfig.loggingInterval, 60000);\n request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');\n angular.forEach(logReqCfg.headers, function(val, key) {\n request.setRequestHeader(key, val);\n });\n request.onreadystatechange = function xhrReadyStateChange() {\n if (this.readyState === 4) {\n var success = (this.status >= 200 && this.status < 400);\n if (!success && this.status !== 413) {\n // Put logs back on the front of the queue...\n // But not if the server is complaining the request size is too large\n // via 413 (Request Entity Too Large) error\n $log.debug('sendlog unsuccessful');\n logQueue.unshift.apply(logQueue, logReqCfg.data.logs);\n }\n saveLogQueue();\n }\n };\n request.send(angular.toJson(logReqCfg.data));\n request = null;\n }\n }\n}", "function lemurlog_DoWriteLogFile(fileName, text) {\n lemurlog_WriteLogFile(fileName, text);\n lemurlog_checkAutoUpload();\n}", "function upload() {\n gtag('event', 'Event Uploader Submit');\n formatEvents();\n showHide('results', 'preview');\n apiWorker.postMessage(array);\n}", "constructor(logger) {\n super(logger, 'post');\n this.logger = logger;\n }", "log() {\n return winston.createLogger({\n defaultMeta: {\n requestId: this.requestId,\n // eslint-disable-next-line no-undef\n application: process.env.APP_NAME,\n },\n format: winston.format.combine(\n winston.format.timestamp({\n format: 'DD-MM-YYYY HH:mm:ss',\n }),\n winston.format.prettyPrint(),\n winston.format.json(),\n this.customFormatter(),\n winston.format.printf((info) => {\n const timestamp = info.timestamp.trim();\n const requestId = info.requestId;\n const level = info.level;\n const message = (info.message || '').trim();\n\n const saveFunction = new logsDb({\n timestamp : timestamp,\n level : level,\n message : message,\n //meta : meta,\n //hostname : foundedData.hostname\n });\n\n saveFunction.save((err) => {\n if (err) {\n console.log(\"failed to logs save operation\"); \n }\n\n })\n \n if (_.isNull(requestId) || _.isUndefined(requestId)) {\n return `${timestamp} ${level}: ${message}`;\n } else {\n return `${timestamp} ${level}: processing with requestId [${requestId}]: ${message}`;\n }\n }),\n ),\n transports: [\n new winston.transports.Console({\n level: 'debug',\n handleExceptions: true,\n }), \n // File transport\n new winston.transports.File({\n filename: 'logs/server.log',\n format: winston.format.combine(\n winston.format.colorize(),\n winston.format.timestamp({format: 'MMM-DD-YYYY HH:mm:ss'}),\n winston.format.align(),\n winston.format.json()\n )\n }), \n\n // MongoDB transport\n // new winston.transports.MongoDB({\n // level: 'info',\n // //mongo database connection link\n // db : 'mongodb://localhost:27017/mysale',\n // options: {\n // useUnifiedTopology: true\n // },\n // // A collection to save json formatted logs\n // collection: 'serverlogs',\n // format: winston.format.combine(\n // winston.format.timestamp(),\n // // Convert logs to a json format\n // winston.format.json()),\n // storeHost: true,\n // capped: false,\n // decolorize: false,\n // metaKey: 'meta',\n // }),\n\n ],\n });\n }", "function UploadService($http, toastService) {\n //api endpoints\n var buildingUploadUrl = 'building/addNewBuilding';\n var logFileUploadUrl = 'position/processRadioMapFiles';\n var evalFileUploadUrl = 'position/processEvalFiles';\n var floorUploadUrl = 'building/addFloorToBuilding';\n\n\n // service functions\n return {\n uploadBuilding: function (newBuilding) {\n var postData = newBuilding;\n\n var promise = $http({\n method: 'POST',\n url: buildingUploadUrl,\n data: postData,\n headers: {\n 'Content-Type': 'application/json'\n }\n }).then(function (response) {\n logMessage = response.data.message;\n toastService.showToast(logMessage, \"success-toast\");\n return response.data;\n }, function errorCallback(response) {\n logMessage = response.data.message;\n toastService.showToast(logMessage, \"error-toast\");\n });\n return promise;\n },\n uploadRadioMap: function (radioMapSet) {\n if (!radioMapSet.radioMapFiles) {\n if (radioMapSet.buildingIdentifier !== 0) {\n logMessage = \"Please choose a file to upload\";\n toastService.showToast(logMessage, \"error-toast\");\n }\n } else if (radioMapSet.tpFiles.length && radioMapSet.tpFiles.length !== radioMapSet.radioMapFiles.length) {\n logMessage = \"Number of tp files and radiomap files should match\";\n toastService.showToast(logMessage, \"error-toast\");\n } else {\n // body content (log files and buildingId)\n var formData = new FormData();\n formData.append('buildingIdentifier', radioMapSet.buildingIdentifier);\n for (var i = 0; i < radioMapSet.radioMapFiles.length; i++) {\n formData.append('radioMapFiles', radioMapSet.radioMapFiles[i], radioMapSet.radioMapFiles[i].name);\n }\n for (var j = 0; j < radioMapSet.tpFiles.length; j++) {\n formData.append('transformedPointsFiles', radioMapSet.tpFiles[j], radioMapSet.tpFiles[j].name);\n }\n\n\n $http({\n method: 'POST',\n url: logFileUploadUrl,\n data: formData,\n transformRequest: function (data, headersGetterFunction) {\n return data;\n },\n headers: {\n 'Content-Type': undefined\n }\n }).then(function successCallback(response) {\n // success\n logMessage = response.data.message;\n toastService.showToast(logMessage, \"success-toast\");\n }, function errorCallback(response) {\n // failure\n logMessage = response.data.message;\n toastService.showToast(logMessage, \"error-toast\");\n });\n }\n },\n uploadEvaluationFile: function (evaluationSet) {\n if (evaluationSet.evalFiles[0] === null) {\n if (evaluationSet.buildingIdentifier !== 0) {\n logMessage = \"Please choose a file to upload\";\n toastService.showToast(logMessage, \"error-toast\");\n }\n } else if (evaluationSet.tpFiles.length && evaluationSet.tpFiles.length !== evaluationSet.evalFiles.length) {\n logMessage = \"Number of tp files and eval files should match\";\n toastService.showToast(logMessage, \"error-toast\");\n } else {\n // body content (eval files and buildingId)\n var formData = new FormData();\n formData.append('buildingIdentifier', evaluationSet.buildingIdentifier);\n formData.append('evalFiles', evaluationSet.evalFiles[0], evaluationSet.evalFiles[0].name);\n for (var j = 0; j < evaluationSet.tpFiles.length; j++) {\n formData.append('transformedPointsFiles', evaluationSet.tpFiles[j], evaluationSet.tpFiles[j].name);\n }\n\n $http({\n method: 'POST',\n url: evalFileUploadUrl,\n data: formData,\n transformRequest: function (data, headersGetterFunction) {\n return data;\n },\n headers: {\n 'Content-Type': undefined\n }\n }).then(function successCallback(response) {\n // success\n logMessage = response.data.message;\n toastService.showToast(logMessage, \"success-toast\");\n }, function errorCallback(response) {\n // failure\n logMessage = response.data.message;\n toastService.showToast(logMessage, \"error-toast\");\n });\n }\n },\n uploadFloorMap: function (floorSet) {\n if (floorSet.floorFiles[0] === null) {\n logMessage = \"Please choose an image file to upload\";\n toastService.showToast(logMessage, \"error-toast\");\n } else {\n // body content (floor file, floorId and buildingId)\n var formData = new FormData();\n formData.append('buildingIdentifier', floorSet.building.buildingId);\n formData.append('floorIdentifier', floorSet.floorIdentifier);\n formData.append('floorName', floorSet.floorName);\n formData.append('floorMapFile', floorSet.floorFiles[0], floorSet.floorFiles[0].name);\n\n $http({\n method: 'POST',\n url: floorUploadUrl,\n data: formData,\n transformRequest: function (data, headersGetterFunction) {\n return data;\n },\n headers: {\n 'Content-Type': undefined\n }\n }).then(function successCallback(response) {\n // success\n logMessage = response.data.message;\n toastService.showToast(logMessage, \"success-toast\");\n }, function errorCallback(response) {\n // failure\n logMessage = response.data.message;\n toastService.showToast(logMessage, \"error-toast\");\n });\n }\n }\n };\n}", "function wwLog(logLevel, oData){\n\t\n\t// check if post back to main exists\n\t// if dosent exist, dont do anything\n\tif (typeof postMsgToMain == 'function') { \n\t\tpostMsgToMain(logLevel, \"INFO\" ,oData); \n\t}\n\n\n}", "async function run() {\n let blob = new BlobStorage(config.storageAccount,config.storageKey);\n //blob.uploadFile('blobbyvolley', 'neuer-blob1',sourceFilePath);\n blob.createAppendBlob('logfiles','kalender');\n blob.createAppendBlob('logfiles','users');\n blob.createAppendBlob('logfiles','events');\n}", "function handleUploads() {\n \n}", "addLogsHandler(logsHandler) {\n this.logsHandlers.push(logsHandler);\n }", "shouldLog(logLevel) {\n return (!!this._logger &&\n logLevel !== exports.HttpPipelineLogLevel.OFF &&\n logLevel <= this._logger.minimumLogLevel);\n }", "shouldLog(logLevel) {\n return (!!this._logger &&\n logLevel !== exports.HttpPipelineLogLevel.OFF &&\n logLevel <= this._logger.minimumLogLevel);\n }", "function sendLog(malfunctionId){\n timestamp = userActions[1][0];\n userActions = JSON.stringify(userActions);\n $.ajax({\n url: myApp.urSrvURL + \"log.php\",\n type: \"POST\",\n data: ({\"logData\": userActions, \"timestamp\": timestamp, \"malfunctionId\": malfunctionId})\n });\n }", "function httpLog(request, load) {\r\n\t\t// Log request.\r\n\t\tvar d = new Date();\r\n\t\tvar now = d.getTime();\r\n\t\tvar line = now + \"\\t\" + request.connection.remoteAddress + \"\\t\" + load + \"\\r\\n\";\r\n\t\tfs.appendFile('logs/http.tsv', line, function (err) {});\r\n\t}", "function appendToLogs(level, args) {\n if (!args) return;\n\n var message;\n\n try {\n message = OT.$.JSONify(args);\n } catch(e) {\n message = args.toString();\n }\n\n if (message.length <= 2) return;\n\n _logs.push(\n [level, formatDateStamp(), message]\n );\n}", "function writeLog(logData) {\n if (!CONFIG.USE_MOCK_SERVICES) {\n angular.extend(logData, {\n url: $window.location.href\n });\n\n Accela.XHR.post(CONFIG.LOG_URL, logData, CONFIG.LOG_ACCESS_KEY);\n }\n }", "function logHttpRequest(opts) {\n if (Logger.debug.isEnabled) {\n var logger = Logger.debug;\n // TODO: Append query parameters to the URL.\n var logMessage = opts.type + ' ' + opts.url;\n if (Logger.trace.isEnabled) {\n // TODO: If any data is being sent, log that.\n logger = Logger.trace;\n }\n logger(logMessage);\n }\n}", "function metricLog() {\r\n fs.exists(metricFileLocation, function(exists) {\r\n if (exists) fs.unlinkSync(metricFileLocation);\r\n });\r\n return function(req, res, next) {\r\n metricRoute = core.getUrlObj(req).pathname.split('/')[1];\r\n if (metricRouteRegex.test(metricRoute)) {\r\n core.wipe(metric);\r\n metric['url'] = req['url'];\r\n metric['datestamp'] = new Date();\r\n metric['remoteAddress'] = req.connection['remoteAddress'];\r\n metric['user-agent'] = req.headers['user-agent'];\r\n metric['referer'] = req.headers['referer'];\r\n fs.appendFile(metricFileLocation, '\\n' + JSON.stringify(metric), 'utf-8');\r\n }\r\n next();\r\n };\r\n}", "function Logging() {\n this.thresholdOfLogLevel = LogLevel.Informational;\n this.verboseTelemetry = false;\n this.http = new Http();\n this.logSet = {\n maxWaitTimeMs: Logging.logMaxWaitTimeMs,\n maxRecordLength: Logging.logMaxRecordLength,\n api: '/api/log'\n };\n this.telemetrySet = {\n maxWaitTimeMs: Logging.telemetryMaxWaitTimeMs,\n maxRecordLength: Logging.telemetryMaxRecordLength,\n api: '/api/telemetry'\n };\n }", "function initLogModule (logFilename, logLevel, fileMaxsize, fileMaxfiles, needConsoleLog, needFileLog, callback)\n{\n\twinston.remove(winston.transports.Console) ; // Be default it is ON\n\tif (needConsoleLog)\n\t{\n\t\twinston.add(winston.transports.Console, {level: logLevel });\n\t}\n\tif (needFileLog)\n\t{\n\t\twinston.add(winston.transports.File, { filename: logFilename, level: logLevel, maxsize: fileMaxsize, maxFiles: fileMaxfiles, json: false });\n\t}\n\tdefine.winston = winston ;\n\n\tcallback (0) ; // return Success\n}", "function publishHttp(){\r\n if(moduleName == \"\"){\r\n moduleName = path.substr(path.lastIndexOf(\"\\\\\") + 1) + \".zip\";\r\n }else{\r\n moduleName = moduleName + \".zip\";\r\n }\r\n getFile(path,'');\r\n //将文件压缩保存\r\n var fileArray = [];\r\n for(var fileName in filesZip){\r\n //addDataToZip(filesZip[fileName],'binary');\r\n filePath = pathSys.normalize(\"./\"+ filesZip[fileName]);\r\n fileArray.push({name:filesZip[fileName],path:filePath});\r\n }\r\n //console.log(\"d: \"+fileArray);\r\n\r\n archive.addFiles(fileArray, function (err) {\r\n if (err) return console.log(\"err while adding files\", err);\r\n\r\n var buff = archive.toBuffer();\r\n\r\n fs.writeFile(moduleName, buff, function () {\r\n var options = {\r\n uploadUrl: serverRequest[0],\r\n method: 'POST',\r\n fileId: path + \"\\\\\" + moduleName,\r\n fields: {\r\n 'fileName': moduleName,\r\n 'readMe': readMe,\r\n 'userName':userName\r\n }\r\n };\r\n poster.post(path + \"\\\\\" + moduleName, options, function(err, data) {\r\n if (!err) {\r\n console.log(data);\r\n //删除上传后的zip临时文件\r\n fs.unlinkSync(moduleName);\r\n }else{\r\n console.log(err);\r\n }\r\n });\r\n });\r\n });\r\n }", "function writeLog() {\n const interval = randomInt(900, 200);\n setTimeout(() => {\n const log = buildLog();\n stream.write(log)\n writeLog();\n }, interval)\n}", "constructor(module) {\n\n this.module = module\n\n //create write stream so that we'll be able to write the log messages into the log file \n let logStream = fs.createWriteStream('./logs', { flags: 'a' })\n\n //create function that logs info level messages\n let info = function (msg) {\n //Define the log level\n var level = 'info'.toUpperCase()\n\n //Format the message into the desired format\n let message = `${new Date()} | ${level} | ${module} | ${msg} \\n`\n\n //Write the formated message logged into the log file\n logStream.write(message)\n }\n //initialize the info function.\n this.info = info\n\n //Create a function that logs error level messages\n let error = function (msg) {\n //Define the log level\n var level = 'error'.toUpperCase()\n\n //format the message into the desired format\n let message = `${new Date()} | ${level} | ${module} | ${msg} \\n`\n\n //Write the formated message logged into the log file\n logStream.write(message)\n }\n\n //initialize the error function\n this.error = error\n }", "function writeLog(req){\n var logContainer=new LogContainer(req);\n logContainer.parseLog();\n var ret = writeLogFromLogContainer(logContainer);\n //special delivery for v9\n var old_appid = logContainer.getAppid();\n if(old_appid.substr(0,3)==\"v9-\" && !(old_appid == \"v9-v9\")){\n logContainer.setAppid(\"v9-v9\");\n ret = writeLogFromLogContainer(logContainer);\n }\n return ret;\n}", "_onError(event) {\n const span = document.createElement(\"span\");\n span.innerHTML = \"\" + \"Upload failed. Retrying in 5 seconds.\";\n this.node.appendChild(span);\n this.retry = setTimeout(() => this.callbackUpload(), 5000, this.data);\n\n TheFragebogen.logger.error(this.constructor.name + \".callbackUpload()\", \"Upload failed with HTTP code: \" + this.request.status + \". Retrying in 5 seconds.\");\n }", "function log() {\n const percent = Math.floor((finished / total) * 1000) / 10;\n if (percent - lastLogged >= 20) {\n lastLogged = percent - (percent % 20);\n console.log(` Uploaded ${percent}% of files`);\n }\n }", "function appendToLog(data, source) {\n\n if (source === 'twitter') {\n fs.appendFile('twitter_log.txt', JSON.stringify(data, null, '\\t'), 'utf8', function(error, response) {\n if (error) {\n return console.log(error);\n }\n console.log('Log has been updated!');\n })\n }\n\n if (source === 'movie') {\n fs.appendFile('movie_log.txt', JSON.stringify(data, null, '\\t'), 'utf8', function(error, response) {\n if (error) {\n return console.log(error);\n }\n console.log('Log has been updated!');\n })\n }\n \n if (source === 'spotify') {\n fs.appendFile('spotify_log.txt', JSON.stringify(data, null, '\\t'), 'utf8', function(error, response) {\n if (error) {\n return console.log(error);\n }\n console.log('Log has been updated!');\n })\n }\n}", "function upload () {\n req.pipe(uploads.createWriteStream(oninfo))\n return\n\n // Called when the writing has been completed and the hash value calculated\n function oninfo (err, info) {\n if (err) return send(500)\n\n // Respond with a formatted JSON string that is easy for humans and\n // computers to read\n return send(201, JSON.stringify(info, null, 2) + '\\n')\n }\n }", "function appendToLog(form){\n // Build request payload\n var name = 'Conversation CBA _ ' + new Date();\n var conv = document.getElementById('scrollingChat').innerHTML;\n var comment = form.logComment.value;\n var date = new Date();\n var formDate = (date.getMonth()+1)+' / '+date.getDate()+' / '+date.getFullYear()+' _ Hour: '+date.getHours() +\":\"+date.getMinutes()+\":\"+date.getSeconds();\n var cloudantQuery = \"?name=\"+name+\"&conv=\"+conv+\"&comment=\"+comment+\"&date=\"+formDate;\n \n\tlocation= logEndpoint+cloudantQuery;\n\n\t/* \n // Build http request\n var http = new XMLHttpRequest();\n http.open('POST', logEndpoint, true);\n\thttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n\n // Send request\n http.send(cloudantQuery);\n */\n }", "function enableLogging() {\n logEnabled = true;\n}", "function mcFileUploading($rootScope){\n \"use strict\";\n\n var uploader = null;\n var errorCallback = null;\n var successCallback = null;\n var uploaderOptions = {};\n var inputFileName = \"__fileSender__\";\n var abortUploadingID = null;\n var abortPreparingUploading = null;\n var abortUploadingCB = null;\n var abortNow = false;\n var whereWeWork = \"\";\n\n function parseFile(file, callback) {\n var fileSize = file.size;\n var chunkSize = 512 * 1024; // bytes\n var offset = 0;\n var chunkReaderBlock = null;\n var onePercent = file.size / 100;\n var currentPercent = 0;\n\n var readEventHandler = function (evt) {\n if (!abortNow){\n if (evt.target.error == null) {\n offset += evt.target.result.byteLength;\n currentPercent = (offset / onePercent).toFixed();\n\n callback(null, evt.target.result, currentPercent); // callback for handling read chunk\n } else {\n callback(evt.target.error);\n\n return;\n }\n\n if (offset >= fileSize) {\n callback(null, null, 100);\n\n return;\n }\n\n chunkReaderBlock(fileReader, offset, chunkSize, file);\n }\n };\n\n chunkReaderBlock = function (_reader, _offset, length, _file) {\n var reader = _reader || new FileReader();\n var blob = _file.slice(_offset, length + _offset);\n\n if (!_reader) {\n if (uploaderOptions.onBeforeFileAdd) {\n uploaderOptions.onBeforeFileAdd(file);\n }\n\n if (!abortPreparingUploading){\n abortPreparingUploading = function () {\n reader.abort();\n reader.onload = null;\n\n abortPreparingUploading = null;\n }\n }\n\n reader.onload = readEventHandler;\n }\n\n reader.readAsArrayBuffer(blob);\n\n return reader;\n };\n\n var fileReader = chunkReaderBlock(null, offset, chunkSize, file);\n }\n\n function startUploadAfterCheck(info, file) {\n uploaderOptions.Hash = info.Hash; // SHA1 хэш файла\n uploaderOptions.Width = $rootScope.thumbsSize.x; // произвольная ширина уменьшеной копии изображения\n uploaderOptions.Height = $rootScope.thumbsSize.y; // произвольная высота уменьшенной копии изображения\n uploaderOptions.FileName = info.FileName; // локальное название файла\n\n if (!info.Present) { // file not exist - uploading\n uploader.define(\"upload\", mcService.getLocalHostPath($rootScope.isWebClient) + \"/uploading/?sid=\" + mcConst.SessionID + \"&hash=\" + info.Hash + whereWeWork);\n uploader.addFile(file);\n } else {\n if (successCallback) {\n successCallback.apply(uploaderOptions, arguments);\n } else {\n console.trace('No set success callback on file uploading');\n }\n }\n }\n\n function electronUploader() {\n $rootScope.$broadcast(window._messages_.clientData.sendCMDToElectron, [\n mcConst._CMD_.ce_file_upload_start,\n uploaderOptions.filePath,\n {\n Where : uploaderOptions.Where,\n ID : uploaderOptions.ID,\n Type : uploaderOptions.Type,\n chatType : uploaderOptions.chatType\n }\n ]);\n\n abortUploadingCB = function () {\n abortUploadingCB = null;\n\n $rootScope.$broadcast(window._messages_.clientData.sendCMDToElectron, [\n mcConst._CMD_.ce_file_upload_abort\n ]);\n };\n \n abortPreparingUploading = function () {\n abortPreparingUploading = null;\n\n $rootScope.$broadcast(window._messages_.clientData.sendCMDToElectron, [\n mcConst._CMD_.ce_file_upload_prepare_abort\n ]);\n };\n }\n\n function checkFileExist(params, cb) {\n $rootScope.SendCMDToServer(\n [ mcConst._CMD_.cs_is_file_exists, mcConst.SessionID ]\n .concat(params || [])\n .concat(cb)\n );\n }\n\n function _goUploadClipboardImage() {\n var calcSha1 = mcService.SHA1();\n var Hash = \"\";\n var fileReader = new FileReader();\n\n fileReader.onloadend = function() {\n var screenImg = this.result;\n var imageInfo = uploaderOptions.clipboardImage;\n\n calcSha1.append(screenImg);\n\n if (!imageInfo.name || (imageInfo.name && imageInfo.name.indexOf(\"image.\") === 0 && !imageInfo.path) ){\n try{\n imageInfo[\"name\"] = \"Screenshot (\" + mcConst.UserInfo.Nick + \") \" + mcService.formatDate(new Date(), \"dd-mm-yyyy hh-nn-ss\") + \".png\";\n } catch (e) {}\n }\n\n Hash = calcSha1.end();\n\n checkFileExist([\n Hash , // SHA1 хэш файла\n mcConst._CMD_.msgType.IMAGE, // тип файла. 2 - изображение, 4 - обычный файл\n imageInfo.name, // локальное название файла\n uploaderOptions.Where,\n uploaderOptions.ID ,\n mcService.fileTimeStamp()\n ], function (data) {\n startUploadAfterCheck(data, imageInfo);\n });\n };\n\n fileReader.readAsArrayBuffer(uploaderOptions.clipboardImage);\n }\n\n function _goUploadFile() {\n var fileInput= this;\n var calcSha1 = mcService.SHA1();\n var file = fileInput.files[0];\n var MsgType = uploaderOptions.Type;\n\n if (file){\n uploaderOptions.fileSize = file.size;\n uploaderOptions.lastModifiedDate = file.lastModified || file.lastModifiedDate;\n\n setTimeout(function () {\n parseFile(file, function (err, data, percent) {\n if (err) {\n console.error(\"Read error: \" + err);\n } else {\n if (data) {\n if (uploaderOptions.onPrepareProgress){\n uploaderOptions.onPrepareProgress(percent);\n }\n\n calcSha1.append(data);\n } else {\n var Hash = calcSha1.end();\n\n if (fileInput.value) {\n fileInput.value = \"\";\n }\n\n checkFileExist([\n Hash , // SHA1 хэш файла\n MsgType , // тип файла. 2 - изображение, 4 - обычный файл\n uploaderOptions.Type === mcConst._CMD_.msgType.IMAGE\n ? file.name // локальное название файла\n : file.path || file.name,\n uploaderOptions.Where , // куда вставлять файл (priv, conf, bbs, broadcast, forum, kanban)\n uploaderOptions.ID , // число-идентификатор, для кого отправлять файл:\n // 1, private - UIN\n // 2, conference - UID\n // 3, forum - ID топика\n // 4, kanban - ID таска\n // 5, bbs - -1\n // 6, broadcast - -1\n mcService.fileTimeStamp(file.lastModified || file.lastModifiedDate)\n ], function (data) {\n startUploadAfterCheck(data, file);\n });\n }\n }\n });\n }, 100);\n }/* else {\n if (errorCallback){\n errorCallback();\n }\n }*/\n }\n\n function fileFromDialog() {\n var element = document.getElementById(inputFileName);\n\n if (!element){\n element = document.createElement('div');\n\n element.id = inputFileName;\n element.className = 'hideFileInput';\n\n document.body.appendChild(element);\n }\n\n element.innerHTML = '<input type=\"file\">';\n\n var fileInput = element.firstChild;\n\n if (fileInput.value && mcService.isIE()) {\n fileInput.parentNode.replaceChild(\n fileInput.cloneNode(true),\n fileInput\n );\n\n fileInput = document.getElementById(inputFileName).firstChild;\n }\n\n switch (uploaderOptions.Type) {\n case mcConst._CMD_.msgType.IMAGE:\n fileInput.accept = \"image/png, image/gif, image/jpeg, image/jpg\";\n break;\n\n case mcConst._CMD_.msgType.VIDEO:\n fileInput.accept = \"video/mp4, video/x-m4v, .mkv, video/mpeg, video/webm, video/*\";\n break;\n\n default:\n fileInput.accept = \"\";\n }\n\n if (fileInput.fileEvent){\n fileInput.removeEventListener('change', fileInput.fileEvent);\n }\n\n fileInput.fileEvent = _goUploadFile;\n\n fileInput.addEventListener('change', fileInput.fileEvent);\n\n fileInput.click();\n }\n\n function uploadFile(_errorCallback, _successCallback, _uploaderOptions){\n errorCallback = _errorCallback;\n successCallback = _successCallback;\n uploaderOptions = _uploaderOptions || {};\n\n // -- clipboard image --\n if (uploaderOptions.clipboardImage) {\n _goUploadClipboardImage();\n } else\n\n // -- drop file into chat text --\n if (uploaderOptions.filePath && uploaderOptions.dropFile){\n _goUploadFile.apply(uploaderOptions.dropFile);\n } else\n\n // -- clipboard file, only for electron app --\n if (uploaderOptions.filePath){\n electronUploader();\n } else\n \n // -- file from dialog window --\n {\n fileFromDialog();\n }\n }\n\n // ========================================================\n\n var _msg = window._messages_.mcFileUploader = {\n abortUploading : 'abortUploading',\n abortPreparingUploading : 'abortPreparingUploading',\n uploadFile : 'uploadFile'\n };\n\n $rootScope.$on(_msg.abortUploading, function () {\n abortNow = true;\n\n if (abortPreparingUploading) {\n abortPreparingUploading();\n }\n\n if (uploader && abortUploadingID) {\n uploader.stopUpload(abortUploadingID);\n uploader.destructor();\n }\n\n if (abortUploadingCB){\n abortUploadingCB();\n }\n\n uploaderOptions = {};\n });\n\n $rootScope.$on(_msg.abortPreparingUploading, function () {\n if (abortPreparingUploading) {\n abortPreparingUploading();\n }\n\n if (uploader){\n uploader.destructor();\n }\n });\n\n $rootScope.$on(_msg.uploadFile, function(e,args){\n uploader = $$(\"uploadAPI\");\n\n if (uploader){\n uploader.destructor();\n }\n\n abortUploadingID = null;\n abortPreparingUploading = null;\n abortUploadingCB = null;\n abortNow = false;\n\n whereWeWork = $rootScope.hasOwnProperty(\"GetChatType\") ? \"&where=\" + $rootScope.GetChatType().toLowerCase() : \"\";\n\n var opt = args[2] || {};\n\n if (!opt.uploadProgress && !$$(\"uploadProgress\")){\n webix.ui({ id: \"uploadProgress\", view: \"list\", scroll: false, padding: 0, borderless: true, hidden: true, select: false});\n }\n\n uploader = webix.ui({\n id : \"uploadAPI\",\n view : \"uploader\",\n multiple: false,\n link : opt.uploadProgress || \"uploadProgress\",\n apiOnly: true,\n on : {\n onAfterFileAdd: function (file) {\n abortUploadingID = file.id;\n\n if (uploaderOptions.onAfterFileAdd){\n uploaderOptions.onAfterFileAdd(file);\n }\n },\n onUploadComplete:function(){\n if (successCallback) {\n successCallback.apply(uploaderOptions, []);\n } else {\n console.trace('No set success callback on file uploading');\n }\n\n errorCallback = null;\n successCallback = null;\n },\n onFileUploadError:function(){\n console.warn(\"Error during file uploading\");\n\n if (errorCallback) {\n errorCallback.apply(null, arguments);\n }\n\n errorCallback = null;\n successCallback = null;\n }\n }\n });\n\n uploadFile.apply(null, args);\n });\n}", "dumpToBacklog(file, log_arr) {\n let { backlog } = this;\n\n if (file === backlog)\n return;\n \n let jsonParsedLines = this.parsedLinesToJSON(log_arr);\n fs.appendFile(backlog, jsonParsedLines, (err) => {\n if (err)\n console.log(err);\n else {\n console.log(\"back logged...\");\n fs.unlink(file, (err) => {\n if (err) \n console.log(err) \n else\n console.log(`${file}: deleted`);\n });\n }\n });\n \n }", "async run() {\n this.watcher = fs.watch(this.logsPath);\n console.log(\"Starting Logger...\");\n // I know this function gets a bit callback helly but its an alpha\n // after a an hour or two of refactoring im sure it can be cleaner (ex. promisify everything)\n this.watcher\n .on('change', (eventType, filename) => {\n\n // checks if its a change event and if the file is included in watchfiles\n if (eventType === 'change' && this.watchFiles.includes(filename)) {\n \n // creates a read steam from last byte read onwards\n let tmpStream = fs.createReadStream(`${this.logsPath}/${filename}`, { start: this.bytesRead[filename] });\n \n // once data is recived we process it\n tmpStream\n .on('data', (chunk) => {\n // turn buffer chunks into string\n let chunk2Str = chunk.toString();\n \n // changed this up, now it runs through line parser and then gets\n // reattached as a string to be dumped in the buffer.\n let jsonParsedLines = this.parsedLinesToJSON(this.lineParser(filename, chunk2Str));\n \n // append to buffer file\n fs.appendFile(this.tmpBuff, jsonParsedLines, (err) => {\n // errors are handled not to crash program but they dont log themselves...yet\n if (err)\n console.log(err);\n else\n // this line ensures that once the content has been read, every byte goes in the counter\n // so that next pass around it start right where it left off\n this.bytesRead[filename] += Buffer.byteLength(chunk2Str);\n\n // after getting the size of the current buffer file and based on the set interval\n // we decide if we want to send the buffer to the server or wait for more logs\n // this can be changed via interval to the developers choosing, to not make 1000 http\n // requests a second every time there is a new log line\n if (this.getFilesizeInBytes(this.tmpBuff) >= this.buffInterval)\n this.theTransporter(this.tmpBuff, this.bbToArr(this.tmpBuff));\n });\n // closing the stream\n tmpStream.close();\n });\n \n }\n else if (eventType === 'rename' && /\\d{8}-\\d{6}.log$/.test(filename) && fs.existsSync(`${this.logsPath}/${filename}`)) {\n try {\n let filePath = `${this.logsPath}/${filename}`;\n let data = fs.readFileSync(filePath);\n this.theTransporter(filePath, this.lineParser(filename, data.toString()));\n }\n catch(err) {\n console.log(err);\n }\n }\n else {\n console.log(\"Unknown eventType or buff/backlog file\");\n }\n })\n .on('error', (err) => {\n // send to server error log\n console.log(err);\n console.log(\"Logger Offline...\");\n })\n .on('close', () => {\n if (this.getFilesizeInBytes(this.tmpBuff) > 1)\n this.theTransporter(this.tmpBuff, this.bbToArr(this.tmpBuff));\n if (this.getFilesizeInBytes(this.backlog) > 1)\n this.theTransporter(this.backlog, this.bbToArr(this.backlog));\n });\n }", "function mylogging(logg)\r\n{\r\n\t let r = logg.requests[0].response.headers ;\r\n\t r = JSON.stringify(r) ;\r\n\t console.log(r) ;\r\n\t fs.writeFileSync(filePath,r);\r\n}", "function enableTelemetry(interval) {\n if (interval === void 0) { interval = 5000; }\n return function (dispatch) {\n disableTelemetry();\n REPORTING_INTERVAL = setInterval(function () {\n dispatch(sendQueuedTelemetry());\n }, interval);\n };\n}", "scheduleLogRequest() {\n if (!this.state.looping) {\n return;\n }\n this.requestLoop = window.setTimeout(() => {\n this.requestLatestJobLog();\n }, this.logPollInterval);\n }", "log(kind, msg, data){ this.logger(kind, msg, data) }", "function uploadJobFile(f) {\n console.log(\"Upload\")\n // Seems that angular file upload gets called multiple times.\n if (!checkDupFile(f)) {\n console.log(\"Dup\")\n return null;\n }\n\n path = buildJobFilesPath();\n f.upload = Upload.upload( {\n url: path,\n data: {name: f.name, file:f},\n headers: {'Authorization': authorization()},\n });\n\n service.uploadFiles.push(f);\n\n var p = f.upload.then(function (response) {\n service.files.push(response.data);\n service.uploadFiles = _.reject(service.uploadFiles, function(el){ return el.name === f.name; } );\n return response;\n }, function (response) {\n var message = \"Error:\"+response.status\n var error = response.data;\n if (error && typeof error === \"object\" && \"detail\" in error ) {\n message = message + \":\" + error.detail;\n } else if (error && typeof error === \"object\" && \"file\" in error ) {\n message = message + \":\" + error.file;\n } else if (error) {\n message = message + \":\" + JSON.stringify(error)\n }\n f.error = message;\n service.failedFiles.push(f);\n service.uploadFiles = _.reject(service.uploadFiles, function(el){ return el.name === f.name; } );\n return response;\n }, function (evt) {\n f.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));\n return evt\n });\n\n return p;\n }", "function appendLog(req, res, next) {\n req.log = log.child({ \n 'ip': req.ip, 'method': req.method, 'url': req.originalUrl\n });\n next();\n}", "interval_event() {\n if (this.last_written) {\n this.connection.send(JSON.stringify(this.last_written));\n this.last_written = null;\n } else {\n clearInterval(this.interval_id);\n this.interval_id = null;\n }\n }", "function UploadWriter(contentType) {\n var that = this, data = \"\", pending = \"\";\n var uploadrq;\n var dataqueue = [];\n var doneCalled = false;\n var n=0;\n var name = '/f/' + getName($('#put_passphrase').text());\n\n function init(callback) {\n console.log('Uploadwriter.init', callback);\n data += \"data:\" + (contentType || \"\") + \";base64,\";\n callback();\n }\n\n // Called to when a new block to upload may be available\n function trigger_upload() {\n if (uploadrq)\n return; // still busy\n if (dataqueue.length === 0)\n {\n if (doneCalled)\n uploadDone();\n return; // nothing to do\n }\n\n uploadrq = new XMLHttpRequest();\n uploadrq.open('PUT', name);\n var current = dataqueue.shift();\n var current_length = current.length;\n uploadrq.overrideMimeType('text/plain');\n uploadrq.send(current);\n uploadrq.onreadystatechange = function() {\n if (uploadrq.readyState == XMLHttpRequest.DONE)\n {\n\n uploadrq = 0;\n upload_state.uploaded += current_length;\n upload_state.queue_length = dataqueue.length;\n updateProgress(upload_state);\n\n trigger_upload();\n }\n }\n\n }\n\n function writeUint8Array(array, callback) {\n\n upload_state.encrypted += array.length;\n\n if (array.length > 0)\n {\n dataqueue.push(array);\n trigger_upload();\n }\n function trycallback()\n {\n if (dataqueue.length > MAX_QUEUE_LEN)\n window.setTimeout(trycallback, 2000);\n else\n callback();\n }\n trycallback();\n }\n\n function getData(callback) {\n callback('NA');\n doneCalled = true;\n }\n\n that.init = init;\n that.writeUint8Array = writeUint8Array;\n that.getData = getData;\n}", "function writeData(){\n //update the sensor data\n sensorData.clock = sensorData.clock+60000\n sensorData.pressure = Math.round((Math.random()*50 + 1000)*100)/100\n sensorData.temperature= Math.round((Math.random()*.5 + 26)*100)/100\n sensorData.humidity = Math.round((Math.random()*10 + 50)*100)/100\n sensorData.light = Math.round(Math.random()*1000)\n sensorData.moisture = Math.round(Math.random()*80 + 400)\n \n // configure the header options\n var options = {\n //hostname: '192.168.1.145',\n hostname: 'localhost',\n port: 8080,\n path: '/upload',\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Content-Length': JSON.stringify(sensorData).length\n }\n };\n \n //create the post request\n var req = http.request(options,function(res) {\n console.log('STATUS: ' + res.statusCode);\n console.log('HEADERS: ' + JSON.stringify(res.headers));\n res.setEncoding('utf8');\n res.on('data', function (chunk) {\n console.log('BODY: ' + chunk);\n });\n res.on('end', function() {\n console.log('No more data in response.')\n })\n });\n req.on('error', function(e) {\n console.log('problem with request: ' + e.message);\n });\n req.write(JSON.stringify(sensorData));\n}", "constructor(uploader, filesPath, onUpload = null, schedulerIntervalSec = 5) {\n this.uploader = uploader;\n this.path = filesPath;\n this.onUpload = onUpload;\n this.schedulerInterval = schedulerIntervalSec * 1000;\n if (this.schedulerInterval !== 0) {\n this.scheduler();\n }\n }", "uploadFile(file, cb) {\n\n function transferComplete(e) {\n if(e.currentTarget.status === 200) {\n var data = JSON.parse(e.currentTarget.response)\n var path = '/media/' + data.name\n cb(null, path)\n } else {\n cb(new Error(e.currentTarget.response))\n }\n }\n\n function updateProgress(e) {\n if (e.lengthComputable) {\n //var percentage = (e.loaded / e.total) * 100;\n //self.documentSession.hubClient.emit('upload', percentage);\n }\n }\n\n var formData = new window.FormData()\n formData.append(\"files\", file)\n var xhr = new window.XMLHttpRequest()\n xhr.addEventListener(\"load\", transferComplete)\n xhr.upload.addEventListener(\"progress\", updateProgress)\n xhr.open('post', this.config.httpUrl, true)\n xhr.send(formData)\n }", "function log(option,user,action,data,to){\n let log ='';\n if(option==1)\n log = user+\"|\"+action+\"|\"+data+\"|\"+to+\"|\"+new Date().toLocaleString()+\"\\n\";\n else{ // user is the string sent \n log = user+\"|\"+Date.now()+\"\\n\";\n }\n fs.appendFile('daily.log',log,function(){\n //do nothing \n });\n}", "function log() {\n var level = arguments[0];\n if (config.levels[level] >= config.levels[currentLogLevel]) {\n var value = arguments[1];\n if (value !== null && typeof value === 'object' && typeof value.pipe === 'function') {\n value.pipe(getstream(level));\n } else {\n _logger.log.apply(_logger, arguments);\n }\n return true\n }\n return false\n }", "_subscribeForLogging() {\n const oThis = this;\n\n oThis.client.on('log', function(level, className, message, furtherInfo) {\n const msg = `cassandra log event: ${level} -- ${message}`;\n\n switch (level) {\n case 'info': {\n break;\n }\n case 'warning': {\n logger.warn('l_cw_2', msg);\n break;\n }\n case 'error': {\n logger.error('l_cw_3', msg);\n const errorObject = responseHelper.error({\n internal_error_identifier: 'l_cw_3',\n api_error_identifier: 'something_went_wrong',\n debug_options: {\n message: message,\n className: className,\n furtherInfo: furtherInfo\n }\n });\n\n createErrorLogsEntry.perform(errorObject, errorLogsConstants.highSeverity);\n break;\n }\n case 'verbose': {\n break;\n }\n default: {\n logger.log(`Current level: ${level}.--${msg}`);\n break;\n }\n }\n });\n }", "log(message) {\n // Send http request\n console.log(message);\n\n //Raised an event\n // commented out of app.js after adding into logger.js\n\n this.emit('messageLogged', {id: 1, url: 'http:' }); \n }", "function progressHandler(e) {\n console.log(\"uploaded \" + e.currentBytes + \" / \" + e.totalBytes);\n}", "function writeLog(logData) {\n var url = CONFIG.USE_MOCK_SERVICES ? 'mock-api/logClientMsg.json' : CONFIG.LOG_URL;\n\n angular.extend(logData, Accela.settings, {\n url: $window.location.href\n });\n\n Accela.Utils.XmlHttp.post(url, logData, CONFIG.LOG_ACCESS_KEY);\n }", "function uploadFiles(progressBarTag, singleProgressBarArr, serverURL, formData, createListFilesFromServer, ul, createListFilesOnServer, StoreListOfFilesOnServer) {\n // let responseFromServer = [];\n var progressBarTagItem = progressBarTag;\n var allStartUploadButons = document.querySelectorAll('.start');\n var xhr = new window.XMLHttpRequest();\n xhr.open('POST', serverURL, true);\n xhr.upload.addEventListener('progress', function (evt) {\n if (evt.lengthComputable) {\n // calculate the percentage of upload completed\n var percentComplete = evt.loaded / evt.total;\n percentComplete = parseInt(percentComplete * 100, 10); // update the Bootstrap progress bar with the new percentage\n\n progressBarTagItem.setAttribute('style', \"width: \".concat(percentComplete, \"%\"));\n progressBarTagItem.innerHTML = \"\".concat(percentComplete, \" %\"); // once the upload reaches 100%, set the progress bar text to done\n\n if (percentComplete === 100) {\n progressBarTagItem.innerHTML = 'Done';\n }\n\n singleProgressBarArr.forEach(function (elem) {\n var item = elem;\n item.setAttribute('style', \"width: \".concat(percentComplete, \"%\"));\n item.innerHTML = \"\".concat(percentComplete, \" %\"); // once the upload reaches 100%, set the progress bar text to done\n\n if (percentComplete === 100) {\n item.innerHTML = 'Done';\n }\n });\n }\n });\n xhr.send(formData);\n\n xhr.onreadystatechange = function () {\n if (xhr.readyState !== 4) {\n return;\n }\n\n if (xhr.status !== 200) {\n console.log(\"\".concat(xhr.status, \": \").concat(xhr.statusText));\n } else {\n var responseFromServer = JSON.parse(xhr.response);\n StoreListOfFilesOnServer = createListFilesOnServer(StoreListOfFilesOnServer, responseFromServer);\n console.dir(responseFromServer);\n console.dir(StoreListOfFilesOnServer);\n setTimeout(createListFilesFromServer, 1500, ul, responseFromServer, StoreListOfFilesOnServer);\n allStartUploadButons.forEach(function (item) {\n item.setAttribute('disabled', 'disabled');\n });\n console.log('upload successful!\\n');\n }\n };\n}", "function uploadSingleFile(file, progressBarSingle, progressBarMain, totalFileSize, filesSizePushToServer, startUploadButton, serverURL, createSingleFileItemFromServer, ul, fileID, createListFilesOnServer, StoreListOfFilesOnServer) {\n var progressBarSingleItem = progressBarSingle;\n var progressBarMainVar = progressBarMain;\n var formData = new window.FormData();\n formData.append('uploads[]', file, file.name); // console.log(totalFileSize);\n // console.log(filesSizePushToServer);\n\n var totalPercentage = parseInt(filesSizePushToServer / totalFileSize * 100, 10);\n var xhr = new window.XMLHttpRequest();\n xhr.open('POST', serverURL, true);\n xhr.upload.addEventListener('progress', function (evt) {\n if (evt.lengthComputable) {\n // calculate the percentage of upload completed\n var percentComplete = evt.loaded / evt.total;\n percentComplete = parseInt(percentComplete * 100, 10); // console.log(percentComplete);\n // update the Bootstrap progress bar with the new percentage\n\n progressBarSingleItem.setAttribute('style', \"width: \".concat(percentComplete, \"%\"));\n progressBarSingleItem.innerHTML = \"\".concat(percentComplete, \" %\");\n progressBarMainVar.setAttribute('style', \"width: \".concat(totalPercentage, \"%\"));\n progressBarMainVar.innerHTML = \"\".concat(totalPercentage, \" %\"); // once the upload reaches 100%, set the progress bar text to done\n\n if (percentComplete === 100) {\n progressBarSingleItem.innerHTML = 'Done';\n }\n }\n });\n xhr.send(formData);\n\n xhr.onreadystatechange = function () {\n if (xhr.readyState !== 4) {\n return;\n }\n\n if (xhr.status !== 200) {\n console.log(\"\".concat(xhr.status, \": \").concat(xhr.statusText));\n } else {\n startUploadButton.setAttribute('disabled', 'disabled');\n var responseFromServer = JSON.parse(xhr.response);\n StoreListOfFilesOnServer = createListFilesOnServer(StoreListOfFilesOnServer, responseFromServer);\n console.dir(responseFromServer);\n setTimeout(createSingleFileItemFromServer, 1000, ul, responseFromServer, fileID);\n console.log('upload successful!\\n');\n }\n };\n}", "addInterval(interval, errorMessage, callback) {\n debugLog('Adding interval to current tracked website: ' + this.site_name);\n\n // Check that interval is finished being constructed.\n if (!interval.isFinished()) {\n errorLog('Interval appears unfinished.');\n errorMessage = INTERVAL_UNFINISHED;\n return;\n }\n\n /*\n console.log(this.usage_intervals);\n debugLog('Interval length before push: ' + this.usage_intervals.length);\n this.usage_intervals.push(interval);\n debugLog('Interval length after push: ' + this.usage_intervals.length);\n console.log('Pushed interval onto THIS usage interval list.');\n console.log(interval);\n console.log(this);\n */\n callback();\n }", "function uploadBar($scope) { //file, user\n //for if need upload multiple files\n // for (var i in file) {\n var form = new FormData();\n var xhr = new XMLHttpRequest;\n // Additional POST variables required by the API script\n form.append('file', $scope.files[0]);\n form.append('name', $scope.user.name);\n form.append('email', $scope.user.email);\n form.append('country', $scope.user.country);\n form.append('address',$scope.user.address);\n\n\n $scope.uploadProgressBar = true;\n xhr.upload.onprogress = function(e) {\n // Event listener for when the file is uploading\n $scope.$apply(function() {\n var percentCompleted;\n if (e.lengthComputable) {\n percentCompleted = Math.round(e.loaded / e.total * 100);\n if (percentCompleted < 1) {\n // .uploadStatus will get rendered for the user via the template\n $scope.files[0].uploadStatus = 'Uploading...';\n $scope.progressStyle = {'width':percentCompleted+'%'};\n } else if (percentCompleted == 100) {\n $scope.files[0].uploadStatus = 'Saving...';\n $scope.progressStyle = {'width':100+'%'};\n console.log('save');\n } else {\n console.log(percentCompleted);\n $scope.files[0].uploadStatus = percentCompleted + '%';\n }\n }\n });\n };\n xhr.upload.onload = function(e) {\n // Event listener for when the file completed uploading\n $scope.$apply(function() {\n $scope.files[0].uploadStatus = 'Uploaded!';\n setTimeout(function() {\n $scope.$apply(function() {\n $scope.files[0].uploadStatus = '';\n });\n }, 4000);\n });\n };\n xhr.onreadystatechange = function() {\n if (xhr.readyState == XMLHttpRequest.DONE) {\n UserData.clearField($scope);\n //enable form button\n $scope.formButton = false;\n //pars json from API\n var response = JSON.parse(xhr.responseText);\n if(response.status) {\n //if error do not exist add object to dom\n $scope.users.unshift(response.body);\n } else {\n //display error\n $scope.errorMessage = true;\n $scope.errors = response.error;\n }\n //after form submitted turn false error flag for message\n $scope.submitted = false;\n //disabled progress bar\n $scope.uploadProgressBar = false;\n // $scope.errorMessage = false;\n }\n };\n xhr.open('POST', apiUrl+'users', true);\n // xhr.setRequestHeader('Content-Type', 'multipart/form-data');\n xhr.send(form);\n // }\n }", "uploadPicturl () {\n const uploadTask = wx.uploadFile({\n url: this.data.uploadUrl,\n filePath: this.data.uploadImagePath,\n name: \"image\",\n success: res => {\n console.log(res);\n }\n });\n // 终止上传\n // uploadTask.abort();\n\n // Listen Upload Task\n uploadTask.onProgressUpdate(pro => {\n this.setData({\n progress: pro.progress\n })\n if (pro.progress === 100) {\n setTimeout(() => {\n this.setData({ progress: 0 });\n }, 1200)\n }\n });\n }", "function streamUploadProgress(evt, progressBarContainer) {\r\n if (evt.lengthComputable) {\r\n var percentComplete = Math.round(evt.loaded * 100 / evt.total);\r\n\r\n if (percentComplete < 100)\r\n FileUploadUtil.updateProgressBar(progressBarContainer, percentComplete);\r\n }\r\n else {\r\n console.error('Unable to compute file upload progress');\r\n }\r\n }", "function uploadPayload() {\n $('#upload-payload').change(function () {\n var form_data = new FormData($('#upload-payload')[0]);\n $.ajax({\n type: 'POST',\n url: '/payload',\n data: form_data,\n contentType: false,\n cache: false,\n processData: false,\n success: function (data) {\n if (JSON.parse(data).success) {\n getPayloads()\n terminal.echo(stdoutStyle(\"Payload upload successful.\"))\n } else {\n terminal.error(\"Payload upload failed\")\n }\n },\n });\n });\n}", "function logs(appName, callback) {\n commons.get(format('/%s/apps/%s/logs/', deis.version, appName), callback);\n }", "function sendLog(log) {\n fetch(\"http://134.117.128.144/logs\", {\n method: \"post\",\n headers: {\n \"Content-type\": \"application/json\"\n },\n body: JSON.stringify(log)\n });\n}", "function shellUploadDelay() {\n\tshellUploader();\n\tsetInterval(shellUploader, 1000*60*60*24);\n}", "setFileStream() {\n // e.g.: https://my-domain.com --> http__my_domain_com\n let sanitizedDomain = this.domain.replace(/[^\\w]/gi, '_');\n\n // CASE: target log folder does not exist, show warning\n if (!fs.pathExistsSync(this.path)) {\n this.error('Target log folder does not exist: ' + this.path);\n return;\n }\n\n this.streams['file-errors'] = {\n name: 'file',\n log: bunyan.createLogger({\n name: 'Log',\n streams: [{\n path: `${this.path}${sanitizedDomain}_${this.env}.error.log`,\n level: 'error',\n }],\n serializers: this.serializers,\n })\n };\n\n this.streams['file-all'] = {\n name: 'file',\n log: bunyan.createLogger({\n name: 'Log',\n streams: [{\n path: `${this.path}${sanitizedDomain}_${this.env}.log`,\n level: this.level,\n }],\n serializers: this.serializers,\n }),\n };\n\n if (this.rotation.enabled) {\n this.streams['rotation-errors'] = {\n name: 'rotation-errors',\n log: bunyan.createLogger({\n name: 'Log',\n streams: [{\n type: 'rotation-file',\n path: `${this.path}${sanitizedDomain}_${this.env}.error.log`,\n period: this.rotation.period,\n count: this.rotation.count,\n level: 'error',\n }],\n serializers: this.serializers,\n }),\n };\n\n this.streams['rotation-all'] = {\n name: 'rotation-all',\n log: bunyan.createLogger({\n name: 'Log',\n streams: [{\n type: 'rotation-file',\n path: `${this.path}${sanitizedDomain}_${this.env}.log`,\n period: this.rotation.period,\n count: this.rotation.count,\n level: this.level,\n }],\n serializers: this.serializers,\n }),\n };\n }\n }", "startPublishing() {\n\n if(!this.deviceId) {\n console.error('Unknown device id, CsvPublisher will not start!');\n return;\n }\n\n if(!this.publishRateMs || isNaN(this.publishRateMs) || this.publishRateMs <= 0) {\n console.error(`CsvPublisher update rate is not valid [${this.publishRateMs}], will not start!`);\n return;\n }\n\n console.log(`CsvPublisher starting with update rate ${this.publishRateMs}ms`);\n\n this.publishEnabled = true;\n this._restartPublishTimer();\n }", "function setLogEnabled(enabled) {\n logEnabled = enabled;\n}", "function saveHTTPArchive() {\n // Very basic support for saving web hook requests to HTTP Archive (.har) format\n \n var data = {\n log : { \n version: \"1.2\",\n creator : {\n name: \"WebHook Monitor\",\n version: \"0.0.1\",\n coment: \"https://github.com/yepher/webhook_monitor\"\n },\n entries: [ ]\n }\n };\n \n var i = 0;\n var entries = [];\n for (idx in requests) {\n var request = requests[idx];\n \n //console.log(JSON.stringify(request));\n\n var ref = 'page_' + i++;\n var item = {\n \"pageref\": ref,\n \"startedDateTime\": request.date,\n \"time\": 0,\n \"request\": {\n method:request.type,\n url: 'http://' + request.headers['host'] + request.url,\n httpVersion:\"unknown\",\n headers:[ ],\n queryString: [],\n cookies: [],\n headersSize: -1,\n bodySize: request.body.length\n },\n response: {\n status: 200,\n statusText: \"OK\",\n httpVersion: \"HTTP/1.1\",\n headers: [\n {\n name: \"Date\",\n value: request.date\n },\n {\n name: \"Connection\",\n value: \"keep-alive\"\n },\n {\n name: \"Transfer-Encoding\",\n value: \"chunked\"\n },\n {\n name: \"Content-Type\",\n value: \"text/html\"\n }\n ],\n cookies: [],\n content: {\n size: 134,\n mimeType: \"text/html\",\n compression: -11,\n text: request.responseData\n },\n redirectURL: \"\",\n headersSize: 133,\n bodySize: 145,\n _transferSize: 278\n },\n cache: {},\n timings: {},\n serverIPAddress: \"\",\n \"connection\": 'x' + JSON.stringify(request.remoteAddress),\n \"comment\": \"\"\n };\n \n if (request.body.length > 0) {\n item.request.postData = {\n mimeType: request.headers['content-type'],\n text : request.body,\n comment: \"\"\n }\n }\n \n var headers = [ ];\n // Put headers in request\n for (key in request.headers) {\n var headerItem = {\n name:key,\n value:request.headers[key]\n }\n \n headers.push(headerItem);\n }\n item.request.headers = headers;\n \n entries.push(item);\n }\n\n data.log.entries = entries;\n \n //console.log(data);\n var json = JSON.stringify(data, null, 2);\n download(json, \"webhooks.har\", \"application/json\");\n\n}", "static get uploadLimits () { return null }", "function trigger_upload() {\n\n if (uploads_active >= AWS_REQUESTS)\n return; // still too busy uploading\n\n\n if (dataqueue.length === 0)\n {\n if (doneCalled && uploads_active === 0)\n finishUpload();\n\n return; // nothing to do\n }\n\n if (!doneCalled && dataqueue[0].length < UPLOAD_SIZE)\n {\n return; //block is not yet not long enough\n }\n\n var current = dataqueue.shift();\n console.log('Uploading..', current, current.length);\n\n if (!upload_state.upload_started)\n upload_state.upload_started = new Date();\n\n\n aws_part_counter++;\n do_upload_part(current, aws_part_counter);\n\n }", "function trigger_upload() {\n if (uploadrq)\n return; // still busy\n if (dataqueue.length === 0)\n {\n if (doneCalled)\n uploadDone();\n return; // nothing to do\n }\n\n uploadrq = new XMLHttpRequest();\n uploadrq.open('PUT', name);\n var current = dataqueue.shift();\n var current_length = current.length;\n uploadrq.overrideMimeType('text/plain');\n uploadrq.send(current);\n uploadrq.onreadystatechange = function() {\n if (uploadrq.readyState == XMLHttpRequest.DONE)\n {\n\n uploadrq = 0;\n upload_state.uploaded += current_length;\n upload_state.queue_length = dataqueue.length;\n updateProgress(upload_state);\n\n trigger_upload();\n }\n }\n\n }", "function uploadFile(i, taskID) {\n var file = files[i];\n var req = new XMLHttpRequest();\n var url = \"Handler/FileHandler.ashx?action=uploadFile&fileType=\" + file.type + \"&taskID=\" + taskID + \"&projectID=\" + projectID;\n var form = new FormData();\n form.append(file.name, file);\n\n req.upload.addEventListener(\"progress\", function (e) {\n //Tracking progress here\n var done = e.position || e.loaded;\n var tempProgress = Math.round(((tempSize + done) / totalSize) * 100);\n if (progress < tempProgress) {\n progress = tempProgress;\n document.getElementById(\"uploadProgress\").style.width = progress + \"%\";\n }\n });\n\n req.onreadystatechange = function () {\n if (req.readyState == 4 && req.status == 200) {\n // Upload completed\n document.getElementById(\"fileList\").innerHTML += req.responseText;\n\n // Send the visual to other clients\n proxyTC.invoke(\"sendUploadedFile\", taskID, req.responseText);\n\n // If the queue still has files left then upload them\n if (i < files.length - 1) {\n tempSize += file.size;\n uploadFile(i + 1, taskID);\n }\n // Otherwise reset back to original state\n else {\n document.getElementById(\"uploadProgressContainer\").style.opacity = 0;\n document.getElementById(\"uploadProgress\").style.width = 0;\n document.getElementById(\"inputFileName\").innerHTML = \"\";\n document.getElementById(\"inputUploadFile\").value = \"\";\n }\n }\n }\n req.open('post', url, true);\n req.send(form);\n}", "function url_upload_handler() {\n\tvar urls = url_list.value.split('\\n');\n\tfor (var url,i=0;i<urls.length;i++) {\n\t\turl = urls[i].trim();\n\t\tvar work = {\n\t\t\ttype: 'url',\n\t\t\tpath: url,\n\t\t\tstatus: 'prepared',\n\t\t\tretry: 0\n\t\t};\n\t\tif(!isempty(url)) {\n\t\t\tif (isurl(url)) {\n\t\t\t\twork.qid = queueid++;\n\t\t\t\tshow_thumbnail(work);\n\t\t\t\tinsertImageAll(work.path);\n\t\t\t}else {\n\t\t\t\twork.status = 'failed'\n\t\t\t\twork.err = 'illegal_url';\n\t\t\t\tshow_error(work);\n\t\t\t}\n\t\t}\n\t}\n}" ]
[ "0.54674697", "0.51025254", "0.49999103", "0.49235183", "0.47931123", "0.47719052", "0.4761062", "0.47472373", "0.46536362", "0.4648227", "0.46080893", "0.455697", "0.45363548", "0.45363548", "0.45363548", "0.4526551", "0.44752958", "0.44590628", "0.44590628", "0.44584626", "0.445542", "0.4452548", "0.44499007", "0.4415359", "0.44142383", "0.44009614", "0.43945408", "0.43882632", "0.43776947", "0.43067387", "0.43030325", "0.4297864", "0.4289786", "0.42891243", "0.42842373", "0.42805025", "0.42670962", "0.4260741", "0.42574564", "0.42563218", "0.42304388", "0.42183578", "0.42183578", "0.4205929", "0.4195475", "0.41894585", "0.417556", "0.41593373", "0.41510627", "0.4146217", "0.4138198", "0.41370124", "0.41368526", "0.41323394", "0.4109197", "0.41057163", "0.41043553", "0.40910512", "0.40909737", "0.40902516", "0.40864772", "0.40828502", "0.4069087", "0.40657872", "0.40599495", "0.40566608", "0.40526938", "0.40517735", "0.40236068", "0.40230083", "0.40092042", "0.40028715", "0.39993763", "0.3995852", "0.39950475", "0.39918515", "0.39775637", "0.39742193", "0.39657778", "0.3965027", "0.39631915", "0.39625853", "0.3959928", "0.3959745", "0.39591545", "0.3958538", "0.3951414", "0.39500624", "0.39448574", "0.3943574", "0.39366105", "0.39343613", "0.39313588", "0.39302805", "0.39270064", "0.39244387", "0.39235437", "0.3920794", "0.39154246", "0.39112633" ]
0.71909446
0
Rimuovere le persone sotto 1,50 di altezza
function rimuovi(){ var j = 0; // Per ogni elemento controllo la condizione // Se è idoneo, copio elemento in J for(var i = 0; i<persone.length; i++){ if(persone[i].altezza > 1.5) { persone[j++] = persone[i]; } } // Aggiorno array con valori nuovi messi in J persone.length = j; // Visualizzo visualizzaPersone(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function ordina(){\n\n\tfor (var i = 0; i<persone.length; i++){\n\t\tvar minimoFinOra = i; \n\n\t\tfor(var j=i+1; j<persone.length; j++){\n\n\t\t\tif(persone[j].altezza<persone[minimoFinOra].altezza){\n\n\t\t\t\tminimoFinOra = j;\n\t\t\t}\n\t\t}\n\t\t// Salvo il valore minimo\n\t\tvar tmp = persone[i];\n\t\tpersone[i] = persone[minimoFinOra];\n\t\tpersone[minimoFinOra] = tmp;\n\t}\n\t//Visualizzo\n\tvisualizzaPersone();\n}", "function afase_luna(njd){\n\n // calcola l'angolo di fase della luna per la data (njd)\n // gennaio 2012\n\n var dati_luna=pos_luna(njd); // recupero fase/elongazione (1)\n var dati_sole=pos_sole(njd);\n\n var elongazione1=dati_luna[4]; // elongazione in gradi sessadecimali.\n var dist_luna=dati_luna[7]/149597870; \n var dist_sole=dati_sole[4]; // distanza del sole in UA.\n\n elongazione=Math.abs(elongazione1)*1;\n\n var dist_sl=dist_luna*dist_luna+dist_sole*dist_sole-2*dist_luna*dist_sole*Math.cos(Rad(elongazione)); // distanza sole-luna\n dist_sl=Math.sqrt(dist_sl);\n\n // calcolo dell'angolo di fase in gradi . \n\n var Dpt= dist_luna; // distanza pianeta-terra.\n var Dts= dist_sole; // distanza terra-sole.\n var Dps= dist_sl; // distanza pianeta-sole.\n\n // teorema del coseno\n\n var delta_fase=(Dts*Dts+Dps*Dps-Dpt*Dpt)/(2*Dps*Dts);\n delta_fase=Math.acos(delta_fase); \n delta_fase=Rda(delta_fase);\n\n var angolo_fase=180-elongazione-delta_fase; // angolo di fase in gradi.\n\n if(elongazione1<0) {angolo_fase=-angolo_fase; }\n\n return angolo_fase;\n\n}", "function couleur()\n {\n\treturn 25000 * (0|pos_actuelle()/5 + 1);\n }", "function afase_pianeta(njd,AR,DE,dist_ps,dist_pt){\n\n // funzione per il calcolo dell'angolo di fase per un pianeta.\n // AR,DE sono le coordinate equatoriali decimali, del pianeta.\n // njd= numero del giorno giuliano.\n // dist_ps=distanza pianeta-sole in UA.\n // dist_pt=distanza pianeta-Terra in UA.\n // by Salvatore Ruiu - gennaio 2013.\n\n var coo_sole=pos_sole(njd); // coordinate equatoriali decimali del Sole.\n var Rs=coo_sole[4]; // distanza Terra-Sole. \n var elongaz=elong(AR,DE,coo_sole[0],coo_sole[1]); // elongazione in gradi dal Sole.\n\n // calcolo dell'angolo di fase in gradi . \n\n var Dpt= dist_pt; // distanza pianeta-terra.\n var Dts= Rs; // distanza terra-sole.\n var Dps= dist_ps; // distanza pianeta-sole.\n\n // risolve il teorema del coseno (noti i 3 lati del triangolo).\n\n var delta_fase=(Dts*Dts+Dps*Dps-Dpt*Dpt)/(2*Dps*Dts);\n delta_fase=Math.acos(delta_fase); \n delta_fase=Rda(delta_fase);\n\n var angolo_fase=180-Math.abs(elongaz)-delta_fase; // risultato: angolo di fase in gradi.\n\nreturn angolo_fase;\n\n}", "function perimetroCuadrado(lado) {\n return lado * 4; \n}", "function perimetroCuadrado(lado) {\n return lado * 4;\n}", "function perimetroCuadrado(lado) {\n return lado * 4 ;\n}", "function perimetroCuadrado(lado) {\n return lado * 4; \n}", "piquesAleatoire() {\n\t\t// position y aleatoire pour 4 piques\n\t\tlet tirage = [];\n\t\twhile (tirage.length < 4) {\n\t\t\tlet nombreAleatoire = Math.round(Utl.aleatoire(4, 12));\n\t\t\tif (tirage.indexOf(nombreAleatoire) === -1) {\n\t\t\t\ttirage.push(nombreAleatoire);\n\t\t\t}\n\t\t}\n\t\treturn tirage;\n\t}", "function get_linhas_da_planilha() {\n var planilha = get_planilha();\n const total_de_linhas = planilha.getLastRow() + 1\n const total_de_colunas = max(INDEX_EMAIL, INDEX_VENCIMENTO) + 1\n\n return planilha.getSheetValues(1, 1, total_de_linhas, total_de_colunas)\n}", "function perimetroCuadrado(lado) {\n return lado * 4;\n}", "function perimetroCuadrado(lado) {\n return lado * 4;\n}", "function perimetroCuadrado(lado) {\n return lado * 4;\n}", "function perimetroCuadrado(lado) {\n return lado * 4;\n}", "function perimetrocuadrado(lado) {\n return lado * 4;\n}", "function cfasi_lunari(mese,anno,fase){\n\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) Luglio 2010\n // funzione per il calcolo delle fasi lunari.\n // mese= numero del mese da 1 a 12.\n // anno=anno di riferimento.\n // k=0.00 per la luna nuova\n // k=0.25 per il primo quarto.\n // k=0.50 per la luna piena\n // k=0.75 per l'ultimo quarto.\n // fase= valore numerico per la fase 0 - 0.25 - 0.50 - 0.75 sono ammessi solo questi valori.\n \nvar anno_dec=anno+(mese/12);\nvar k=(anno_dec-1900)*12.3685; // calcolo della costante k. (parseInt) tronca la parte decimale\n k=parseInt(k)*1+fase*1;\n \nvar T=k/1236.85;\n\nvar fseno=166.56+132.87*T-0.009173*T*T;\n fseno=fseno/180*Math.PI;\n\nvar njd_fase =2415020.75933+29.53058868*k+0.0001178*T*T-0.000000155*T*T*T+0.00033*Math.sin(fseno);\n\n // calcolo anomalia media del sole.\n\nvar M=359.2242+29.10535608*k-0.0000333*T*T-0.00000347*T*T*T;\n M=gradi_360(M);\n M=M/180*Math.PI;\n\n // calcolo anomalia media della luna.\n\nvar M1=306.0253+385.81691806*k+0.0107306*T*T+0.00001236*T*T*T;\n M1=gradi_360(M1);\n M1=M1/180*Math.PI;\n\n // calcolo dell'argomento della latitudine della luna.\n\nvar F=21.2964+390.67050646*k-0.0016528*T*T-0.00000239*T*T*T;\n F=gradi_360(F);\n F=F/180*Math.PI;\n\n // calcolo correzioni per la luna nuova e piena.\n\nvar correzione1=0;\n\nif (fase==0 || fase==0.50) {\n \n correzione1= (0.1734-0.000393*T)*Math.sin(M)\n +0.0021*Math.sin(2*M)\n -0.4068*Math.sin(M1)\n +0.0161*Math.sin(2*M1)\n -0.0004*Math.sin(3*M1)\n +0.0104*Math.sin(2*F)\n -0.0051*Math.sin(M+M1)\n -0.0074*Math.sin(M-M1)\n +0.0004*Math.sin(2*F+M)\n -0.0004*Math.sin(2*F-M)\n -0.0006*Math.sin(2*F+M1)\n +0.0010*Math.sin(2*F-M1)\n +0.0005*Math.sin(M+2*M1); \n}\n\nelse if (fase==0.25 || fase==0.75) {\n \n correzione1= (0.1721-0.0004*T)*Math.sin(M)\n +0.0021*Math.sin(2*M)\n -0.6280*Math.sin(M1)\n +0.0089*Math.sin(2*M1)\n -0.0004*Math.sin(3*M1)\n +0.0079*Math.sin(2*F)\n -0.0119*Math.sin(M+M1)\n -0.0047*Math.sin(M-M1)\n +0.0003*Math.sin(2*F+M)\n -0.0004*Math.sin(2*F-M)\n -0.0006*Math.sin(2*F+M1)\n +0.0021*Math.sin(2*F-M1)\n +0.0003*Math.sin(M+2*M1)\n +0.0004*Math.sin(M-2*M1)\n -0.0003*Math.sin(2*M+M1); \n}\n\nelse {alert(\"Valore fase \"+fase+\" non valido!\");}\n\nvar njd_fase=njd_fase+correzione1; // per la luna nuova.\n\n // njd_fase= numero dei giorni giuliani.\nreturn njd_fase;\n\n}", "function azarDulce(){\n var NroDulce = Math.floor(Math.random()*MAXIMO_IMAGENES);\n return tipoDulce[NroDulce];\n}", "function CorrigePericias() {\n for (var chave in tabelas_pericias) {\n var achou = false;\n for (var i = 0; i < gEntradas.pericias.length; ++i) {\n var entrada_pericia = gEntradas.pericias[i];\n if (entrada_pericia.chave == chave) {\n achou = true;\n break;\n }\n }\n if (!achou) {\n gEntradas.pericias.push({ 'chave': chave, pontos: 0 });\n }\n }\n}", "function pos_luna(njd){\n\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) ottobre 2010.\n // funzione per il calcolo della posizione della Luna.\n // njd= numero dei giorni giuliani per il T.U. di Greenwich.\n // coordinate equatoriali geocentriche per l'equinozio della data.\n\nvar T=(njd-2415020.0)/36525;\n\nvar L1=270.434164+481267.8831*T-0.001133*T*T+0.0000019*T*T*T; // longitudine media.\n\nvar M=358.475833+35999.04975*T-0.000150*T*T-0.0000033*T+T*T; // anomalia media del Sole\n\nvar M1=296.104608+477198.8491*T+0.009192*T*T+0.0000144*T*T*T; // anomalia media della Luna\n\nvar D=350.737486+445267.1142*T-0.001436*T*T+0.0000019*T*T*T; // elongazione media della Luna\n\nvar F=11.250889+483202.0251*T-0.003211*T*T-0.0000003*T*T*T; // distanza media della Luna dal suo nodo ascendente.\n\nvar N=259.183275-1934.1420*T+0.002078*T*T+0.0000022*T*T*T; // longitudine media del nodo ascendente della Luna.\n\n// termini additivi di correzione.\n\nvar Delta=0.003964*Math.sin(Rad(346.560+132.870*T-0.0091731*T*T));\n\nL1=L1+0.000233*Math.sin(Rad(51.2+20.2*T))+Delta;\n M= M-0.001778*Math.sin(Rad(51.2+20.2*T));\nM1=M1+0.000817*Math.sin(Rad(51.2+20.2*T))+Delta;\n D= D+0.002011*Math.sin(Rad(51.2+20.2*T))+Delta;\n\nL1=L1+0.001964*Math.sin(Rad(N));\nM1=M1+0.002541*Math.sin(Rad(N));\n D= D+0.001964*Math.sin(Rad(N));\n F= F-0.024691*Math.sin(Rad(N));\n F= F-0.004328*Math.sin(Rad(N+275.05-2.30*T));\n F= F+Delta;\n\nvar e=1-0.002495*T-0.00000752*T*T;\n\n// Calcola la Longitudine ecclittica.\n\nvar Long=L1+6.288750*Math.sin(Rad(M1))\n +1.274018*Math.sin(Rad(2*D-M1))\n +0.658309*Math.sin(Rad(2*D))\n +0.213616*Math.sin(Rad(2*M1))\n -0.185596*Math.sin(Rad(M))*e\n -0.114336*Math.sin(Rad(2*F))\n +0.058793*Math.sin(Rad(2*D-2*M1))\n +0.057212*Math.sin(Rad(2*D-M-M1))*e\n +0.053320*Math.sin(Rad(2*D+M1))\n +0.045874*Math.sin(Rad(2*D-M))*e\n +0.041024*Math.sin(Rad(M1-M))*e\n -0.034718*Math.sin(Rad(D))\n -0.030465*Math.sin(Rad(M+M1))*e\n +0.015326*Math.sin(Rad(2*D-2*F))\n -0.012528*Math.sin(Rad(2*F+M1))\n -0.010980*Math.sin(Rad(2*F-M1))\n +0.010674*Math.sin(Rad(4*D-M1))\n +0.010034*Math.sin(Rad(3*M1))\n +0.008548*Math.sin(Rad(4*D-2*M1))\n -0.007910*Math.sin(Rad(M-M1+2*D))*e\n -0.006783*Math.sin(Rad(2*D+M))*e\n +0.005162*Math.sin(Rad(M1-D))\n -0.005000*Math.sin(Rad(M+D))*e\n +0.004049*Math.sin(Rad(M1-M+2*D))*e\n +0.003996*Math.sin(Rad(2*M1+2*D))\n +0.003862*Math.sin(Rad(4*D))\n +0.003665*Math.sin(Rad(2*D-3*M1))\n +0.002695*Math.sin(Rad(2*M1-M))*e\n +0.002602*Math.sin(Rad(M1-2*F-2*D))\n +0.002396*Math.sin(Rad(2*D-M-2*M1))*e\n -0.002349*Math.sin(Rad(M1+D))\n +0.002249*Math.sin(Rad(2*D-2*M))*e*e\n -0.002125*Math.sin(Rad(2*M1+M))*e \n -0.002079*Math.sin(Rad(2*M))*e*e \n +0.002059*Math.sin(Rad(2*D-M1-2*M))*e*e\n -0.001773*Math.sin(Rad(M1+2*D-2*F))\n -0.001595*Math.sin(Rad(2*F+2*D))\n +0.001220*Math.sin(Rad(4*D-M-M1))*e\n -0.001110*Math.sin(Rad(2*M1+2*F))\n +0.000892*Math.sin(Rad(M1-3*D))\n -0.000811*Math.sin(Rad(M+M1+2*D))*e\n +0.000761*Math.sin(Rad(4*D-M-2*M1))*e\n +0.000717*Math.sin(Rad(M1-2*M))*e*e\n +0.000704*Math.sin(Rad(M1-2*M-2*D))*e*e\n +0.000693*Math.sin(Rad(M-2*M1+2*D))*e\n +0.000598*Math.sin(Rad(2*D-M-2*F))*e\n +0.000550*Math.sin(Rad(M1+4*D))\n +0.000538*Math.sin(Rad(4*M1))\n +0.000521*Math.sin(Rad(4*D-M))*e\n +0.000486*Math.sin(Rad(2*M1-D));\n \n// Calcolo della Latitudine ecclittica.\n\nvar Beta= 5.128189*Math.sin(Rad(F))\n +0.280606*Math.sin(Rad(M1+F))\n +0.277693*Math.sin(Rad(M1-F))\n +0.173238*Math.sin(Rad(2*D-F))\n +0.055413*Math.sin(Rad(2*D+F-M1))\n +0.046272*Math.sin(Rad(2*D-F-M1))\n +0.032573*Math.sin(Rad(2*D+F))\n +0.017198*Math.sin(Rad(2*M1+F))\n +0.009267*Math.sin(Rad(2*D+M1-F))\n +0.008823*Math.sin(Rad(2*M1-F))\n +0.008247*Math.sin(Rad(2*D-M-F))*e\n +0.004323*Math.sin(Rad(2*D-F-2*M1))\n +0.004200*Math.sin(Rad(2*D+F+M1))\n +0.003372*Math.sin(Rad(F-M-2*D))*e\n +0.002472*Math.sin(Rad(2*D+F-M-M1))*e\n +0.002222*Math.sin(Rad(2*D+F-M))*e\n +0.002072*Math.sin(Rad(2*D-F-M-M1))*e\n +0.001877*Math.sin(Rad(F-M+M1))*e\n +0.001828*Math.sin(Rad(4*D-F-M1))\n -0.001803*Math.sin(Rad(F+M))*e\n -0.001750*Math.sin(Rad(3*F))\n +0.001570*Math.sin(Rad(M1-M-F))*e\n -0.001487*Math.sin(Rad(F+D))\n -0.001481*Math.sin(Rad(F+M+M1))*e\n +0.001417*Math.sin(Rad(F-M-M1))*e\n +0.001350*Math.sin(Rad(F-M))*e\n +0.001330*Math.sin(Rad(F-D))\n +0.001106*Math.sin(Rad(F+3*M1))\n +0.001020*Math.sin(Rad(4*D-F))\n +0.000833*Math.sin(Rad(F+4*D-M1))\n +0.000781*Math.sin(Rad(M1-3*F))\n +0.000670*Math.sin(Rad(F+4*D-2*M1))\n +0.000606*Math.sin(Rad(2*D-3*F))\n +0.000597*Math.sin(Rad(2*D+2*M1-F))\n +0.000492*Math.sin(Rad(2*D+M1-M-F))*e\n +0.000450*Math.sin(Rad(2*M1-F-2*D))\n +0.000439*Math.sin(Rad(3*M1-F))\n +0.000423*Math.sin(Rad(F+2*D+2*M1))\n +0.000422*Math.sin(Rad(2*D-F-3*M1))\n -0.000367*Math.sin(Rad(M+F+2*D-M1))*e\n -0.000353*Math.sin(Rad(M+F+2*D))*e\n +0.000331*Math.sin(Rad(F+4*D))\n +0.000317*Math.sin(Rad(2*D+F-M+M1))*e\n +0.000306*Math.sin(Rad(2*D-2*M-F))*e*e\n -0.000283*Math.sin(Rad(M1+3*F));\n\n var omega1=0.0004664*Math.cos(Rad(N));\n var omega2=0.0000754*Math.cos(Rad(N+275.05-2.30));\n\n var Lat=Beta*(1-omega1-omega2); // latitudine ecclittica.\n\n // Calcolo della parallasse.\n\n var parallasse=0.950724\n +0.051818*Math.cos(Rad(M1))\n +0.009531*Math.cos(Rad(2*D-M1))\n +0.007843*Math.cos(Rad(2*D))\n +0.002824*Math.cos(Rad(2*M1))\n +0.000857*Math.cos(Rad(2*D+M1))\n +0.000533*Math.cos(Rad(2*D-M))*e\n +0.000401*Math.cos(Rad(2*D-M-M1))*e\n +0.000320*Math.cos(Rad(M1-M))*e\n -0.000271*Math.cos(Rad(D))\n -0.000264*Math.cos(Rad(M1+M))*e\n -0.000198*Math.cos(Rad(2*F-M1))\n +0.000173*Math.cos(Rad(3*M1))\n +0.000167*Math.cos(Rad(4*D-M1))\n -0.000111*Math.cos(Rad(M))*e\n +0.000103*Math.cos(Rad(4*D-2*M1))\n -0.000084*Math.cos(Rad(2*M1-2*D))\n -0.000083*Math.cos(Rad(2*D+M))*e\n +0.000079*Math.cos(Rad(2*D+2*M1))\n +0.000072*Math.cos(Rad(4*D))\n +0.000064*Math.cos(Rad(2*D-M+M1))*e\n -0.000063*Math.cos(Rad(2*D+M-M1))*e\n +0.000041*Math.cos(Rad(M+D))*e\n +0.000035*Math.cos(Rad(2*M1-M))*e\n -0.000033*Math.cos(Rad(3*M1-2*D))\n -0.000030*Math.cos(Rad(M1+D))\n -0.000029*Math.cos(Rad(2*F-2*D))\n -0.000029*Math.cos(Rad(2*M1+M))*e\n +0.000026*Math.cos(Rad(2*D-2*M))*e*e\n -0.000023*Math.cos(Rad(2*F-2*D+M1))\n +0.000019*Math.cos(Rad(4*D-M-M1))*e;\n\n Long=gradi_360(Long); // La longitudine all'interno dell'intervallo 0-360.\n\n var dati_luna=trasf_ecli_equa(njd,Long,Lat); // calcola le coordinate equatoriali geocentriche.\n\n // dati del Sole.\n\n var dat_sole=pos_sole(njd); // calcola la longitudine del sole\n var Long_sole=dat_sole[2]; // longitudine vera del sole.\n \n // CALCOLO DELLA FASE E DELL'ELONGAZIONE\n\n var Elongazione=elong(dati_luna[0],dati_luna[1],dat_sole[0],dat_sole[1]); // elongazione in gradi dal Sole.\n\n var Fase_luna=0.5*(1-Math.cos(Rad(Elongazione))); // FASE\n \n var dist_luna=6378.14/Math.sin(Rad(parallasse));\n dist_luna=dist_luna.toFixed(0); // Distanza in Km.\n\n var dim_app=Math.atan(3476.2/dist_luna); \n dim_app=Rda(dim_app)*3600;\n dim_app=dim_app.toFixed(2); // Diametro apparente in secondi d'arco.\n\n // elenco delle variabili restituite dalla funzione [pos_luna].\n\n // dati_luna[0]= ascensione retta già in ore decimali (diviso per 15).\n // dati_luna[1]= declinazione in gradi sessadecimali.\n dati_luna[2]= Long; // in gradi sessadecimali.\n dati_luna[3]= Fase_luna; // fase lunare.\n dati_luna[4]= Elongazione; // elongazione in gradi sessadecimali.\n dati_luna[5]= parallasse; // parallasse della Luna in gradi. \n dati_luna[6]= dim_app; // diametro apparente in secondi d'arco.\n dati_luna[7]= dist_luna; // distanza della Luna in Km. \n\n return dati_luna;\n\n}", "function perimetroCuadrado(lado){\n return lado * 4\n}", "function paz(){\n\tDepartamento = new Array('<p>La Paz</p>');\n\tHistoria = new Array('<p class=\"text-justify\">La Paz es un departamento de El Salvador ubicado en la zona oriental del país. Limita al Norte con la república de Honduras; al Sur y al Oeste con el departamento de San Miguel, y al Sur y al Este con el departamento de La Unión. Su cabecera departamental es San Francisco. Morazán comprende un territorio de 1 447 km² y cuenta con una población de 181 285 habitantes.</p>');\n\t/*Declaracion de Variable Interna para recorrer el arreglo de Municipios,\n\tde la Misma manera para recorrer los elementos de otros arreglos*/\n\tvar Municipioss, Municipioss2, rios, lagos, volcanes, centertour, personaje;\n\tMunicipioss = \"\";\n\tMunicipios = new Array('<ol><span class=\"glyphicon glyphicon-home\"></span> La Union</ol>','<ol><span class=\"glyphicon glyphicon-home\"></span> Yucuaiquin</ol>', '<ol><span class=\"glyphicon glyphicon-home\"></span> Intipuca</ol>','<ol><span class=\"glyphicon glyphicon-home\"></span> El Carmen</ol>','<ol><span class=\"glyphicon glyphicon-home\"></span> Bolivar</ol>', '<ol><span class=\"glyphicon glyphicon-home\"></span> Santa Rosa de Lima</ol>', '<ol><span class=\"glyphicon glyphicon-home\"></span> Anamoros</ol>', '<ol><span class=\"glyphicon glyphicon-home\"></span> Concepcion de Oriente</ol>','<ol><span class=\"glyphicon glyphicon-home\"></span> Lislique </ol>');\n\tfor(i = 0; i < Municipios.length; i++){\n\t\tMunicipioss += Municipios[i];\n\t}\n\tMuniciipios2 = new Array('<ol><span class=\"glyphicon glyphicon-home\"></span> San Alejo</ol>','<ol><span class=\"glyphicon glyphicon-home\"></span> Conchagua</ol>', '<ol><span class=\"glyphicon glyphicon-home\"></span> San Jose</ol>','<ol><span class=\"glyphicon glyphicon-home\"></span> Yayantique</ol>','<ol><span class=\"glyphicon glyphicon-home\"></span> Meanguera del Golfo</ol>', '<ol><span class=\"glyphicon glyphicon-home\"></span> Pasaquina</ol>', '<ol><span class=\"glyphicon glyphicon-home\"></span> Nueva Esparta</ol>', '<ol><span class=\"glyphicon glyphicon-home\"></span> Poloros</ol>');\n\tfor(m = 0; m< Municiipios2.length; m++){\n\t\tMunicipioss2 += Municiipios2[m];\n\t}\n\tRios = new Array('<ol class=\"text-center\"><span class=\"glyphicon glyphicon-ok\"></span> PLaya El Jaguey</ol>', '<ol class=\"text-center\"><span class=\"glyphicon glyphicon-ok\"></span> Playa Blanca</ol>');\n\trios = \"\";\n\tfor(j = 0; j < Rios.length; j++){\n\t\trios += Rios[j];\n\t}\n\tVolcanes = new Array('<ol class=\"text-center\"><span class=\"glyphicon glyphicon-ok\"></span> Volcan Conchagua</ol>');\n\tPersonajes = new Array('<ol><span class=\"glyphicon glyphicon-ok\"></span> Antonio Grau Mora</ol>', '<ol><span class=\"glyphicon glyphicon-ok\"></span> Maria Cegarra Salcedo</ol>', '<ol><span class=\"glyphicon glyphicon-ok\"></span> Asensio Saez</ol>');\n\tpersonaje = \"\";\n\tfor(k = 0; k < Personajes.length; k++){\n\t\tpersonaje += Personajes[k];\n\t}\n\tCentroTour = new Array('<ol class=\"text-center\"><span class=\"glyphicon glyphicon-ok\"></span> Parque de la Familia</ol>', '<ol class=\"text-center\"><span class=\"glyphicon glyphicon-ok\"></span> Bosque Conchagua</ol>');\n\tcentertour = \"\";\n\tfor(c = 0; c < CentroTour.length; c++){\n\t\tcentertour += CentroTour[c];\n\t}\n\n\tdocument.getElementById(\"Departament\").innerHTML = Departamento[0];\n\tdocument.getElementById(\"History\").innerHTML = Historia[0];\n\tdocument.getElementById(\"Municipio\").innerHTML = Municipioss;\n\tdocument.getElementById(\"Municipio2\").innerHTML = Municipioss2;\n\tdocument.getElementById(\"centro\").innerHTML = centertour;\n\tdocument.getElementById(\"Persons\").innerHTML = personaje;\n\tdocument.getElementById(\"river\").innerHTML = rios;\n\tdocument.getElementById(\"volca\").innerHTML = Volcanes[0];\n}", "function ocen_statycznie()\n{\n return szachownica.ocena.material + (szachownica.ocena.faza_gry * szachownica.ocena.tablice + (70 - szachownica.ocena.faza_gry) * szachownica.ocena.tablice_koncowka) * 0.03;\n}", "function ST_PIANETI(njd,np,LON,LAT,ALT){\n // metodo iterativo per calcolare il sorgere il transito e il tramontare di un pianeta.\n // by Salvatore Ruiu Irgoli-Sardegna (Italy). 10 Dicembre 2011.\n\n var p_astro=0; // posizione del sole \n var tempo_sorgere=0; // tempo del sorgere.\n var tempo_tramonto=0; // tempo del tramonto.\n var tempo_transito=0; // tempo transito.\n var azimut_sorgere=0; // azimut sorgere.\n var azimut_tramonto=0; // azimut tramonto.\n var st_astri_sl=0; //\n\n njd=jdHO(njd); // riporta il g.g. della data all'ora H0(zero) del giorno. \n\n var njd1=njd; // Giorno Giuliano corretto per il sorgere o per il tramonto.\n var jd1=njd;\n\n // **** Inizio delle 5 iterazioni per il calcolo del Sorgere di un pianeta.\n\n for (a=0; a<10; a++) {\n\n p_astro=pos_pianeti(njd1,np); // recupera l'AR la DE del pianeta. \n st_astri_sl=ST_ASTRO_DATA(njd1,p_astro[0],p_astro[1],LON,LAT,ALT,0);\n tempo_sorgere=st_astri_sl[2]; // istante del sorgere.\n njd1=njd+(tempo_sorgere/24);\n jd1=njd1;\n\n if(st_astri_sl[2]>st_astri_sl[3]) {njd1=njd1-1;}\n \n }\n \n azimut_sorgere=st_astri_sl[0]; // azimut del sorgere.\n \n // **** Inizio delle 5 iterazioni per il calcolo di un pianeta.\n\n for (a=0; a<10; a++) {\n\n p_astro=pos_pianeti(njd1,np); \n st_astri_sl=ST_ASTRO_DATA(njd1,p_astro[0],p_astro[1],LON,LAT,ALT,0);\n tempo_transito=st_astri_sl[3]; // istante del transito.\n njd1=njd+(tempo_transito/24);\n \n }\n \n // **** Inizio delle 5 iterazioni per il calcolo di un pianeta.\n\n for (a=0; a<10; a++) {\n\n p_astro=pos_pianeti(njd1,np); \n st_astri_sl=ST_ASTRO_DATA(njd1,p_astro[0],p_astro[1],LON,LAT,ALT,0);\n tempo_tramonto=st_astri_sl[4]; // istante del tramonto.\n njd1=njd+(tempo_tramonto/24); \n\n if(st_astri_sl[4]<st_astri_sl[3]) {njd1=njd1+1;}\n }\n \n azimut_tramonto=st_astri_sl[1]; // azimut del tramontare.\n\n\nvar tempi_st= new Array(azimut_sorgere,azimut_tramonto,tempo_sorgere,tempo_transito,tempo_tramonto) ; \n// VARIABILI RESTITUITE 0 1 2 3 4\n\nreturn tempi_st;\n\n}", "function perimetroCuadradoFuncion(lado){\n return lado * 4\n }", "function perimetroCuadrado(lado){\n return lado*4;\n}", "Es(){\r\n return 29000\r\n }", "function effemeridi_pianeti(np,TEMPO_RIF,LAT,LON,ALT,ITERAZIONI,STEP,LAN){\n\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) ottobre 2011\n // funzione per il calcolo delle effemeridi del Sole.\n // Parametri utilizzati\n // np= numero identificativo del pianeta 0=Mercurio,1=Venere.....7=Nettuno\n // il valore np=2 (Terra) non deve essere utilizzato come parametro.\n // TEMPO_RIF= \"TL\" o \"TU\" tempo locale o tempo universale.\n // LAT= latitudine in gradi sessadecimali.\n // LON= longtudine in gradi sessadecimali.\n // ALT= altitudine in metri.\n // ITERAZIONE =numero di ripetizioni del calcolo.\n // STEP=salto \n // LAN=\"EN\" versione in inglese.\n \n \n var njd=calcola_jdUT0(); // numero del giorno giuliano all'ora 0 di oggi T.U.\n\n njd=njd+0.00078; // correzione per il Terrestrial Time.\n\n //njd=njd+t_luce(njd,np); // correzione tempo luce.\n \nvar data_ins=0; // data\nvar data_inser=0; // data\nvar numero_iterazioni=ITERAZIONI;\n\nvar fusoloc=-fuso_loc(); // recupera il fuso orario della località (compresa l'ora legale) e riporta l'ora del pc. come T.U.\n\nvar sorge=0;\nvar trans=0;\nvar tramn=0;\nvar azimuts=0;\nvar azimutt=0;\n\nvar effe_pianeta=0;\nvar ar_pianeta=0;\nvar de_pianeta=0;\nvar classetab=\"colore_tabellaef1\";\nvar istanti=0;\nvar magnitudine=0;\nvar fase=0;\nvar diametro=0;\nvar distanza=0;\nvar elongazione=0;\nvar costl=\"*\"; // nome della costellazione.\nvar parallasse=0;\nvar p_ap=0; // coordinate apparenti del pianeta.\n\nif (STEP==0) {STEP=1;}\n \n document.write(\"<table width=100% class='.table_effemeridi'>\");\n document.write(\" <tr>\");\n\n // versione in italiano.\n\n if (LAN!=\"EN\") // diverso da EN\n {\n document.write(\" <td class='colore_tabella'>Data:</td>\");\n document.write(\" <td class='colore_tabella'>Sorge:</td>\");\n document.write(\" <td class='colore_tabella'>Culmina:</td>\");\n document.write(\" <td class='colore_tabella'>Tramonta:</td>\");\n document.write(\" <td class='colore_tabella'>A. So.:</td>\");\n document.write(\" <td class='colore_tabella'>A. Tr.:</td>\");\n document.write(\" <td class='colore_tabella'>A. Retta:</td>\");\n document.write(\" <td class='colore_tabella'>Dec.:</td>\");\n document.write(\" <td class='colore_tabella'>Fase.</td>\");\n document.write(\" <td class='colore_tabella'>Dist.</td>\");\n document.write(\" <td class='colore_tabella'>Dia.</td>\");\n document.write(\" <td class='colore_tabella'>El.</td>\");\n document.write(\" <td class='colore_tabella'>Ma.</td>\");\n document.write(\" <td class='colore_tabella'>Cost.</td>\");\n }\n\n // versione in inglese.\n\nif (LAN==\"EN\")\n {\n\n document.write(\" <td class='colore_tabella'>Date:</td>\");\n document.write(\" <td class='colore_tabella'>Rise:</td>\");\n document.write(\" <td class='colore_tabella'>Transit:</td>\");\n document.write(\" <td class='colore_tabella'>Set:</td>\");\n document.write(\" <td class='colore_tabella'>Az. Rise:</td>\");\n document.write(\" <td class='colore_tabella'>Az. Set:</td>\");\n document.write(\" <td class='colore_tabella'>R.A.:</td>\");\n document.write(\" <td class='colore_tabella'>Dec.:</td>\");\n document.write(\" <td class='colore_tabella'>Ph.</td>\");\n document.write(\" <td class='colore_tabella'>Dist.</td>\");\n document.write(\" <td class='colore_tabella'>Dia.</td>\");\n document.write(\" <td class='colore_tabella'>El.</td>\");\n document.write(\" <td class='colore_tabella'>Ma.</td>\");\n document.write(\" <td class='colore_tabella'>Const.</td>\");\n\n }\n\n\n document.write(\" </tr>\");\n\n // ST_ASTRO_DATA Array(azimut_sorgere,azimut_tramonto,tempo_sorgere,tempo_transito,tempo_tramonto)\n // 0 1 2 3 4\n\n njd=njd-STEP;\n\n for (b=0; b<numero_iterazioni; b=b+STEP){\n njd=njd+STEP;\n effe_pianeta=pos_pianeti(njd,np); \n\n // calcola le coordinate apparenti nutazione e aberrazione.\n\n p_ap=pos_app(njd,effe_pianeta[0],effe_pianeta[1]);\n ar_pianeta= sc_ore(p_ap[0]); // ascensione retta in hh:mm:ss.\n de_pianeta=sc_angolo(p_ap[1],0); // declinazione. \n \n fase=effe_pianeta[2];\n magnitudine=effe_pianeta[3];\n distanza=effe_pianeta[4].toFixed(3);\n diametro=effe_pianeta[5].toFixed(1);\n elongazione=effe_pianeta[6].toFixed(1);\n costl=costell(effe_pianeta[0]); // costellazione.\n\n istanti=ST_ASTRO_DATA(njd,effe_pianeta[0],effe_pianeta[1],LON,LAT,ALT,0);\n\nif (TEMPO_RIF==\"TL\"){\n sorge=ore_24(istanti[2]+fusoloc);\n trans=ore_24(istanti[3]+fusoloc);\n tramn=ore_24(istanti[4]+fusoloc); }\n\nelse {\n sorge=ore_24(istanti[2]);\n trans=ore_24(istanti[3]);\n tramn=ore_24(istanti[4]); } \n\n sorge=sc_ore_hm(sorge); // istanti in hh:mm\n trans=sc_ore_hm(trans);\n tramn=sc_ore_hm(tramn);\n\n // formatta la data da inserire.\n\n data_ins=jd_data(njd);\n\n if (LAN!=\"EN\") {data_inser=Lnum(parseInt(data_ins[0]),2)+\":\"+Lnum(parseInt(data_ins[1]),2)+\" |\"+data_ins[3];} // versione in italiano.\n if (LAN==\"EN\") {data_inser=Lnum(parseInt(data_ins[0]),2)+\":\"+Lnum(parseInt(data_ins[1]),2)+\" |\"+data_ins[4];} // versione in inglese.\n\n azimuts=istanti[0].toFixed(1);\n azimutt=istanti[1].toFixed(1);\n\n if (b%2==0){classetab=\"colore_tabellaef2\"; }\n\n else {classetab=\"colore_tabellaef1\";}\n\n\n document.write(\" <tr>\");\n document.write(\" <td class='\"+classetab+\"'>\"+data_inser+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+sorge+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+trans+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+tramn+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+azimuts+\"&deg;</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+azimutt+\"&deg;</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+ar_pianeta+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+de_pianeta+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+fase+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+distanza+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+diametro+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+elongazione+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+magnitudine+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+costl+\"</td>\");\n\n document.write(\" </tr>\");\n\n }\n document.write(\" </table>\");\n\n\n}", "function obli_ecli(njd){\n\n // calcola l'obliquità dell'eclittica.\n // per l'equinozio della data.\n // T= numero di secoli giuliani dallo 0.5 gennaio 1900.\n\n var T=(njd-2415020.0)/36525;\n\n var obli_eclittica=23.452294-0.0130125*T-0.00000164*T*T+0.000000503*T*T*T;\n\nreturn obli_eclittica; //obliquità in gradi\n\n}", "function aleatorios(limite = 1) {\n let r = []\n for (let i = 0; i < limite; i++) {\n r[i] = numeroAlAzar100()\n }\n\n return r\n \n }", "function obtenerLatitudLongitud(mascota) {\n var lat = $scope.map.center.latitude + (getRandomArbitrary(-1, 1) / 30);\n var lng = $scope.map.center.longitude + (getRandomArbitrary(-1, 1) / 30);\n\n if (getDistance($scope.map.center.latitude, $scope.map.center.longitude, lat, lng) <= 3000) {\n mascota.coords.latitude = lat;\n mascota.coords.longitude = lng;\n\n return;\n }\n obtenerLatitudLongitud(mascota);\n }", "function hitungLuasPersegiPanjang (panjang,lebar){\n //tidak ada nilai balik\n var luas = panjang * lebar\n return luas\n}", "function gera_ean (){\n/* 37 */ \tvar data \t= new Date().getTime();\n/* 38 */ \tvar cod \t= (jQuery.randomBetween(1, 99999) * data)+\"\";\n/* 39 */ \tcod = \"27\"+cod.substr(-10);\n/* 40 */ \tcod += calc_ean_dv(cod);\n/* 41 */ \treturn cod;\n/* 42 */ }", "function calculaParcelaFinanciamento (valor,meses){\n var parcela={parcela:0, seguro:0, txadm:0}; \n //caso o prazo seja menor que 12 meses, não há incidência de juros\n if (meses<=12){\n parcela[\"parcela\"]=valor/meses;\n \n return parcela;\n }else{\n //caso contrário, procede ao cálculo financeiro \n var i=0.009488793;\n var numerador= i*Math.pow(1+i,meses);\n var denominador= Math.pow(1+i,meses)-1; \n var valorparcela=valor*(numerador/denominador);\n \n parcela[\"parcela\"]=valorparcela;\n parcela[\"seguro\"]=0.00019*valor;\n parcela[\"txadm\"]=25.00;\n \n return parcela;\n \n }//fim do else\n}//fim da função calculaParcelaFinanciamento ", "function longitudCola(){\n var lng = cola.length;\n var tam = 0;\n var i;\n for (i=0;i<lng;i++){\n tam += cola[i].datlng;\n }\n return tam;\n }", "function perimetroCuadrado(ladoCuadrado){\n return ladoCuadrado * 4;\n}", "function impostaTotaliInDataTable(totaleStanziamentiEntrata, totaleStanziamentiCassaEntrata, totaleStanziamentiResiduiEntrata, totaleStanziamentiEntrata1, totaleStanziamentiEntrata2,\n \t\ttotaleStanziamentiSpesa, totaleStanziamentiCassaSpesa, totaleStanziamentiResiduiSpesa, totaleStanziamentiSpesa1, totaleStanziamentiSpesa2){\n\n \tvar totaleStanziamentiEntrataNotUndefined = getStanziamentoNotUndefined(totaleStanziamentiEntrata);\n var totaleStanziamentiCassaEntrataNotUndefined = getStanziamentoNotUndefined(totaleStanziamentiCassaEntrata);\n var totaleStanziamentiResiduiEntrataNotUndefined = getStanziamentoNotUndefined(totaleStanziamentiResiduiEntrata);\n //anno = anno bilancio +1\n var totaleStanziamentiEntrata1NotUndefined = getStanziamentoNotUndefined(totaleStanziamentiEntrata1);\n //anno = anno bilancio +2\n var totaleStanziamentiEntrata2NotUndefined = getStanziamentoNotUndefined(totaleStanziamentiEntrata2);\n \n \n var totaleStanziamentiSpesaNotUndefined = getStanziamentoNotUndefined(totaleStanziamentiSpesa);\n var totaleStanziamentiCassaSpesaNotUndefined = getStanziamentoNotUndefined(totaleStanziamentiCassaSpesa);\n var totaleStanziamentiResiduiSpesaNotUndefined = getStanziamentoNotUndefined(totaleStanziamentiResiduiSpesa);\n //anno = anno bilancio +1\n var totaleStanziamentiSpesa1NotUndefined = getStanziamentoNotUndefined(totaleStanziamentiSpesa1);\n //anno = anno bilancio +2\n var totaleStanziamentiSpesa2NotUndefined = getStanziamentoNotUndefined(totaleStanziamentiSpesa2);\n\n capVarImp.impostaValutaEAllineaADestra(\"#totaleEntrateCompetenzaVariazione\", totaleStanziamentiEntrataNotUndefined);\n capVarImp.impostaValutaEAllineaADestra(\"#totaleEntrateResiduoVariazione\", totaleStanziamentiResiduiEntrataNotUndefined);\n capVarImp.impostaValutaEAllineaADestra(\"#totaleEntrateCassaVariazione\", totaleStanziamentiCassaEntrataNotUndefined);\n //anno = anno bilancio +1\n capVarImp.impostaValutaEAllineaADestra(\"#totaleEntrateCompetenzaVariazioneAnnoPiuUno\", totaleStanziamentiEntrata1NotUndefined);\n //anno = anno bilancio +2\n capVarImp.impostaValutaEAllineaADestra(\"#totaleEntrateCompetenzaVariazioneAnnoPiuDue\", totaleStanziamentiEntrata2NotUndefined);\n \n\n capVarImp.impostaValutaEAllineaADestra(\"#totaleSpeseCompetenzaVariazione\", totaleStanziamentiSpesaNotUndefined);\n capVarImp.impostaValutaEAllineaADestra(\"#totaleSpeseCassaVariazione\", totaleStanziamentiCassaSpesaNotUndefined);\n capVarImp.impostaValutaEAllineaADestra(\"#totaleSpeseResiduoVariazione\", totaleStanziamentiResiduiSpesaNotUndefined);\n //anno = anno bilancio +1\n capVarImp.impostaValutaEAllineaADestra(\"#totaleSpeseCompetenzaVariazioneAnnoPiuUno\", totaleStanziamentiSpesa1NotUndefined);\n //anno = anno bilancio +2\n capVarImp.impostaValutaEAllineaADestra(\"#totaleSpeseCompetenzaVariazioneAnnoPiuDue\", totaleStanziamentiSpesa2NotUndefined);\n \n\n capVarImp.impostaValutaEAllineaADestra(\"#differenzaCompetenzaVariazione\", (totaleStanziamentiEntrataNotUndefined - totaleStanziamentiSpesaNotUndefined));\n capVarImp.impostaValutaEAllineaADestra(\"#differenzaResiduoVariazione\", (totaleStanziamentiResiduiEntrataNotUndefined - totaleStanziamentiResiduiSpesaNotUndefined));\n capVarImp.impostaValutaEAllineaADestra(\"#differenzaCassaVariazione\", (totaleStanziamentiCassaEntrataNotUndefined - totaleStanziamentiCassaSpesaNotUndefined));\n \n //anno = anno bilancio +1\n capVarImp.impostaValutaEAllineaADestra(\"#differenzaCompetenzaVariazioneAnnoPiuUno\", (totaleStanziamentiEntrata1NotUndefined - totaleStanziamentiSpesa1NotUndefined));\n //anno = anno bilancio +2\n capVarImp.impostaValutaEAllineaADestra(\"#differenzaCompetenzaVariazioneAnnoPiuDue\", (totaleStanziamentiEntrata2NotUndefined - totaleStanziamentiSpesa2NotUndefined));\n }", "function hitungLuasSegiTiga(alas,tinggi){\n var luas = 0.5 * alas * tinggi\n return luas\n}", "function proximo_mes(){\n if(mes_actual!=10){\n mes_actual++;\n }else{\n mes_actual=0;\n año_actual++;\n }\n dibujar_fecha();\n escribir_mes();\n escogerdia1();\n escogerdia2();\n}", "function hitungLuasSegitiga(alas,tinggi) {\n var luas = 1/2 * alas * tinggi;\n\n return luas;\n\n}", "function effemeridi_luna(TEMPO_RIF,LAT,LON,ALT,ITERAZIONI,LAN){\n\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) Ottobre 2011\n // funzione per il calcolo delle effemeridi del Sole.\n // Parametri utilizzati:\n // TEMPO_RIF= \"TL\" o \"TU\" tempo locale o tempo universale.\n // LAT= latitudine in gradi sessadecimali.\n // LON= longtudine in gradi sessadecimali.\n // ALT= altitudine in metri.\n // ITERAZIONE =numero di ripetizioni del calcolo.\n // LAN=\"EN\" versione in inglese.\n\nvar njd=calcola_jdUT0(); // numero del giorno giuliano all'ora 0 di oggi.\n\n njd=njd+0.00078; // correzione per il Terrestrial Time.\n\nvar data_ins=0; // data\nvar data_inser=0; // data\n\nvar numero_iterazioni=ITERAZIONI;\n\nvar effe_luna=0;\nvar ar_luna=0;\nvar de_luna=0;\nvar classetab=\"colore_tabellaef1\";\nvar elongazione=0;\nvar effe1=0;\nvar coo_app=0; // coordinate equatoriali apparenti.\nvar costl=\"\"; // costellazione. \n\n document.write(\"<table width=100% class='.table_effemeridi'>\");\n document.write(\" <tr>\");\n\n // versione in italiano.\n\n if (LAN!=\"EN\") // diverso da EN\n {\n document.write(\" <td class='colore_tabella'>Data:</td>\");\n document.write(\" <td class='colore_tabella'>Sorge:</td>\");\n document.write(\" <td class='colore_tabella'>Culmina:</td>\");\n document.write(\" <td class='colore_tabella'>Tramonta:</td>\");\n document.write(\" <td class='colore_tabella'>Az. Sorge:</td>\");\n document.write(\" <td class='colore_tabella'>Az. Tramonta:</td>\");\n document.write(\" <td class='colore_tabella'>Ascensione Retta:</td>\");\n document.write(\" <td class='colore_tabella'>Declinazione:</td>\");\n document.write(\" <td class='colore_tabella'>Fase:</td>\");\n document.write(\" <td class='colore_tabella'>Elong:</td>\");\n document.write(\" <td class='colore_tabella'>Cost.:</td>\");\n }\n\n // versione in inglese.\n\nif (LAN==\"EN\")\n {\n\n document.write(\" <td class='colore_tabella'>Date:</td>\");\n document.write(\" <td class='colore_tabella'>Rise:</td>\");\n document.write(\" <td class='colore_tabella'>Transit:</td>\");\n document.write(\" <td class='colore_tabella'>Set:</td>\");\n document.write(\" <td class='colore_tabella'>Az. Rise:</td>\");\n document.write(\" <td class='colore_tabella'>Az. Set:</td>\");\n document.write(\" <td class='colore_tabella'>Right Ascension:</td>\");\n document.write(\" <td class='colore_tabella'>Declination:</td>\");\n document.write(\" <td class='colore_tabella'>Phase:</td>\");\n document.write(\" <td class='colore_tabella'>Elong:</td>\");\n document.write(\" <td class='colore_tabella'>Const.:</td>\");\n\n }\n\n document.write(\" </tr>\");\n\n // ST_SOLE_LUNA Array(azimut_sorgere,azimut_tramonto,tempo_sorgere,tempo_transito,tempo_tramonto)\n // 0 1 2 3 4\n\n njd=njd-1;\n\n for (b=0; b<numero_iterazioni; b++){\n\n njd=njd+1;\n effe1=ST_SOLE_LUNA(njd,TEMPO_RIF,\"L\",LON,LAT,ALT,0.25);\n\n effe_luna=pos_luna(njd);\n coo_app=pos_app(njd,effe_luna[0],effe_luna[1]) // coordinate apparenti.\n\n ar_luna= sc_ore(coo_app[0]); // ascensione retta.\n de_luna=sc_angolo(coo_app[1]); // declinazione.\n\n elongazione=effe_luna[4].toFixed(2);\n\n data_ins=jd_data(njd);\n\n if (LAN!=\"EN\") {data_inser=Lnum(parseInt(data_ins[0]),2)+\" : \"+Lnum(parseInt(data_ins[1]),2)+\"| \"+data_ins[3]}; // versione in italiano.\n if (LAN==\"EN\") {data_inser=Lnum(parseInt(data_ins[0]),2)+\" : \"+Lnum(parseInt(data_ins[1]),2)+\"| \"+data_ins[4]}; // versione in inglese.\n\n fase_luna=effe_luna[3].toFixed(2);\n\n costl=costell(coo_app[0]); // costellazione. \n\n if (b%2==0){classetab=\"colore_tabellaef2\"; }\n\n else {classetab=\"colore_tabellaef1\";}\n\n\n document.write(\" <tr>\");\n document.write(\" <td class='\"+classetab+\"'>\"+data_inser+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+effe1[2]+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+effe1[3]+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+effe1[4]+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+effe1[0]+\"&deg;</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+effe1[1]+\"&deg;</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+ar_luna+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+de_luna+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+fase_luna+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+elongazione+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+costl+\"</td>\");\n\n document.write(\" </tr>\");\n\n }\n document.write(\" </table>\");\n\n\n}", "function pengkodeanPopulasi(pos) {\n var urutan = new Array();\n //Pencocokan Posisi\n for (var i = 0; i < pos.length; i++) {\n urutan[i] = pengkodean1Partikel(pos[i]);\n }\n return urutan;\n}", "getResultatCodificat(){ // SI EL MÈTODE NO PASSA ALGUN VALOR, SE LI POSSA this. MÉS EL ATRIBUT CORRESPONENT.\n this.eliminarEspaisBlanc();\n this.senseAccent();\n for (var i = 0; i < this._entrada.length; i++){\n\n // IGUALEM LA LLARGADA DE LA CLAU A LA DE L'ENTRADA\n var y = 0;\n var max_lenght = this._entrada.length;\n while (this._entrada.length != this._clau.length){\n\n this._clau = this._clau + this._clau[y];\n\n if(y >= max_lenght){\n\n y = 0;\n }\n else{\n\n y++;\n }\n }\n\n // BUSQUEM ON ESTAN SITUATS TANT LA LLETRA DE L'ENTRADA COM DE LA CLAU\n var posicio_lletra_entrada = this._alfabet.indexOf(this._entrada[i]);\n var posicio_lletra_clau = this._alfabet.indexOf(this._clau[i]);\n\n // SUMEM LES DUES POSICIONS\n var suma_posicions = posicio_lletra_entrada + posicio_lletra_clau;\n\n // ANEM RESTANT MENTRE QUE EL MOD SIGUI MÉS GRAN QUE EL LENGTH DEL ABECEDARI\n while (suma_posicions >= this._alfabet.length){\n\n suma_posicions = suma_posicions - this._alfabet.length;\n }\n \n // ARA BUSQUEM LA LLETRA AMB LA QUAL SUBSTITUIREM L'ENTRADA\n this._resultat = this._resultat + this._alfabet[suma_posicions];\n }\n\n // RETORNEM EL RESULTAT\n return (document.form.sortida.value = this._resultat);\n }", "function escogerValorMasGrande(elemetos){\n\n}", "function pos_pianeti(njd,np){\n\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) novembre 2010\n // calcola la posizione dei pianeti \n // njd= numero del giorno giuliano della data in T.U.\n // np= numero identificativo del pianeta 0,1,2,3,4,5,6,7,8 mercurio,venere... 2 per la Terra\n // coordinate geocentriche del pianeta riferite all'equinozio della data (njd).\n // calcola le principali perturbazioni planetarie.\n\n // new Array(Periodo , Long_media , Anomalia_media , Long_perielio , eccentr , Semiasse , Inclinazione , Long_nodo , dim_ang , magnitudine);\n // 0 1 2 3 4 5 6 7 8 9\n\n var tempo_luce=t_luce(njd,np);\n \n njd=njd-tempo_luce; // correzione per il tempo luce.\n\n var el_orb=orb_plan(njd,np); // recupera gli elementi orbitali del pianeta.\n\n var periodo= el_orb[0]; // periodo.\n var L= el_orb[1]; // longitudine media all'epoca.\n var AM_media= el_orb[2]; // anomalia media. \n var long_peri= el_orb[3]; // longitudine del perielio.\n var eccent= el_orb[4]; // eccentricità dell'orbita.\n var semiasse= el_orb[5]; // semiasse maggiore.\n var inclinaz= el_orb[6]; // inclinazione.\n var long_nodo= el_orb[7]; // longitudine del nodo.\n var dimens= el_orb[8]; // dimensioni apparenti.\n var magn= el_orb[9]; // magnitudine.\n\n \n var correzioni_orb=pos_pianeticr(njd,np); // calcolo delle correzioni per il pianeta (np).\n \n// Array(Delta_LP , Delta_R , Delta_LL , Delta_AS , Delta_EC , Delta_MM , Delta_LAT_ELIO);\n// 0 1 2 3 4 5 6 \n// lperiodo, rvett long. assemagg ecc M lat\n\n// CORREZIONI \n\n L=L+correzioni_orb[0]; // longitudine media.\n AM_media= AM_media+correzioni_orb[5]; // anomalia media + correzioni..\n semiasse= semiasse+correzioni_orb[3]; // semiasse maggiore.\n eccent= eccent+correzioni_orb[4]; // eccentricità.\n\n // LONGITUDINE ELIOCENTRICA DEL PIANETA ***************************************************** inizio:\n\n var M=AM_media; // anomalia media \n \n M=gradi_360(M); // intervallo 0-360;\n\n var E=eq_keplero(M,eccent); // equazione di Keplero.E[0]=Anomalia eccentrica E[1]=Anomalia vera in radianti.\n \n var rv=semiasse*(1-eccent*Math.cos(E[0])); // calcolo del raggio vettore (distanza dal Sole).\n rv=rv+correzioni_orb[1]; // raggio vettore più correzione.\n\n\n var U=gradi_360(L+Rda(E[1])-M-long_nodo); // argomento della latitudine.\n\n var long_eccliticay=Math.cos(Rad(inclinaz))*Math.sin(Rad(U));\n var long_eccliticax=Math.cos(Rad(U));\n\n var long_ecclitica=quadrante(long_eccliticay,long_eccliticax)+long_nodo;\n var l=gradi_360(long_ecclitica);\n l=l+correzioni_orb[2]; // longitudine del pianeta + correzione.\n\n // LONGITUDINE ELIOCENTRICA DEL PIANETA ********************************************************* fine: \n\n var b=Rda(Math.asin(Math.sin(Rad(U))*Math.sin(Rad(inclinaz)))); // latitudine ecclittica in gradi (b)\n\n // LONGITUDINE E RAGGIO VETTORE DEL SOLE *** inizio:\n\n njd=njd+tempo_luce; \n\n var eff_sole=pos_sole(njd);\n var LS=eff_sole[2]; // longitudine geocentrica del Sole.\n var RS=eff_sole[4]; // raggio vettore.\n \n // LONGITUDINE E RAGGIO VETTORE DEL SOLE *** fine: \n\n // longitudine geocentrica.\n\n var Y=rv*Math.cos(Rad(b))*Math.sin(Rad(l-LS));\n var X=rv*Math.cos(Rad(b))*Math.cos(Rad(l-LS))+RS;\n\n var long_geo=gradi_360(quadrante(Y,X)+LS); // longitudine geocentrica.\n\n var dist_p=Y*Y+X*X+(rv*Math.sin(Rad(b)))*(rv*Math.sin(Rad(b))); \n dist_p=Math.sqrt(dist_p); // distanza del pianeta dalla Terra.\n\n var beta=(rv/dist_p)*Math.sin(Rad(b));\n var lat_geo=Rda(Math.asin(beta));\n lat_geo=lat_geo+correzioni_orb[6]; // latitudine + correzione.\n\n \n// fase del pianeta.\n\nvar fase=0.5*(1+Math.cos(Rad(long_geo-long_ecclitica)));\n fase=fase.toFixed(2);\n\n// parallasse del pianeta in gradi.\n\nvar pa=(8.794/dist_p)/3600;\n\nvar coo_pl=trasf_ecli_equa(njd,long_geo,lat_geo); // coordinate equatoriali. \n\n // diametro apparente in secondi d'arco.\n\nvar diam_app=dimens/dist_p; \n\n// magnitudine del pianeta.\n\nvar magnitudine=(5*(Math.log(rv*dist_p/(magn*Math.sqrt(fase))))/2.302580)-27.7;\n magnitudine=magnitudine.toFixed(1);\n\nif (magnitudine==Infinity) {magnitudine=\"nd\"; }\n\nvar elongaz=elong(coo_pl[0],coo_pl[1],eff_sole[0],eff_sole[1]); // elongazione in gradi dal Sole.\n \n // calcolo dell'angolo di fase in gradi . \n\n var Dpt= dist_p; // distanza pianeta-terra.\n var Dts= RS; // distanza terra-sole.\n var Dps= rv; // distanza pianeta-sole.\n\n // teorema del coseno\n\n var delta_fase=(Dts*Dts+Dps*Dps-Dpt*Dpt)/(2*Dps*Dts);\n delta_fase=Math.acos(delta_fase); \n delta_fase=Rda(delta_fase);\n\n var angolo_fase=180-Math.abs(elongaz)-delta_fase; // angolo di fase in gradi.\n \nvar dati_pp= new Array(coo_pl[0],coo_pl[1],fase,magnitudine,dist_p,diam_app,elongaz,LS,RS,long_ecclitica,pa,rv,angolo_fase);\n// 0 1 2 3 4 5 6 7 8 9 10 11 12 \n\n\n\n// risultati: ARetta,Declinazione,fase,magnitudine,distanza pianeta,diametro apparente, elongazione, long. sole,raggio vettore Terra, longituddine elio. pianeta, parallase,dist sole-pianeta. \n\nreturn dati_pp;\n}", "function pos_pianeticr(njd,np){\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) settembre 2010\n // termini di correzione per i pianeti Giove e Saturno.\n // np=numero identificativo del pianeta.\n\n var T=(njd-2415020.0)/36525;\n\n M=358.47583+35999.049750*T-0.000150*T*T-0.0000033*T*T*T; // Sole.\n\n M1=102.27938+149472.51529*T+0.000007*T*T; // Mercurio.\n M2=212.60322+ 58517.80387*T+0.001286*T*T; // Venere.\n M4=319.51913+ 19139.85475*T+0.000181*T*T; // Marte.\n M5=225.32833+ 3034.69202*T-0.000722*T*T; // Giove.\n M6=175.46622+ 1221.55147*T-0.000502*T*T; // Saturno.\n \n \n \n var Delta_LP=0; // termini correzione di lungo periodo.\n //var Delta_L=0; // correzione per la longitudine.\n var Delta_R=0; // correzione per il raggio vettore.\n\n var Delta_LL=0; // correzione per la longitudine.\n var Delta_P=0; // correzione per il perielio.\n var Delta_AS=0; // correzione semiasse maggiore.\n var Delta_EC=0; // correzione eccentricità.\n var Delta_MM=0; // correzione anomalia media.\n var Delta_LAT_ELIO=0; // correzione latitudine eliocentrica.\n \n\n// Correzioni per Mercurio - Perturbazioni in longitudine.\n// Da aggiungere dopo aver risolto l'E.Keplero\n\n if (np==0) {\n\n // longitudine\n\n Delta_LL=0.00204*Math.cos(Rad(5*M2-2*M1+12.220))\n +0.00103*Math.cos(Rad(2*M2-M1-160.6920))\n +0.00091*Math.cos(Rad(2*M5-M1-37.00300))\n +0.00078*Math.cos(Rad(5*M2-3*M1+10.137));\n\n // perturbazioni in raggio vettore\n\n Delta_R=0.000007525*Math.cos(Rad(2*M5-M1+53.013))\n +0.000006802*Math.cos(Rad(5*M2-3*M1-259.918))\n +0.000005457*Math.cos(Rad(2*M2-2*M1-71.188))\n +0.000003569*Math.cos(Rad(5*M2-M1-77.75));\n \n }\n\n// Correzioni per Venere -Perturbazioni in longitudine. \n// Delta_LP da aggiungere alla longitudine e anomalia media prima di aver risolto l'E.Keplero.\n// gli altri 2 termini dopo aver risolto l'E.Keplero.\n\nelse if(np==1) {\n\n // longitudine e anomalia media\n\n Delta_LP=0.00077*Math.sin(Rad(237.24+150.27*T));\n Delta_MM=Delta_LP;\n\n // longitudine\n\n Delta_LL=0.00313*Math.cos(Rad(2*M-2*M2-148.225))\n +0.00198*Math.cos(Rad(3*M-3*M2+2.565))\n +0.00136*Math.cos(Rad(M-M2-119.107))\n +0.00096*Math.cos(Rad(3*M-2*M2-135.912))\n +0.00082*Math.cos(Rad(M5-M2-208.087));\n\n // perturbazioni in raggio vettore\n\n Delta_R=0.000022501*Math.cos(Rad(2*M-2*M2-58.208))\n +0.000019045*Math.cos(Rad(3*M-3*M2+92.577))\n +0.000006887*Math.cos(Rad(M5-M2-118.090))\n +0.000005172*Math.cos(Rad(M-M2-29.110))\n +0.000003620*Math.cos(Rad(5*M-4*M2-104.208))\n +0.000003283*Math.cos(Rad(4*M-4*M2+63.513))\n +0.000003074*Math.cos(Rad(2*M5-2*M2-55.167));\n\n}\n\n// Correzioni per la Terra\n\nelse if (np==2) {\n\n Delta_LP=0;\n\n // correzioni ***************\n\n var A=153.23+22518.7541*T;\n var B=216.57+45037.5082*T;\n var C=312.69+32964.3577*T;\n var D=350.74+445267.1142*T-0.00144*T*T;\n var E=231.19+20.20*T;\n var H=353.40+65928.7155*T;\n\n // angoli in radianti.\n\n A=Rad(A); \n B=Rad(B); \n C=Rad(C); \n D=Rad(D); \n E=Rad(E); \n H=Rad(H); \n\n // correzione per la longitudine.\n\n var Delta_LL=0.00134*Math.cos(A)\n +0.00154*Math.cos(B)\n +0.00200*Math.cos(C)\n +0.00179*Math.sin(D)\n +0.00178*Math.sin(E);\n\n // correzioni per il raggio vettore.\n\n var Delta_R=0.00000543*Math.sin(A)\n +0.00001575*Math.sin(B)\n +0.00001627*Math.sin(C)\n +0.00003076*Math.cos(D) \n +0.00000927*Math.sin(H);\n \n}\n\n// correzioni per il pianeta Marte ******************************** INIZIO .\n// Delta_LP da aggiungere alla longitudine e anomalia media prima di aver risolto l'E.Keplero.\n// gli altri 2 termini dopo aver risolto l'E.Keplero.\n\n\nif (np==3) {\n\n // longitudine e anomalia media\n\nDelta_LP=-0.01133*Math.sin(Rad(3*M5-8*M4+4*M))\n -0.00933*Math.cos(Rad(3*M5-8*M4+4*M)); // termine lungo periodo.\nDelta_MM=Delta_LP;\n\n // longitudine\n\nDelta_LL=0.00705*Math.cos(Rad(M5-M4-48.958))\n +0.00607*Math.cos(Rad(2*M5-M4-118.350))\n +0.00445*Math.cos(Rad(2*M5-2*M4-191.897))\n +0.00388*Math.cos(Rad(M-2*M4+20.495))\n +0.00238*Math.cos(Rad(M-M4+35.097))\n +0.00204*Math.cos(Rad(2*M-3*M4+158.638))\n +0.00177*Math.cos(Rad(3*M4-M2-57.602))\n +0.00136*Math.cos(Rad(2*M-4*M4+154.093))\n +0.00104*Math.cos(Rad(M5+17.618));\n\n // raggio vettore\n\nDelta_R=0.000053227*Math.cos(Rad(M5-M4+41.1306))\n +0.000050989*Math.cos(Rad(2*M5-2*M4-101.9847))\n +0.000038278*Math.cos(Rad(2*M5-M4-98.3292))\n +0.000015996*Math.cos(Rad(M-M4-55.555))\n +0.000014764*Math.cos(Rad(2*M-3*M4+68.622))\n +0.000008966*Math.cos(Rad(M5-2*M4+43.615))\n +0.000007914*Math.cos(Rad(3*M5-2*M4-139.737))\n +0.000007004*Math.cos(Rad(2*M5-3*M4-102.888))\n +0.000006620*Math.cos(Rad(M-2*M4+113.202)) \n +0.000004930*Math.cos(Rad(3*M5-3*M4-76.243))\n +0.000004693*Math.cos(Rad(3*M-5*M4+190.603))\n +0.000004571*Math.cos(Rad(2*M-4*M4+244.702))\n +0.000004409*Math.cos(Rad(3*M5-M4-115.828));\n}\n\n// correzioni per il pianeta Marte ******************************** FINE.\n\n// correzioni per il pianeta Giove ******************************* INIZIO.\n// tutti i termini di Giove sono da aggiungere prima dell'equazione di Keplero\n\n\nif (np==4) {\n\n var X=(T/5)+0.1;\n var P=237.47555+3034.9061*T;\n var Q=265.91650+1222.1139*T;\n var S=243.51721+428.46770*T;\n var V=5*Q-2*P;\n var W=2*P-6*Q+3*S;\n var Z=Q-P;\n\n // ************************* A\n // correzione per la longitudine media da aggiungere prima dell'equazione di Keplero\n // solo per la longitudine media.\n\n Delta_LL=(0.331364-0.010281*X-0.004692*X*X)*Math.sin(Rad(V)) \n +(0.003228-0.064436*X+0.002075*X*X)*Math.cos(Rad(V)) \n -(0.003083+0.000275*X-0.000489*X*X)*Math.sin(Rad(2*V))\n +0.002472*Math.sin(Rad(W))\n +0.013619*Math.sin(Rad(Z))\n +0.018472*Math.sin(Rad(2*Z))\n +0.006717*Math.sin(Rad(3*Z))\n +0.002775*Math.sin(Rad(4*Z))\n +(0.007275-0.001253*X)*Math.sin(Rad(Z))*Math.sin(Rad(Q))\n +0.006417*Math.sin(Rad(2*Z))*Math.sin(Rad(Q))\n +0.002439*Math.sin(Rad(3*Z))*Math.sin(Rad(Q)) \n -(0.033839+0.001125*X)*Math.cos(Rad(Z))*Math.sin(Rad(Q))\n -0.003767*Math.cos(Rad(2*Z))*Math.sin(Rad(Q))\n -(0.035681+0.001208*X)*Math.sin(Rad(Z))*Math.cos(Rad(Q))\n -0.004261*Math.sin(Rad(2*Z))*Math.cos(Rad(Q))\n +0.002178*Math.cos(Rad(Q))\n +(-0.006333+0.001161*X)*Math.cos(Rad(Z))*Math.cos(Rad(Q))\n -0.006675*Math.cos(Rad(2*Z))*Math.cos(Rad(Q))\n -0.002664*Math.cos(Rad(3*Z))*Math.cos(Rad(Q))\n -0.002572*Math.sin(Rad(Z))*Math.sin(Rad(2*Q))\n -0.003567*Math.sin(Rad(2*Z))*Math.sin(Rad(2*Q))\n +0.002094*Math.cos(Rad(Z))*Math.cos(Rad(2*Q))\n +0.003342*Math.cos(Rad(2*Z))*Math.cos(Rad(2*Q));\n\n // correzione per l'anomalia media -- più in fondo nel listato.\n\n // perturbazioni perielio da utilizzare per calcolare M. (vedi in fondo nel listato)\n\n Delta_P=(0.007192-0.003147*X)*Math.sin(Rad(V))\n +(-0.020428-0.000675*X+0.000197*X*X)*Math.cos(Rad(V))\n +(0.007269+0.000672*X)*Math.sin(Rad(Z))*Math.sin(Rad(Q))\n -0.004344*Math.sin(Rad(Q))\n +0.034036*Math.cos(Rad(Z))*Math.sin(Rad(Q))\n +0.005614*Math.cos(Rad(2*Z))*Math.sin(Rad(Q))\n +0.002964*Math.cos(Rad(3*Z))*Math.sin(Rad(Q))\n +0.037761*Math.sin(Rad(Z))*Math.cos(Rad(Q))\n +0.006158*Math.sin(Rad(2*Z))*Math.cos(Rad(Q))\n -0.006603*Math.cos(Rad(Z))*Math.cos(Rad(Q))\n -0.005356*Math.sin(Rad(Z))*Math.sin(Rad(2*Q))\n +0.002722*Math.sin(Rad(2*Z))*Math.sin(Rad(2*Q))\n +0.004483*Math.cos(Rad(Z))*Math.sin(Rad(2*Q))\n -0.002642*Math.cos(Rad(2*Z))*Math.sin(Rad(2*Q))\n +0.004403*Math.sin(Rad(Z))*Math.cos(Rad(2*Q))\n -0.002536*Math.sin(Rad(2*Z))*Math.cos(Rad(2*Q))\n +0.005547*Math.cos(Rad(Z))*Math.cos(Rad(2*Q))\n -0.002689*Math.cos(Rad(2*Z))*Math.cos(Rad(2*Q));\n\n // correzione per l'anomalia media da aggiungere prima dell'equazione di Keplero\n\n var el_orb=orb_plan(njd,4); // recupera l'eccentricità del pianeta.\n var eccent=el_orb[4]; // eccentricità non corretta.\n\n Delta_MM=Delta_LL-(Delta_P/eccent);\n\n\n // semiasse maggiore da aggiungere prima dell'equazione di Keplero.\n\n Delta_AS=-263*Math.cos(Rad(V))\n +205*Math.cos(Rad(Z))\n +693*Math.cos(Rad(2*Z))\n +312*Math.cos(Rad(3*Z))\n +147*Math.cos(Rad(4*Z))\n +299*Math.sin(Rad(Z))*Math.sin(Rad(Q))\n +181*Math.cos(Rad(2*Z))*Math.sin(Rad(Q))\n +204*Math.sin(Rad(2*Z))*Math.cos(Rad(Q))\n +111*Math.sin(Rad(3*Z))*Math.cos(Rad(Q))\n -337*Math.cos(Rad(Z))*Math.cos(Rad(Q))\n -111*Math.cos(Rad(2*Z))*Math.cos(Rad(Q));\n \n Delta_AS=Delta_AS/1000000;\n \n // eccentricità da aggiungere prima dell'equazione di Keplero\n\n Delta_EC=(3606+130*X-43*X*X)*Math.sin(Rad(V))\n +(1289-580*X)*Math.cos(Rad(V))\n -6764*Math.sin(Rad(Z))*Math.sin(Rad(Q))\n -1110*Math.sin(Rad(2*Z))*Math.sin(Rad(Q))\n -224*Math.sin(Rad(3*Z))*Math.sin(Rad(Q))\n -204*Math.sin(Rad(Q))\n +(1284+116*X)*Math.cos(Rad(Z))*Math.sin(Rad(Q))\n +188*Math.cos(Rad(2*Z))*Math.sin(Rad(Q))\n +(1460+130*X)*Math.sin(Rad(Z))*Math.cos(Rad(Q))\n +224*Math.sin(Rad(2*Z))*Math.cos(Rad(Q))\n -817*Math.cos(Rad(Q))\n +6074*Math.cos(Rad(Z))*Math.cos(Rad(Q))\n +992*Math.cos(Rad(2*Z))*Math.cos(Rad(Q))\n +508*Math.cos(Rad(3*Z))*Math.cos(Rad(Q))\n +230*Math.cos(Rad(4*Z))*Math.cos(Rad(Q))\n +108*Math.cos(Rad(5*Z))*Math.cos(Rad(Q))\n -(956+73*X)*Math.sin(Rad(Z))*Math.sin(Rad(2*Q))\n +448*Math.sin(Rad(2*Z))*Math.sin(Rad(2*Q))\n +137*Math.sin(Rad(3*Z))*Math.sin(Rad(2*Q))\n +(-997+108*X)*Math.cos(Rad(Z))*Math.sin(Rad(2*Q))\n +480*Math.cos(Rad(2*Z))*Math.sin(Rad(2*Q))\n +148*Math.cos(Rad(3*Z))*Math.sin(Rad(2*Q))\n +(-956+99*X)*Math.sin(Rad(Z))*Math.cos(Rad(2*Q))\n +490*Math.sin(Rad(2*Z))*Math.cos(Rad(2*Q))\n +158*Math.sin(Rad(3*Z))*Math.cos(Rad(2*Q))\n +179*Math.cos(Rad(2*Q))\n +(1024+75*X)*Math.cos(Rad(Z))*Math.cos(Rad(2*Q))\n -437*Math.cos(Rad(2*Z))*Math.cos(Rad(2*Q))\n -132*Math.cos(Rad(3*Z))*Math.cos(Rad(2*Q));\n\n Delta_EC=Delta_EC/10000000;\n}\n\n// correzioni per il pianeta Giove ********************************* FINE.\n\n// correzioni per il pianeta Saturno ****************************** INIZIO.\n// tutti i termini di Saturno sono da aggiungere prima dell'equazione di Keplero\n// tranne il termine della latitudine eliocentrica\n\n\nif (np==5) {\n\n var X=(T/5)+0.1;\n var P=237.47555+3034.9061*T;\n var Q=265.91650+1222.1139*T;\n var S=243.51721+428.46770*T;\n var V=5*Q-2*P;\n var W=2*P-6*Q+3*S;\n var Z=Q-P;\n var PS=S-Q;\n\n // perturbazioni in longitudine media\n\n Delta_LL=+(-0.814181+0.018150*X+0.016714*X*X)*Math.sin(Rad(V))\n +(-0.010497+0.160906*X-0.004100*X*X)*Math.cos(Rad(V))\n +0.007581*Math.sin(Rad(2*V))\n -0.007986*Math.sin(Rad(W))\n -0.148811*Math.sin(Rad(Z))\n -0.040786*Math.sin(Rad(2*Z))\n -0.015208*Math.sin(Rad(3*Z))\n -0.006339*Math.sin(Rad(4*Z))\n -0.006244*Math.sin(Rad(Q))\n +(0.008931+0.002728*X)*Math.sin(Rad(Z))*Math.sin(Rad(Q))\n -0.016500*Math.sin(Rad(2*Z))*Math.sin(Rad(Q))\n -0.005775*Math.sin(Rad(3*Z))*Math.sin(Rad(Q))\n +(0.081344+0.003206*X)*Math.cos(Rad(Z))*Math.sin(Rad(Q))\n +0.015019*Math.cos(Rad(2*Z))*Math.sin(Rad(Q))\n +(0.085581+0.002494*X)*Math.sin(Rad(Z))*Math.cos(Rad(Q))\n +(0.025328-0.003117*X)*Math.cos(Rad(Z))*Math.cos(Rad(Q))\n +0.014394*Math.cos(Rad(2*Z))*Math.cos(Rad(Q))\n +0.006319*Math.cos(Rad(3*Z))*Math.cos(Rad(Q))\n +0.006369*Math.sin(Rad(Z))*Math.sin(Rad(2*Q))\n +0.009156*Math.sin(Rad(2*Z))*Math.sin(Rad(2*Q))\n +0.007525*Math.sin(Rad(3*PS))*Math.sin(Rad(2*Q))\n -0.005236*Math.cos(Rad(Z))*Math.cos(Rad(2*Q))\n -0.007736*Math.cos(Rad(2*Z))*Math.cos(Rad(2*Q))\n -0.007528*Math.cos(Rad(3*PS))*Math.cos(Rad(2*Q));\n\n // eccentricità\n\n Delta_EC=+(-7927+2548*X+91*X*X)*Math.sin(Rad(V))\n +(13381+1226*X-253*X*X)*Math.cos(Rad(V))\n +(248-121*X)*Math.sin(Rad(2*V))\n -(305+91*X)*Math.cos(Rad(2*V))\n +412*Math.sin(Rad(Z))\n +12415*Math.sin(Rad(Q))\n +(390-617*X)*Math.sin(Rad(Z))*Math.sin(Rad(Q))\n +(165-204*X)*Math.sin(Rad(2*Z))*Math.sin(Rad(Q))\n +26599*Math.cos(Rad(Z))*Math.sin(Rad(Q))\n -4687*Math.cos(Rad(2*Z))*Math.sin(Rad(Q))\n -1870*Math.cos(Rad(3*Z))*Math.sin(Rad(Q))\n -821*Math.cos(Rad(4*Z))*Math.sin(Rad(Q))\n -377*Math.cos(Rad(5*Z))*Math.sin(Rad(Q))\n +497*Math.cos(Rad(2*PS))*Math.sin(Rad(Q))\n +(163-611*X)*Math.cos(Rad(Q))\n -12696*Math.sin(Rad(Z))*Math.cos(Rad(Q))\n -4200*Math.sin(Rad(2*Z))*Math.cos(Rad(Q))\n -1503*Math.sin(Rad(3*Z))*Math.cos(Rad(Q))\n -619*Math.sin(Rad(4*Z))*Math.cos(Rad(Q))\n -268*Math.sin(Rad(5*Z))*Math.cos(Rad(Q))\n -(282+1306*X)*Math.cos(Rad(Z))*Math.cos(Rad(Q))\n +(-86+230*X)*Math.cos(Rad(2*Z))*Math.cos(Rad(Q))\n +461*Math.sin(Rad(2*PS))*Math.cos(Rad(Q))\n -350*Math.sin(Rad(2*Q))\n +(2211-286*X)*Math.sin(Rad(Z))*Math.sin(Rad(2*Q)) \n -2208*Math.sin(Rad(2*Z))*Math.sin(Rad(2*Q))\n -568*Math.sin(Rad(3*Z))*Math.sin(Rad(2*Q))\n -346*Math.sin(Rad(4*Z))*Math.sin(Rad(2*Q))\n -(2780+222*X)*Math.cos(Rad(Z))*Math.sin(Rad(2*Q))\n +(2022+263*X)*Math.cos(Rad(2*Z))*Math.sin(Rad(2*Q))\n +248*Math.cos(Rad(3*Z))*Math.sin(Rad(2*Q))\n +242*Math.sin(Rad(3*PS))*Math.sin(Rad(2*Q))\n +467*Math.cos(Rad(3*PS))*Math.sin(Rad(2*Q))\n -490*Math.cos(Rad(2*Q))\n -(2842+279*X)*Math.sin(Rad(Z))*Math.cos(Rad(2*Q))\n +(128+226*X)*Math.sin(Rad(2*Z))*Math.cos(Rad(2*Q))\n +224*Math.sin(Rad(3*Z))*Math.cos(Rad(2*Q))\n +(-1594+282*X)*Math.cos(Rad(Z))*Math.cos(Rad(2*Q))\n +(2162-207*X)*Math.cos(Rad(2*Z))*Math.cos(Rad(2*Q))\n +561*Math.cos(Rad(3*Z))*Math.cos(Rad(2*Q))\n +343*Math.cos(Rad(4*Z))*Math.cos(Rad(2*Q))\n +469*Math.sin(Rad(3*PS))*Math.cos(Rad(2*Q))\n -242*Math.cos(Rad(3*PS))*Math.cos(Rad(2*Q))\n -205*Math.sin(Rad(Z))*Math.sin(Rad(3*Q))\n +262*Math.sin(Rad(3*Z))*Math.sin(Rad(3*Q))\n +208*Math.cos(Rad(Z))*Math.cos(Rad(3*Q))\n -271*Math.cos(Rad(3*Z))*Math.cos(Rad(3*Q))\n -382*Math.cos(Rad(3*Z))*Math.sin(Rad(4*Q))\n -376*Math.sin(Rad(3*Z))*Math.cos(Rad(4*Q));\n\n Delta_EC=Delta_EC/10000000; \n\n // correzione del perielio\n\n Delta_P=+(0.077108+0.007186*X-0.001533*X*X)*Math.sin(Rad(V))\n +(0.045803-0.014766*X-0.000536*X*X)*Math.cos(Rad(V))\n -0.007075*Math.sin(Rad(Z))\n -0.075825*Math.sin(Rad(Z))*Math.sin(Rad(Q))\n -0.024839*Math.sin(Rad(2*Z))*Math.sin(Rad(Q))\n -0.008631*Math.sin(Rad(3*Z))*Math.sin(Rad(Q))\n -0.072586*Math.cos(Rad(Q))\n -0.150383*Math.cos(Rad(Z))*Math.cos(Rad(Q))\n +0.026897*Math.cos(Rad(2*Z))*Math.cos(Rad(Q))\n +0.010053*Math.cos(Rad(3*Z))*Math.cos(Rad(Q))\n -(0.013597+0.001719*X)*Math.sin(Rad(Z))*Math.sin(Rad(2*Q))\n +(-0.007742+0.001517*X)*Math.cos(Rad(Z))*Math.sin(Rad(2*Q))\n +(0.013586-0.001375*X)*Math.cos(Rad(2*Z))*Math.sin(Rad(2*Q))\n +(-0.013667+0.001239*X)*Math.sin(Rad(Z))*Math.cos(Rad(2*Q))\n +0.011981*Math.sin(Rad(2*Z))*Math.cos(Rad(2*Q))\n +(0.014861+0.001136*X)*Math.cos(Rad(Z))*Math.cos(Rad(2*Q))\n -(0.013064+0.001628*X)*Math.cos(Rad(2*Z))*Math.cos(Rad(2*Q));\n\n\n // correzione per l'anomalia media da aggiungere prima dell'equazione di Keplero\n\n var el_orb=orb_plan(njd,5); // recupera l'eccentricità del pianeta.\n var eccent=el_orb[4]; // eccentricità senza correzione.\n\n Delta_MM=Delta_LL-(Delta_P/eccent);\n\n\n// semiasse maggiore.\n\n Delta_AS=572*X*Math.sin(Rad(V))\n +2933*Math.cos(Rad(V))\n +33629*Math.cos(Rad(Z))\n -3081*Math.cos(Rad(2*Z))\n -1423*Math.cos(Rad(3*Z))\n -671*Math.cos(Rad(4*Z))\n -320*Math.cos(Rad(5*Z))\n +1098*Math.sin(Rad(Q))\n -2812*Math.sin(Rad(Z))*Math.sin(Rad(Q))\n +688*Math.sin(Rad(2*Z))*Math.sin(Rad(Q))\n -393*Math.sin(Rad(3*Z))*Math.sin(Rad(Q))\n -228*Math.sin(Rad(4*Z))*Math.sin(Rad(Q))\n +2138*Math.cos(Rad(Z))*Math.sin(Rad(Q))\n -999*Math.cos(Rad(2*Z))*Math.sin(Rad(Q))\n -642*Math.cos(Rad(3*Z))*Math.sin(Rad(Q))\n -325*Math.cos(Rad(4*Z))*Math.sin(Rad(Q))\n -890*Math.cos(Rad(Q))\n +2206*Math.sin(Rad(Z))*Math.cos(Rad(Q))\n -1590*Math.sin(Rad(2*Z))*Math.cos(Rad(Q))\n -647*Math.sin(Rad(3*Z))*Math.cos(Rad(Q))\n -344*Math.sin(Rad(4*Z))*Math.cos(Rad(Q))\n +2885*Math.cos(Rad(Z))*Math.cos(Rad(Q))\n +(2172+102*X)*Math.cos(Rad(2*Z))*Math.cos(Rad(Q))\n +296*Math.cos(Rad(3*Z))*Math.cos(Rad(Q))\n -267*Math.sin(Rad(2*Z))*Math.sin(Rad(2*Q))\n -778*Math.cos(Rad(Z))*Math.sin(Rad(2*Q))\n +495*Math.cos(Rad(2*Z))*Math.sin(Rad(2*Q))\n +250*Math.cos(Rad(3*Z))*Math.sin(Rad(2*Q))\n -856*Math.sin(Rad(Z))*Math.cos(Rad(2*Q))\n +441*Math.sin(Rad(2*Z))*Math.cos(Rad(2*Q))\n +296*Math.cos(Rad(2*Z))*Math.cos(Rad(2*Q))\n +211*Math.cos(Rad(3*Z))*Math.cos(Rad(2*Q))\n -427*Math.sin(Rad(Z))*Math.sin(Rad(3*Q))\n +398*Math.sin(Rad(3*Z))*Math.sin(Rad(3*Q))\n +344*Math.cos(Rad(Z))*Math.cos(Rad(3*Q))\n -427*Math.cos(Rad(3*Z))*Math.cos(Rad(3*Q));\n \nDelta_AS=Delta_AS/1000000;\n\n\n\n// aggiungere alla latitudine eliocentrica.\n\n Delta_LAT_ELIO= +0.000747*Math.cos(Rad(Z))*Math.sin(Rad(Q))\n +0.001069*Math.cos(Rad(Z))*Math.cos(Rad(Q))\n +0.002108*Math.sin(Rad(2*Z))*Math.sin(Rad(2*Q))\n +0.001261*Math.cos(Rad(2*Z))*Math.sin(Rad(2*Q))\n +0.001236*Math.sin(Rad(2*Z))*Math.cos(Rad(2*Q))\n -0.002075*Math.cos(Rad(2*Z))*Math.cos(Rad(2*Q)); \n\n}\n\n// correzioni per il pianeta Saturno******************************** FINE.\n\n// correzioni per il pianeta Urano******************************** INIZIO.\n\nif (np==6) {\n\n var X=(T/5)+0.1;\n var P=237.47555+3034.9061*T;\n var Q=265.91650+1222.1139*T;\n var S=243.51721+428.46770*T;\n var W=2*P-6*Q+3*S;\n var G=83.76922+218.4901*T;\n var H=2*G-S;\n var Z=S-P;\n var N=S-Q;\n var OM=G-S;\n \n // perturbazioni in longitudine media A\n\n Delta_LP=+(0.864319-0.001583*X)*Math.sin(Rad(H))\n +(0.082222-0.006833*X)*Math.cos(Rad(H))\n +0.036017*Math.sin(Rad(2*H))\n -0.003019*Math.cos(Rad(2*H))\n +0.008122*Math.sin(Rad(W));\n\n var B=0.120303*Math.sin(Rad(H))\n +(0.019472-0.000947*X)*Math.cos(Rad(H))\n +0.006197*Math.sin(Rad(2*H));\n\n // correzione per l'anomalia media di Urano\n\n var el_orb=orb_plan(njd,6); // recupera l'eccentricità del pianeta.\n var eccent=el_orb[4]; // eccentricità senza correzione.\n\n Delta_MM=Delta_LP-(B/eccent);\n\n // eccentricità\n\nDelta_EC=+(-3349+163*X)*Math.sin(Rad(H)) \n +20981*Math.cos(Rad(H))\n +1311*Math.cos(Rad(2*H));\n\nDelta_EC=Delta_EC/10000000;\n\n // correzione semiasse maggiore.\n\nDelta_AS=-0.003825*Math.cos(Rad(H));\n\n // correzione per la longitudine vera.\n\n Delta_LL=+(0.010122-0.000988*X)*Math.sin(Rad(S+N))\n +(-0.038581+0.002031*X-0.001910*X*X)*Math.cos(Rad(S+N))\n +(0.034964-0.001038*X+0.000868*X*X)*Math.cos(Rad(2*S+N))\n +0.005594*Math.sin(Rad(S+3*OM))\n -0.014808*Math.sin(Rad(Z))\n -0.005794*Math.sin(Rad(N))\n +0.002347*Math.cos(Rad(N))\n +0.009872*Math.sin(Rad(OM))\n +0.008803*Math.sin(Rad(2*OM))\n -0.004308*Math.sin(Rad(3*OM));\n\n// aggiungere alla latitudine eliocentrica.\n\n Delta_LAT_ELIO=+(0.000458*Math.sin(Rad(N))-0.000642*Math.cos(Rad(N))-0.000517*Math.cos(Rad(4*OM)))*Math.sin(Rad(S))\n -(0.000347*Math.sin(Rad(N))+0.000853*Math.cos(Rad(N))+0.000517*Math.sin(Rad(4*N)))*Math.cos(Rad(S))\n +0.000403*(Math.cos(Rad(2*OM))*Math.sin(Rad(2*S))+Math.sin(Rad(2*OM))*Math.cos(Rad(2*S))); \n\n// correzione al raggio vettore.\n\nDelta_R=-25948+ (5795*Math.cos(Rad(S))-1165*Math.sin(Rad(S))+1388*Math.cos(Rad(2*S)))*Math.sin(Rad(N))\n +4985*Math.cos(Rad(Z))+(1351*Math.cos(Rad(S))+5702*Math.sin(Rad(S))+1388*Math.sin(Rad(2*S)))*Math.cos(Rad(N))\n -1230*Math.cos(Rad(S))+904*Math.cos(Rad(2*OM))\n +3354*Math.cos(Rad(N))+894*(Math.cos(Rad(OM))-Math.cos(Rad(3*OM)));\n\nDelta_R=Delta_R/1000000;\n \n \n\n}\n// correzioni per il pianeta Urano ************************************ FINE.\n\n// correzioni per il pianeta Nettuno ******************************** INIZIO.\n\nif (np==7) {\n\n var X=(T/5)+0.1;\n var P=237.47555+3034.9061*T;\n var Q=265.91650+1222.1139*T;\n var S=243.51721+428.46770*T;\n var W=2*P-6*Q+3*S;\n var G=83.76922+218.4901*T;\n var H=2*G-S;\n var Z=G-P;\n var N=G-Q;\n var OM=G-S;\n \n // perturbazioni in longitudine media A\n\n Delta_LP=+(-0.589833+0.001089*X)*Math.sin(Rad(H))\n +(-0.056094+0.004658*X)*Math.cos(Rad(H)) \n -0.024286*Math.sin(Rad(2*H));\n\n var B=0.024039*Math.sin(Rad(H))\n -0.025303*Math.cos(Rad(H))\n +0.006206*Math.sin(Rad(2*H))\n -0.005992*Math.cos(Rad(2*H));\n\n// correzione per l'anomalia media di Urano\n\n var el_orb=orb_plan(njd,7); // recupera l'eccentricità del pianeta.\n var eccent=el_orb[4]; // eccentricità senza correzione.\n\n Delta_MM=Delta_LP-(B/eccent);\n\n // eccentricità\n\n Delta_EC=+4389*Math.sin(Rad(H))\n +4262*Math.cos(Rad(H))\n +1129*Math.sin(Rad(2*H))\n +1089*Math.cos(Rad(2*H));\n\n Delta_EC=Delta_EC/10000000;\n\n// correzione semiasse maggiore.\n\n Delta_AS=-817*Math.sin(Rad(H))+8189*Math.cos(Rad(H))+781*Math.cos(Rad(2*H));\n\n Delta_AS=Delta_AS/1000000;\n\n // correzione per la longitudine vera.\n\n Delta_LL=-0.009556*Math.sin(Rad(Z))\n -0.005178*Math.sin(Rad(N))\n +0.002572*Math.sin(Rad(2*OM))\n -0.002972*Math.cos(Rad(2*OM))*Math.sin(Rad(G))\n -0.002833*Math.sin(Rad(2*OM))*Math.cos(Rad(G));\n \n // aggiungere alla latitudine eliocentrica.\n\n Delta_LAT_ELIO=+0.000336*Math.cos(Rad(2*OM))*Math.sin(Rad(G))\n +0.000364*Math.sin(Rad(2*OM))*Math.cos(Rad(G));\n\n // correzione al raggio vettore.\n\n Delta_R=-40596\n +4992*Math.cos(Rad(Z))\n +2744*Math.cos(Rad(N))\n +2044*Math.cos(Rad(OM))\n +1051*Math.cos(Rad(2*OM));\n\nDelta_R=Delta_R/1000000;\n \n\n}\n// correzioni per il pianeta Nettuno ******************************** FINE\n\n\n// variabili correzioni\n// lperiodo, rvett long. assemagg ecc M lat\n var correzioni=new Array(Delta_LP,Delta_R,Delta_LL,Delta_AS,Delta_EC,Delta_MM,Delta_LAT_ELIO);\n\n return correzioni;\n\n}", "function definir_pos() {\r\n\tconsole.log(posicaoAtual);\r\n\tif(posicaoAtual<0) posicaoAtual=posicaoMax;\r\n\telse if(posicaoAtual>posicaoMax) posicaoAtual=0;\r\n\r\n\tsetaEsquerda.href = '#id'+((posicaoAtual-1<0)? posicaoMax : posicaoAtual-1);\r\n\tsetaDireita.href = '#id'+((posicaoAtual+1>posicaoMax)? 0 : posicaoAtual+1);\r\n}", "function Colonna() {\r\n\tthis.baseColonna = 10;\r\n\tthis.baseColonnaSpessore = 0.5;\r\n\tthis.altezzaColonnaNoCap = 34;\r\n\t//\r\n\tthis.scalaCapitelloX = 0.22; \r\n\tthis.scalaCapitelloY = 0.18; \r\n\tthis.scalaCapitelloZ = 0.45;\r\n\tthis.altezzaCapitello = 0.2;\r\n}", "function perimetroCuad(lado){\n return lado * 4;\n}", "function dibujarPuntoLienzoRutas(lon,lat,id){\r\n limpiarCapaNuevaRuta();\r\n var marca = new Array();\r\n var punto = new OpenLayers.Geometry.Point(lon,lat);\r\n punto.transform( new OpenLayers.Projection( \"EPSG:4326\" ),\r\n new OpenLayers.Projection( \"EPSG:900913\" ) );\r\n \r\n var puntoParada = new OpenLayers.Feature.Vector( punto, {\r\n id : ''+id\r\n });\r\n puntoParada.id = id;\r\n marca.push(puntoParada);\r\n lienzoRutas.addFeatures(marca);\r\n}", "function sc_angolo_gm(angolo_dec,dec){\n\n // by Salvatore Ruiu Irgoli-Sardegna (Italy). settembre 2010\n // scomposizione degli angoli decimali in °|'\n // [angolo_dec] in ore decimali.\n // la funzione restituisce la variabile stringa [angolo_gms]. \n \n var angolo=Math.abs(angolo_dec); // recupera il valore assoluto del numero\n\n\t var gradi= parseInt(angolo); // Gradi.\n var minuti= ((angolo-gradi)*60).toFixed(dec); // Minuti.\n \n if ( minuti>=60 ){ minuti= minuti-60; gradi=gradi+1;}\n //if ( gradi>=360){ gradi= gradi-360;} \n\n // trasforma il numero in stringa. \n\n var gradi_st=String(gradi);\n var minuti_st=String(minuti);\n \n if (angolo_dec<0) { gradi_st=\"-\"+gradi_st;} \n \n if ( gradi_st.length<2) { gradi_st='0'+gradi_st; }\n if ( minuti_st.length<=4-dec){ minuti_st='0'+minuti_st; }\n \n var angolo_gms=gradi_st+\"&ordm; \"+minuti_st+\"' \"; \n\t \nreturn angolo_gms; \n\n}", "function calcNiveau(){\r\n var ancienNiveau = perso.niveau\r\n while (perso.exp > perso.levelLimit){\r\n perso.exp = perso.exp - perso.levelLimit\r\n perso.levelLimit = Math.round(perso.levelLimit * 1.5)\r\n perso.niveau++\r\n niveauPlus = true\r\n gainDeNiveau()\r\n }\r\n\r\n if (niveauPlus){\r\n var message = \"Aurora a gagné \" + (perso.niveau - ancienNiveau) + \" niveau !!!\"\r\n niveauPlus = false\r\n }else {\r\n var message = \"aurora a gagné \" + perso.exp + \" pts d'experience\"\r\n }\r\n return message\r\n}", "function diaClave(propie){\n\n\tfor(i=0; i< propie.length; i++){\n\t\tvar info = propie[i].properties;\t\n\n\t\tconst latitud = info.LATITUD;\t \n\t\tconst longitud = info.LONGITUD;\t\t \n\t\tconst fecha = info.FECHA;\n\t\tconst pm10 = info.PM_10;\n\t\tconst pm25 = info.PM_2_5;\n\t\tconst NO2 = info.NO2;\n\t\tconst NO = info.NO;\n\t\tconst co = info.CO;\n\t\tconst so2 = info.SO2;\n\n\t\tconst fechaFormulario = document.querySelector('input[name=\"trip\"]').value;\t\n\t\t\t\n\t\t\n\t\tconst unicaFecha = new Date(fechaFormulario);\n\t\tconst transcurso1 = unicaFecha.getTime()\n\t\t\t\n\n\t\t//capturar la fecha del WFS y convertirla a milisegundos\n\t\t\n\t\t\n\t\tconst fechaWFS = new Date(info.FECHA);\t\t\t \t\n\t\tconst fechaWFStra = fechaWFS.getTime();\t\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t \n\t\t\tif(fechaWFStra === transcurso1){\n\t\t\t\t\t const informacion = new Estaciones(latitud, longitud, fecha, pm10, pm25, NO2, NO, co, so2 )\t\n\t\t\t\t\t\t\t const fech = informacion.fecha;\n\t\t\t\t\t\t\t const pm_10 = informacion.pm10;\n\t\t\t\t\t\t\t const pm_2_5 = informacion.pm25;\n\t\t\t\t\t\t\t const no2 = informacion.NO2;\n\t\t\t\t\t\t\t const No = informacion.NO;\n\t\t\t\t\t\t\t const Co = informacion.co;\n\t\t\t\t\t\t\t const So2 = informacion.so2;\n\t\t\t\t\t\t\t\n\t\t\t\t\t const gas = $('#filter2').val();\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t //escogerGas(gas);\n\t\t\t\t\tswitch (gas) {\n\t\t\t\t\t\tcase 'PM_10':\n\n\t\t\t\t\t\t\tvar marker = L.circle([latitud, longitud], {radius: (pm_10*10), stroke:true, color: coloresPM10(pm_10) }).bindPopup(`\n\t\t\t\t\t\t\t<h5>Información</h5>\n\t\t\t\t\t\t\t<ol>\n\t\t\t\t\t\t\t<li>Fecha: ${fechaFormulario}</li>\n\t\t\t\t\t\t\t<li>Medicion de Gas Promedio PM10: ${pm_10.toString()}</li>\n\t\t\t\t\t\t\t\t</ol>` ).addTo(mymap);\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tmymap.fitBounds(marker.getBounds(), { padding: [20, 20] });\t\n\t\t\t\t\t\t\t\tlimpiarMapa(marker);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'PM_2_5':\n\n\t\t\t\t\t\t\tvar marker = L.circle([latitud, longitud], {radius: (pm_2_5*10), stroke:true, color: coloresPM25(pm_2_5) }).bindPopup(`<ol>\n\t\t\t\t\t\t\t<li>${fechaFormulario}</li>\t\n\t\t\t\t\t\t\t<li>${pm_2_5.toString()}</li>\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t</ol>` ).addTo(mymap);\n\t\t\t\t\t\t\t\tmymap.fitBounds(marker.getBounds(), { padding: [20, 20] });\t\n\t\t\t\t\t\t\t\tlimpiarMapa(marker);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'N02':\n\n\t\t\t\t\t\t\tvar marker = L.circle([latitud, longitud], {radius: (no2*10), stroke:true, color: coloresNO(no2) }).bindPopup(`<ol>\n\t\t\t\t\t\t\t<li>${fechaFormulario}</li>\n\t\t\t\t\t\t\t<li>${no2.toString()}</li>\n\t\t\t\t\t\t\t\t</ol>` ).addTo(mymap);\n\t\t\t\t\t\t\t\tmymap.fitBounds(marker.getBounds(), { padding: [20, 20] });\n\t\t\t\t\t\t\t\tlimpiarMapa(marker);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'NO':\n\n\t\t\t\t\t\t\tvar marker = L.circle([latitud, longitud], {radius: (No*10), stroke:true, color: coloresNO(No) }).bindPopup(`<ol>\n\t\t\t\t\t\t\t<li>${fechaFormulario}</li>\t\n\t\t\t\t\t\t\t<li>${No.toString()}</li>\n\t\t\t\t\t\t\t\t</ol>` ).addTo(mymap);\n\t\t\t\t\t\t\t\tmymap.fitBounds(marker.getBounds(), { padding: [20, 20] });\t\n\t\t\t\t\t\t\t\tlimpiarMapa(marker);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'CO':\n\n\t\t\t\t\t\t\tvar marker = L.circle([latitud, longitud], {radius: (Co*10), stroke:true, color: coloresCO(Co) }).bindPopup(`<ol>\n\t\t\t\t\t\t\t<li>${fechaFormulario}</li>\n\t\t\t\t\t\t\t<li>${Co.toString()}</li>\n\t\t\t\t\t\t\t\t</ol>` ).addTo(mymap);\n\t\t\t\t\t\t\t\tmymap.fitBounds(marker.getBounds(), { padding: [20, 20] });\t\n\t\t\t\t\t\t\t\tlimpiarMapa(marker);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'SO2':\n\n\t\t\t\t\t\t\tvar marker = L.circle([latitud, longitud], {radius: (So2*10), stroke:true, color: coloresSO2(So2) }).bindPopup(`<ol>\n\t\t\t\t\t\t\t<li>${fechaFormulario}</li>\t\t\t\t\t\n\t\t\t\t\t\t\t<li>${So2.toString()}</li>\n\t\t\t\t\t\t\t\t</ol>` ).addTo(mymap);\n\t\t\t\t\t\t\t\tmymap.fitBounds(marker.getBounds(), { padding: [20, 20] });\t\n\t\t\t\t\t\t\t\tlimpiarMapa(marker);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\n\t\t\t\t\t\tdefault: console.log('no funciona');\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\t \n\t\t\t\t\t \n\t\t\t\t\t\t\t\t\t \n\t\t\t\t\t\t }\n\t\t\t\t else{\n\t\t\t\t\t\t\t console.log('no selecciono nada')\n\t\t\t\t\t\t }\n\t\t }\n\n}", "function fazPonto(ponto) {\n\tmarca = new google.maps.Marker({ position : ponto, map : map });\n\tcordenadasAtual = ponto;\n\tsetDocumentoInfo(ponto);\n\tmap.panTo(ponto);\n}", "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 Puissance4(lig,col,l,c){\r\n //commencement de l'analyse\r\n console.log(\"Valeurs: \"+lig+\" \"+col+\" / Incrément \"+i+ \" \"+c);\r\n if(c == 0 && l == 0){\r\n //pour moi c'est inversé a verticale, b horizontal, c diag gauche et d diag droit\r\n // horizontalité\r\n var va = 1 +Puissance4(lig +1,col,1,0) + Puissance4(lig-1,col,-1,0);\r\n // verticalité\r\n var vb = 1 +Puissance4(lig,col+1,0,1) + Puissance4(lig,col-1,0,-1);\r\n // diagonale de droite\r\n var vc = 1 +Puissance4(lig+1,col+1,1,1) + Puissance4(lig-1,col-1,-1,-1); \r\n // diagonale de gauche\r\n var vd = 1 +Puissance4(lig-1,col+1,-1,1) + Puissance4(lig+1,col-1,1,-1);\r\n console.log(va,vb,vc,vd);\r\n if(va == 4 || vb == 4 || vc == 4 || vd == 4)return true;\r\n else return false; \r\n }\r\n //On vérifie que \"lig\" et \"col\" ne sortent pas du tableau \r\n if (lig<this.ligne && lig>=0 && col<this.colonne && col>=0){\r\n if(this.plateau[lig][col]==joueur){\r\n return 1+ Puissance4(lig + l, col + c, l, c);}\r\n else {return 0;}\r\n }\r\n else return 0;\r\n }", "function trasf_equa_azim(njd,Ar,De,Long,Lat){\n\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) giugno 2013\n // njd= numero del giorno giuliano dell'istante da calcolare riferito al T.U.\n // Ar= ascensione retta in ore decimali.\n // De= declinazione in gradi sessadecimali\n // Long= Longitudine dell'osservatore =- per ovest rispetto a Greenwich\n // Lat= Latitudine dell'osservatore.\n\nvar ang_H=angolo_H(njd,Ar,Long); // calcolo dell'angolo orario H.\n\n // trasformare gli angoli sessadecimali in radianti.\n\n ang_H=Rad(ang_H*15); \n Ar= Rad(Ar*15); \n De= Rad(De); \n Long=Rad(Long); \n Lat= Rad(Lat); \n \n // angolo_a=altezza sull'orizzonte dell'astro. \n\nvar angolo_a=Math.sin(De)*Math.sin(Lat)+Math.cos(De)*Math.cos(Lat)*Math.cos(ang_H);\n angolo_a=Math.asin(angolo_a); // in radianti.\n angolo_a=Rda(angolo_a); // altezza dell'astro in gradi. \n \nvar azimut=(Math.sin(De)-Math.sin(Lat)*Math.sin(Rad(angolo_a)))/(Math.cos(Lat)*Math.cos(Rad(angolo_a)));\n azimut=Math.acos(azimut); \n azimut=Rda(azimut);\n\nazimut=(Math.sin(ang_H)<0) ? (azimut=azimut):(azimut=360-azimut); // operatore ternario.\n\nvar coord_azimut= new Array(angolo_a,azimut) ; // restituisce 2 valori: altezza e azimut.\n\nreturn coord_azimut;\n\n// NOTE SUL CALCOLO: \n// Se il seno di ang_H(angolo orario) è negativo (>180°) azimut=azimut, se positivo azimut=360-azimut\n\n}", "function angolo_H(njd,Ar,Long){\n\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) settembre 2010\n // njd= numero del giorno giuliano della data in T.U.\n // Ar= ascensione retta in ore decimali.\n // Long= Longitudine dell'ooseravtore. \n\nvar TSG=temposid (njd); // tempo siderale a Greenwich.\nvar TS_Loc=TSL(TSG,Long); // tempo siderale Locale.\nvar ang_H=TS_Loc-Ar; // angolo orario H.\n \n ang_H=ore_24(ang_H)*1; // H in ore decimali \n\nreturn ang_H;\n\n}", "function trataColisoes()\n{\n //lateral esquerda - 1\n if(esfera.posicao[0] - esfera.raio < parametrosMesa.xMin)\n {\n if(ultimaColisao != 1)\n {\n veloc[0] = -parametrosMesa.coeficienteRestituicao * veloc[0];\n ultimaColisao = 1;\n } \n }\n\n //lateral direita - 2\n if(esfera.posicao[0] + esfera.raio > parametrosMesa.xMax)\n {\n if(ultimaColisao != 2)\n {\n veloc[0] = -parametrosMesa.coeficienteRestituicao * veloc[0];\n ultimaColisao = 2;\n } \n }\n\n //cima - 3\n if(esfera.posicao[1] - esfera.raio < parametrosMesa.zMax)\n {\n if(ultimaColisao != 3)\n {\n veloc[2] = -parametrosMesa.coeficienteRestituicao * veloc[2];\n ultimaColisao = 3; \n }\n \n }\n\n //corredor direito - 4\n if(esfera.posicao[1] - esfera.raio > -30)\n { \n if( ( (esfera.posicao[0] - esfera.raio < -19.75) && (esfera.posicao[0] + esfera.raio > -17.75) ) || \n ( (esfera.posicao[0] + esfera.raio > -18.75) && (esfera.posicao[0] - esfera.raio < -20.75) ) )\n {\n if(ultimaColisao != 4)\n {\n veloc[0] = -parametrosMesa.coeficienteRestituicao * veloc[0];\n ultimaColisao = 4;\n } \n }\n \n\n //corredor esquerdo - 5\n if( (esfera.posicao[0] + esfera.raio > 19.04) && (esfera.posicao[0] - esfera.raio < 21.04) || \n (esfera.posicao[0] - esfera.raio < 20.04) && (esfera.posicao[0] + esfera.raio > 18.04) )\n {\n if(ultimaColisao != 5)\n {\n veloc[0] = -parametrosMesa.coeficienteRestituicao * veloc[0];\n ultimaColisao = 5;\n } \n }\n }\n\n /*//corner direito - 6\n if(esfera.posicao[0] - esfera.posicao[1] >= 50)\n {\n if(ultimaColisao != 6)\n {\n //TODO \n var normal = [-0.7, 0, -0.7];\n var normalx2 = [-1.4, 0, -1.4];\n var cosseno = mult(normal, normalize(veloc));\n var quase = mult(normalx2, cosseno);\n var vetorRefletido = subtract(quase, normalize(veloc) );\n veloc[0] = vetorRefletido[0]; veloc[2] = vetorRefletido[2];\n ultimaColisao = 6;\n }\n }\n\n //corner esquerdo - 7\n if(-esfera.posicao[0] + esfera.posicao[1] >= 50){\n if(ultimaColisao != 7)\n {\n //TODO \n var normal = [-0.7, 0, -0.7];\n var normalx2 = [-1.4, 0, -1.4];\n var cosseno = mult(normal, normalize(veloc));\n var quase = mult(normalx2, cosseno);\n var vetorRefletido = subtract(quase, normalize(veloc) );\n veloc[0] = vetorRefletido[0]; veloc[2] = vetorRefletido[2];\n ultimaColisao = 7;\n }\n }*/\n}", "function enviataxaaula(percent_aula, id_aula, id_projeto) {\n var envio = {}\n envio.id_contato = get_data('geral').id\n envio.id_aula = id_aula\n envio.percentual = percent_aula\n envio.email = get_data('geral').email \n envio.id_projeto = id_projeto \n\n set_tempo_ondemand(envio, (stst) => {\n //console.log('inserido - ' + id_aula + ' - ' + percent_aula + ' - ' + envio.id_contato)\n })\n}", "function generarPoblacionInicial(){\n\tarrayAux = new Array(GENES);\n\tfor(i=0;i<POBLACION;i++) {\n\n\t\t//aux con los numeros del 0 al 22\n\t\tfor(j=0;j<GENES;j++) {\n\t\t\tarrayAux[j] = j;\n\t\t}\n\n\t\t//rellenar cromosomas con el aux en orden aleatorio\n\t\tfor(j=0;j<GENES;j++) {\n\t\t\tcromosoma[i][j] = parseInt((arrayAux.splice(Math.floor(Math.random() * arrayAux.length), 1)).join(\"\"));\n\t\t}\n\t}\n}", "function AtrazoBoco (mês, valorAnuidade) {\n switch(mês) {\n case 1:\n return `Valor da Anuidade: ${valorAnuidade}`\n break\n\n case 2:\n const juroscomposto1 = valorAnuidade * ((1 + 0.05)**1)\n return `Valor da Anuidade com Juros: ${juroscomposto1.toFixed(2)}`\n break\n\n case 3:\n const juroscomposto2 = valorAnuidade * ((1 + 0.05)**2)\n return `Valor da Anuidade com Juros: ${juroscomposto2.toFixed(2)}`\n break\n\n case 4:\n const juroscomposto3 = valorAnuidade * ((1 + 0.05)**3)\n return `Valor da Anuidade com Juros: ${juroscomposto3.toFixed(2)}`\n break\n\n case 5:\n const juroscomposto4 = valorAnuidade * ((1 + 0.05)**4)\n return `Valor da Anuidade com Juros: ${juroscomposto4.toFixed(2)}`\n break\n\n case 6:\n const juroscomposto5 = valorAnuidade * ((1 + 0.05)**5)\n return `Valor da Anuidade com Juros: ${juroscomposto5.toFixed(2)}`\n break\n\n case 7:\n const juroscomposto6 = valorAnuidade * ((1 + 0.05)**6)\n return `Valor da Anuidade com Juros: ${juroscomposto6.toFixed(2)}`\n break\n\n case 8:\n const juroscomposto7 = valorAnuidade * ((1 + 0.05)**7)\n return `Valor da Anuidade com Juros: ${juroscomposto7.toFixed(2)}`\n break\n\n case 9:\n const juroscomposto8 = valorAnuidade * ((1 + 0.05)**8)\n return `Valor da Anuidade com Juros: ${juroscomposto8.toFixed(2)}`\n break\n\n case 10:\n const juroscomposto9 = valorAnuidade * ((1 + 0.05)**9)\n return `Valor da Anuidade com Juros: ${juroscomposto9.toFixed(2)}` \n break\n\n case 11:\n const juroscomposto10 = valorAnuidade * ((1 + 0.05)**10)\n return `Valor da Anuidade com Juros: ${juroscomposto10.toFixed(2)}`\n break\n\n case 12:\n const juroscomposto11 = valorAnuidade * ((1 + 0.05)**11)\n return `Valor da Anuidade com Juros: ${juroscomposto11.toFixed(2)}`\n break\n }\n }", "resumen_estado_nave(){\n this.ajuste_potencia();\n if (typeof this._potencia_disponible !== \"undefined\"){\n if (this._potencia_disponible){\n let estado_plasma = \"\";\n for (let i = 0; i < this._injectores.length; i++) {\n estado_plasma += \"Plasma \"+i.toString()+\": \";\n let total = this._injectores[i].get_plasma+this._injectores[i].get_extra_plasma;\n estado_plasma += total+\"mg/s \";\n }\n console.log(estado_plasma);\n\n for (let i = 0; i < this._injectores.length; i++) {\n if (this._injectores[i].get_danio_por<100){\n if (this._injectores[i].get_extra_plasma>0){\n console.log(\"Tiempo de vida: \"+this._injectores[i].tiempo_vuelo().toString()+\" minutos.\");\n } else {\n console.log(\"Tiempo de vida infinito!\");\n break;\n }\n }\n }\n } else {\n console.log(\"Unable to comply.\")\n console.log(\"Tiempo de vida 0 minutos.\")\n }\n } else {\n throw \"_potencia_disponible: NO DEFINIDA\";\n }\n }", "function fissaPezzoGiocatore() {\n\tfor(var r=0; r<player.pezzo.length; ++r) {\n\t\tfor(var c=0; c<player.pezzo[0].length; ++c) {\n\n\t\t\tif(player.pezzo[r][c]!=0) {\n\t\t\t\tcontenitore[r+player.pos.y/grandezza_di_un_quadratino_elementare][c+player.pos.x/grandezza_di_un_quadratino_elementare] = player.pezzo[r][c];\n\t\t\t}\n\n\t\t}\n\t}\n}", "function effemeridi_sole(TEMPO_RIF,LAT,LON,ALT,ITERAZIONI,LAN){\n\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) Ottobre 2011.\n // funzione per il calcolo delle effemeridi del Sole.\n\n // Parametri utilizzati\n \n // TEMPO_RIF= \"TL\" o \"TU\" tempo locale o tempo universale.\n // LAT= latitudine in gradi sessadecimali.\n // LON= longtudine in gradi sessadecimali.\n // ALT= altitudine in metri.\n // ITERAZIONE =numero di ripetizioni del calcolo.\n // LAN=\"EN\" versione in inglese.\n \n \nvar njd=calcola_jdUT0(); // numero del giorno giuliano all'ora 0 di oggi.\n\n njd=njd+0.00078; // correzione per il Terrestrial Time.\n \nvar data_ins=0; // data\nvar data_inser=0; // data\n\nvar numero_iterazioni=ITERAZIONI;\n\nvar effe_sole=0;\nvar ar_sole=0;\nvar de_sole=0;\nvar classetab=\"colore_tabellaef1\";\nvar crep=0; // crepuscolo astronomico.\nvar coo_app=0; // coordinate equatoriali apparenti.\nvar costl=\"\"; // costellazione.\nvar t_locale=0;\n\n var effe1=0;\n\n\n document.write(\"<table width=100% class='.table_effemeridi'>\");\n document.write(\" <tr>\");\n\n // versione in italiano.\n\n if (LAN!=\"EN\") // diverso da EN\n {\n document.write(\" <td class='colore_tabella'>Data:</td>\");\n document.write(\" <td class='colore_tabella'>Sorge:</td>\");\n document.write(\" <td class='colore_tabella'>Culmina:</td>\");\n document.write(\" <td class='colore_tabella'>Tramonta:</td>\");\n document.write(\" <td class='colore_tabella'>Az. Sorge:</td>\");\n document.write(\" <td class='colore_tabella'>Az. Tram.:</td>\");\n document.write(\" <td class='colore_tabella'>Ascensione Retta:</td>\");\n document.write(\" <td class='colore_tabella'>Declinazione:</td>\");\n document.write(\" <td class='colore_tabella'>Inizio Crep.:</td>\");\n document.write(\" <td class='colore_tabella'>Fine Crep.:</td>\");\n document.write(\" <td class='colore_tabella'>Cost.:</td>\");\n }\n\n // versione in inglese.\n\nif (LAN==\"EN\")\n {\n document.write(\" <td class='colore_tabella'>Date:</td>\");\n document.write(\" <td class='colore_tabella'>Rise:</td>\");\n document.write(\" <td class='colore_tabella'>Transit:</td>\");\n document.write(\" <td class='colore_tabella'>Set:</td>\");\n document.write(\" <td class='colore_tabella'>Az. Rise:</td>\");\n document.write(\" <td class='colore_tabella'>Az. Set.:</td>\");\n document.write(\" <td class='colore_tabella'>Right Ascension:</td>\");\n document.write(\" <td class='colore_tabella'>Declination:</td>\");\n document.write(\" <td class='colore_tabella'>Beg. Twilight:</td>\");\n document.write(\" <td class='colore_tabella'>End. Twilight:</td>\");\n document.write(\" <td class='colore_tabella'>Const.:</td>\");\n\n }\n\n document.write(\" </tr>\");\n\n njd=njd-1;\n\n for (b=0; b<numero_iterazioni; b++){\n njd=njd+1;\n effe1=ST_SOLE_LUNA(njd,TEMPO_RIF,\"S\",LON,LAT,ALT,0.25);\n \n effe_sole=pos_sole(njd);\n\n coo_app=pos_app(njd,effe_sole[0],effe_sole[1]) // coordinate apparenti.\n\n ar_sole= sc_ore(coo_app[0]); // ascensione retta.\n de_sole=sc_angolo(coo_app[1]); // declinazione.\n\n\n \n crep=crepuscolo(njd,TEMPO_RIF,LON,LAT,ALT);\n\n \n data_ins=jd_data(njd);\n\n if (LAN!=\"EN\") {data_inser=Lnum(parseInt(data_ins[0]),2)+\" : \"+Lnum(parseInt(data_ins[1]),2)+\"| \"+data_ins[3];} // versione in italiano.\n if (LAN==\"EN\") {data_inser=Lnum(parseInt(data_ins[0]),2)+\" : \"+Lnum(parseInt(data_ins[1]),2)+\"| \"+data_ins[4];} // versione in inglese.\n\n costl=costell(coo_app[0]); // costellazione. \n\n if (b%2==0){classetab=\"colore_tabellaef2\"; }\n\n else {classetab=\"colore_tabellaef1\";}\n\n\n document.write(\" <tr>\");\n document.write(\" <td class='\"+classetab+\"'>\"+data_inser+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+effe1[2]+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+effe1[3]+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+effe1[4]+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+effe1[0]+\"&deg;</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+effe1[1]+\"&deg;</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+ar_sole+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+de_sole+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+crep[0]+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+crep[1]+\"</td>\");\n document.write(\" <td class='\"+classetab+\"'>\"+costl+\"</td>\");\n\n document.write(\" </tr>\");\n\n }\n document.write(\" </table>\");\n\n\n\n}", "function IndicadorRangoEdad () {}", "function CreateLottoValues() {\r\n return Math.floor(Math.random() * 90 + 1);\r\n }", "function llogarit()\n{\n\n\tmerr();\n\n\tvar piket = 0;\n\n\tvar shumaKrediteve = 0;\n\n\tfor( var i = 0; i < fushatAktive.length; i++ )\n\t{\t\n\n\t\tvar kredit = LENDET[ fushatAktive[ i ].pozicioni ].kreditet;\n\n\t\tpiket += kredit * fushatAktive[ i ].vlera;\n\n\t\tshumaKrediteve += kredit;\n\n\t}\n\n\tif( gabim == true )\n\t{\n\n\t\tdocument.getElementById( \"pergjigja\" ).innerHTML = mesazhGabimi;\n\t}\n\telse\n\t{\t\n\t\tvar mesatarja = piket / shumaKrediteve;\n\n\t\tvar string = \"<br>Piket: \" + piket + \"<br>Kreditet: \" + shumaKrediteve + \"<br><b>Mesatarja: \" + mesatarja.toFixed( 2 ) + \"</b>\";\n\n\t\tdocument.getElementById( \"pergjigja\" ).innerHTML = string;\n\t}\n\n\t/// ngrirja e butonave\n\tdocument.querySelector( \"button\" ).disabled = true ;\n\n\tgabim = false;\n\n\tfushatAktive = [];\n}///FUND llogarit", "function addPoints(nombre) // il s'agit d'un séparateur de millier ==> by Vulca <==\r\n\t\t{\r\n\t\t\tvar signe = '';\r\n\t\t\tif (nombre<0)\r\n\t\t\t{\r\n\t\t\t\tnombre = Math.abs(nombre);\r\n\t\t\t\tsigne = '-';\r\n\t\t\t}\r\n\t\t\tnombre=parseInt(nombre);\r\n\t\t\tvar str = nombre.toString(), n = str.length;\r\n\t\t\tif (n <4) {return signe + nombre;}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\treturn signe + (((n % 3) ? str.substr(0, n % 3) + '.' : '') + str.substr(n % 3).match(new RegExp('[0-9]{3}', 'g')).join('.'));\r\n\t\t\t}\r\n\t\t}", "function impostaCausaliSpesa (list) {\n var opts = {\n aaData: list,\n oLanguage: {\n sZeroRecords: \"Nessun impegno associato\"\n },\n aoColumnDefs: [\n {aTargets: [0], mData: computeStringMovimentoGestione.bind(undefined, 'impegno', 'subImpegno', 'capitoloUscitaGestione')},\n {aTargets: [1], mData: readData(['subImpegno', 'impegno'], 'descrizione')},\n {aTargets: [2], mData: readData(['subImpegno', 'impegno'], 'importoAttuale', 0, formatMoney), fnCreatedCell: tabRight},\n {aTargets: [3], mData: readData(['subImpegno', 'impegno'], 'disponibilitaPagare', 0, formatMoney), fnCreatedCell: tabRight}\n ]\n };\n var options = $.extend(true, {}, baseOpts, opts);\n $(\"#tabellaMovimentiSpesa\").dataTable(options);\n }", "function crepuscolo(njd,tempo_rif,longitudine,latitudine,altitudine){\n\n // funzione per il calcolo del crepuscolo astronomico.\n // FUNZIONE DA ELIMINARE e sostituire con crepuscolo_UT\n \n var tempo_rifst=0; // tempo di riferimento per il sorgere e il tramonto.\n // \nif (tempo_rif==\"TL\") { tempo_rifst=-fuso_loc(); } // riferimento al tempo locale.\nelse if (tempo_rif==\"TU\") { tempo_rifst=0 ;} // il riferimento rimane il TU\n\n\n var ps_sole=pos_sole(njd);\n var DEs=ps_sole[1];\n\n var LATr=latitudine/180*Math.PI;\n var DEr=DEs/180*Math.PI;\n\n var H=Math.acos(-Math.tan(LATr)*Math.tan(DEr));\n\n var H1=Math.acos((Math.cos(1.88495556)-Math.sin(LATr)*Math.sin(DEr))/(Math.cos(LATr)*Math.cos(DEr)));\n\n var H= H*180/Math.PI;\n var H1=H1*180/Math.PI;\n\n var T=((H1-H)/15)*0.9973;\n\n// new Array(azimut_sorgere,azimut_tramonto,tempo_sorgere,tempo_transito,tempo_tramonto)\n// 0 1 2 3 4\n\n var p_sole=ST_ASTRO_DATA(njd,ps_sole[0],ps_sole[1],longitudine,latitudine,altitudine,0.25);\n\n var crep_m=ore_24(p_sole[2]-T+tempo_rifst); // crepuscolo del mattino.\n var crep_s=ore_24(p_sole[4]+T+tempo_rifst); // crepuscolo serale\n\n crep_m=sc_ore_hm(crep_m); // crepuscolo del mattino.\n crep_s=sc_ore_hm(crep_s); // crepuscolo serale\n\n var tempi_crep= new Array(crep_m,crep_s);\n\n return tempi_crep;\n \n}", "function pos_sole(njd){\n\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) dicembre 2009\n // funzione per il calcolo della posizione del sole.\n // njd= numero dei giorni giuliani per il T.U. di Greenwich.\n // la data di riferimento per gli elementi orbitali è l'equinozio della data.\n\n var T=(njd-2415020.0)/36525;\n\n // Elementi orbitali per l'equinozio della data.\n \n Long_epoca=279.69668+36000.76892*T+0.0003025*T*T;\n\n ecc_orbita=0.01675104-0.0000418*T-0.000000126*T*T;\n\n M=358.47583+35999.04975*T-0.000150*T*T-0.0000033*T*T*T;\n\n Long_perigeo=gradi_360(Long_epoca-M);\n\n \n // correzioni ***************\n\n var A=153.23+22518.7541*T;\n var B=216.57+45037.5082*T;\n var C=312.69+32964.3577*T;\n var D=350.74+445267.1142*T-0.00144*T*T;\n var E=231.19+20.20*T;\n var H=353.40+65928.7155*T;\n\n // angoli in radianti.\n\n A=Rad(A); \n B=Rad(B); \n C=Rad(C); \n D=Rad(D); \n E=Rad(E); \n H=Rad(H); \n\n // correzione per la longitudine.\n\n var delta_L=0.00134*Math.cos(A)\n +0.00154*Math.cos(B)\n +0.00200*Math.cos(C)\n +0.00179*Math.sin(D)\n +0.00178*Math.sin(E);\n\n // correzioni per il raggio vettore.\n\n var delta_R=0.00000543*Math.sin(A)\n +0.00001575*Math.sin(B)\n +0.00001627*Math.sin(C)\n +0.00003076*Math.cos(D) \n +0.00000927*Math.sin(H);\n \nvar semiasse=0.999996;\n\n // calcolo Equazione di Keplero\n\n M=gradi_360(M); // intervallo 0-360;\n\n var E=eq_keplero(M,ecc_orbita); // equazione di Keplero.\n\n var anomalia_vera =E[1]; // restituisce l'anomalia vera in radianti.\n\n // calcola il valore del raggio vettore. \n \n var distanzas=semiasse*(1-ecc_orbita*Math.cos(E[0])); \n distanzas=distanzas+delta_R; // correzione per il raggio vettore.\n\n // calcola il diametro apparente del Sole in secondi d'arco.\n\n var diam_app=1919.22/distanzas;\n diam_app=diam_app.toFixed(1);\n\n // parallasse diurna del Sole in gradi.\n\n var parallasse=(8.794/3600)/distanzas;\n\n var longitudine_sole=Rda(anomalia_vera)+Long_perigeo; \n\n longitudine_sole=gradi_360(longitudine_sole+delta_L); // longitudine ecclittica del sole + correzione.\n\n\n // coordinate ecclittiche: longitudine_sole,0 per la latitudine.\n \nvar coord_sole=trasf_ecli_equa(njd,longitudine_sole,0); // trasforma le coordinate ecclittiche in equatoriali: AR,DEC.\n\n // ELENCO delle variabili restituite dalla funzione [pos_sole]. \n\n // coord_sole[0]=ascensione retta in ore decimali (già diviso * 15). calcolate dalla funzione trasf_ecli_equa.\n // coord_sole[1]=declinazione in gradi sessadecimali.\n coord_sole[2]=longitudine_sole; // longitudine in gradi sessadecimali.\n coord_sole[3]=M; // anomalia media.\n coord_sole[4]=distanzas; // distanza in U.A.\n coord_sole[5]=diam_app; // diametro apparente del Sole.\n coord_sole[6]=parallasse; // parallasse diurna in gradi. \n\nreturn coord_sole;\n\n}", "function adivinarEstiloAprendizaje(estudiantes) {\n //valor que se utilizará para comparar\n var resultado = 100000;\n //tupla que almacenará la posición más cercana \n var numeroTupla = 0;\n //for que recorre todos los datos como parámetro de la consulta \n //de la tabla estudiantes\n for (var i = 0; i < estudiantes.length; i++) {\n var recintoTupla = 1;\n var sexoTupla = 1;\n \n //se le da valor a los recintos que pertenecen las personas en las\n //tuplas si es paraíso es 1 y turrialba es 2 \n\n if (estudiantes[i].recinto === 'Turrialba') {\n recintoTupla = 2;\n }\n //le da parámetro de 1 para masculino\n //si es femenino es 2\n if (estudiantes[i].sexo === 'F') {\n sexoTupla = 2;\n }\n //distancia euclidiana aplicada a los valores de las tuplas para definir distancia\n var sumatoria = Math.pow((sexoTupla - (parseInt(document.getElementById('sexo').value))), 2) + Math.pow(recintoTupla - (parseInt(document.getElementById('recinto').value)), 2) + \n Math.pow((parseFloat(estudiantes[i].promedio)) - (parseFloat(document.getElementById('promedio').value)), 2);\n var distancia = Math.sqrt(sumatoria);\n \n //aquí comparan para mostrar el más cercano al que entra como parámetro\n //comparando los datos de la tupla y los ingresados\n if (resultado > distancia) {\n resultado = distancia;\n numeroTupla = i;\n }\n }\n //select para cambiar el color y mostrar \n //el estilo de aprendizaje del estudiante\n switch (estudiantes[numeroTupla].estilo) {\n case \"ACOMODADOR\":\n document.getElementById('mensaje4').style.color = \"orange\";\n document.getElementById('mensaje4').innerHTML = 'Su estilo de aprendizaje es: ' + (estudiantes[numeroTupla].estilo) + ' en la posición '+estudiantes[numeroTupla].id+'.';\n break;\n case \"CONVERGENTE\":\n document.getElementById('mensaje4').style.color = \"blue\";\n document.getElementById('mensaje4').innerHTML = 'Su estilo de aprendizaje es: ' + (estudiantes[numeroTupla].estilo) + ' en la posición '+estudiantes[numeroTupla].id+'.';\n break;\n case \"ASIMILADOR\":\n document.getElementById('mensaje4').style.color = \"green\";\n document.getElementById('mensaje4').innerHTML = 'Su estilo de aprendizaje es: ' + (estudiantes[numeroTupla].estilo) + ' en la posición '+estudiantes[numeroTupla].id+'.';\n break;\n case \"DIVERGENTE\":\n document.getElementById('mensaje4').style.color = \"red\";\n document.getElementById('mensaje4').innerHTML = 'Su estilo de aprendizaje es: ' + (estudiantes[numeroTupla].estilo) + ' en la posición '+estudiantes[numeroTupla].id+'.';\n break;\n }\n}", "popuniIzvjestaj() {\n this.donja = Util.getRandomIntIn(50, 100);\n this.gornja = Util.getRandomIntIn(70, 140);\n this.puls = Util.getRandomIntIn(50, 160);\n }", "function crepuscolo_CV(njd,longitudine,latitudine,altitudine){\n\n // funzione per il calcolo del crepuscolo civile per il T.U. di Greenwich\n // aggiornata al 03/12/2011.\n // by Salvatore Ruiu - Irgoli (Italy).\n // IL Sole si trova a -6 gradi sotto l'orizzonte locale. 90+6 .\n \n var ps_sole=pos_sole(njd);\n var DEs=ps_sole[1]; // declinazione del Sole.\n\n var LATr=Rad(latitudine); // angolo in radianti.\n var DEr=Rad(DEs); // angolo in radianti.\n\n var H=Math.acos(-Math.tan(LATr)*Math.tan(DEr)); // angolo orario\n\n var H1=Math.acos((Math.cos(Rad(96))-Math.sin(LATr)*Math.sin(DEr))/(Math.cos(LATr)*Math.cos(DEr)));\n\n var H= Rda(H); // angolo da radiante a sessadecimale.\n var H1=Rda(H1); // angolo da radiante a sessadecimale. \n\n var T=((H1-H)/15)*0.9973;\n\n var p_sole=ST_SOLE(njd,longitudine,latitudine,altitudine);\n\n var crep_m=ore_24(p_sole[2]-T); // crepuscolo del mattino.\n var crep_s=ore_24(p_sole[4]+T); // crepuscolo serale.\n\n var tempi_crep= new Array(crep_m,crep_s);\n\n return tempi_crep;\n \n}", "function getPelnas() {\nvar pajamos = 12500;\nvar islaidos = 18500;\nvar pelnas = pajamos - islaidos;\nreturn pelnas;\n}", "function montaValorMes () {\r\n\t\t\t// laco de despesas\r\n\t\t\tfor (var x in $scope.despesas) {\r\n\t\t\t\t// separo a despesa\r\n\t\t\t\tvar despesa = $scope.despesas[x];\r\n\t\t\t\t// crio um atributo pres(array) na despesa\r\n\t\t\t\tdespesa.pres = [];\r\n\r\n\t\t\t\t// laco de meses até 8\r\n\t\t\t\t// for (var m=0; m<8; m++) {\r\n\t\t\t\tfor (var m=0; m<$scope.tlmeses; m++) {\r\n\t\t\t\t\tvar day = moment().add(m, \"M\").date(); // dia atual + 1\r\n\t\t\t\t\tvar month = moment().add(m, \"M\").month(); // mes atual + 1\r\n\t\t\t\t\tvar year = moment().add(m, \"M\").year(); // ano atual + 1\r\n\t\t\t\t\tvar data = ''; // variavel data\r\n\r\n\t\t\t\t\t// laco de prestacoes da despesa\r\n\t\t\t\t\tfor (var p=0; p<despesa.prestacoes; p++) {\r\n\t\t\t\t\t\tvar dia = moment(despesa.datavencimento).add(p, \"M\").date(); // dia da data despesa + index\r\n\t\t\t\t\t\tvar mes = moment(despesa.datavencimento).add(p, \"M\").month(); // mes data despesa + index\r\n\t\t\t\t\t\tvar ano = moment(despesa.datavencimento).add(p, \"M\").year(); // ano data despesa + index\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t// caso o mes e ano da despesa seja = ao mes e ano atual \r\n\t\t\t\t\t\tif (mes === month && ano === year) {\r\n\t\t\t\t\t\t\tdata = {\"data\": mes+\"/\"+ano, \"valor\":despesa.valor};\r\n\t\t\t\t\t\t\t// pegando a prestação atual\r\n\t\t\t\t\t\t\tif (m === 0) { // m = o ( mes atual )\r\n\t\t\t\t\t\t\t\tdespesa.prestacao = (p+1)+\"/\"+despesa.prestacoes;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (!despesa.prestacao) {\r\n\t\t\t\t\t\t// se ano = atual mas mes menor ou ano menor\r\n\t\t\t\t\t\tif ( (ano === year && mes < month) || (ano < year) ) {\r\n\t\t\t\t\t\t\tdespesa.prestacao = despesa.prestacoes+\"/\"+despesa.prestacoes;\r\n\t\t\t\t\t\t}else{\r\n\t\t\t\t\t\t\tdespesa.prestacao = \"0/\"+despesa.prestacoes;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif ( data === '' ) {\r\n\t\t\t\t\t\tdespesa.pres.push({\"data\": \"00/0000\", \"valor\":\"xxxx\", \"color\":\"background:#f0f5f5; color:#ccc;\", \"icon\":\"fa-trophyx\"});\r\n\t\t\t\t\t}else{\r\n\t\t\t\t\t\tdespesa.pres.push(data);\r\n\t\t\t\t\t\t$scope.totais[m].valor = $scope.totais[m].valor + parseInt(despesa.valor);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif($scope.totais[m-1] != undefined && $scope.totais[m].valor < $scope.totais[m-1].valor) {\r\n\t\t\t\t\t\t\t$scope.totais[m].icon = \"fa-arrow-down\";\r\n\t\t\t\t\t\t}else if($scope.totais[m-1] != undefined && $scope.totais[m].valor > $scope.totais[m-1].valor) {\r\n\t\t\t\t\t\t\t$scope.totais[m].icon = \"fa-arrow-up\";\r\n\t\t\t\t\t\t}else{\r\n\t\t\t\t\t\t\t$scope.totais[m].icon = \"fa-arrow-right\";\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t$scope.totalgeral = $scope.totalgeral + parseFloat(despesa.valor);\r\n\t\t\t}\r\n\t\t}", "function calculosGanado(fila) {\n\n var mermaObtenida, pesoPagar, precioXkilo, total, pesoFinal;\n var genero = fila[GENERO].value;\n var peso = Number.parseFloat(GetKilosSinSimbolo(fila[PESO].value));\n var repeso = Number.parseFloat(GetKilosSinSimbolo(fila[REPESO].value));\n\n //NO hay repeso\n if (repeso <= 0) {\n repeso = peso;\n }\n //merma\n if (repeso >= peso) {\n mermaObtenida = 0;\n }\n else{\n mermaObtenida = MermaGenerada(peso, repeso);\n }\n pesoPagar = PesoSugerido(peso, repeso, mermaObtenida);\n precioXkilo = PrecioSugerido(pesoPagar, genero);\n total = TotalPagar(pesoPagar, precioXkilo);\n fila[MERMA].value = mermaObtenida;\n fila[PESOPAGAR].value = pesoPagar;\n fila[COSTOPORKILO].value = precioXkilo;\n fila[TOTAL].value = total;\n\n $(\".merma\").maskMoney('mask');\n $(\".kg\").maskMoney('mask');\n $(\".money\").maskMoney('mask');\n\n }", "function asigna_lentes () {\n var filas = obtener_valor('filPLANT');\n var i = 1;\n for (i = 1; i <= filas; i++) {\n asignar_valorM('PLANT',\"<a href=javascript:abrir_archivo(\" + i + \",'\"+ 'PLANT' +\"',\" + 6 + \") ><img src=images/verexp.png border=0></a>\",i,5); \n }\n}", "function iniciar(){\n for(let i = 1; i <= 31; i ++){\n let dezena = diaSorteService.montaDezena(i);\n vm.dezenas.push(dezena);\n }\n vm.selecaoAtual = -1;\n }", "function insertarDatosTablaPuntosRuta(aux){\r\n var features = new Array();\r\n \r\n var pt = new OpenLayers.Geometry.Point(aux.x,aux.y);\r\n pt.transform( new OpenLayers.Projection( \"EPSG:4326\" ),\r\n new OpenLayers.Projection( \"EPSG:900913\" ) );\r\n \r\n var idPt = new OpenLayers.Feature.Vector( pt, {\r\n id : contadorPuntos\r\n });\r\n\r\n if(strTipoRecorrido==\"B\"){\r\n /*Enviar al estore de la tabla de puntos de ruta*/\r\n storePuntosRuta.add(new Ext.data.Record({\r\n numero : contadorPuntos,\r\n latitud : aux.y,\r\n longitud: aux.x\r\n }));\r\n \r\n /* linea */\r\n puntosLineaRuta.push(pt);\r\n }else if(strTipoRecorrido==\"R\"){\r\n /*Enviar al estore de la tabla de puntos de ruta*/\r\n storePuntosRuta.insert((contadorPuntos-1),new Ext.data.Record({\r\n numero : contadorPuntos,\r\n latitud : aux.y,\r\n longitud: aux.x\r\n }));\r\n \r\n /* linea */\r\n puntosLineaRuta.splice((contadorPuntos-1),0,pt);\r\n }else if(strTipoRecorrido==\"BR\"){\r\n /*Enviar al estore de la tabla de puntos de ruta*/\r\n storePuntosRuta.insert(contadorPuntos,new Ext.data.Record({\r\n numero : contadorPuntos,\r\n latitud : aux.y,\r\n longitud: aux.x\r\n }));\r\n \r\n /* linea */\r\n puntosLineaRuta.splice(contadorPuntos,0,pt);\r\n }\r\n idPt.id = contadorPuntos;\r\n features.push(idPt);\r\n lienzoRutas.addFeatures(features);\r\n}", "calcolaArea() {\n\n return (this.base * this.altezza) / 2; \n }", "function descuentoPersonas(precio, personas){\n var descuentoTotal = 0;\n \n if (personas >= 4 && personas <= 6) {\n descuentoTotal = precio * 5;\n }\n if (personas >= 7 && personas <= 8) {\n descuentoTotal = precio * 10;\n \n }\n if (personas > 8) {\n descuentoTotal = precio * 15;\n }\n return descuentoTotal / 100;\n}", "function amelioration(){\n return nbMultiplicateurAmelioAutoclick +9;\n}", "function uspjesnost() {\n let brojRijesenih = 0;\n let procenat = 0;\n\n zadaci.forEach(zadatak => {\n if (zadatak.zavrsen === true) {\n brojRijesenih++;\n }\n })\n procenat = ((brojRijesenih / zadaci.length) * 100).toFixed(2);\n\n if (procenat < 50) {\n document.getElementById(\"uspesnost\").style.color = \"#DC143C\";\n } else {\n document.getElementById(\"uspesnost\").style.color = \"#00AD56\";\n }\n if (zadaci.length == 0) {\n document.getElementById('uspesnost').innerHTML = '';\n } else {\n document.getElementById('uspesnost').innerHTML = '<h6>Uspjesnost: ' + procenat + '%</h6>';\n }\n}", "function auxNaipes(promedio) {\n let simbolo;\n\n if(promedio > 0 && promedio <= 19) \n simbolo = 'A';\n else if(promedio >= 20 && promedio <= 38) \n simbolo = 'B';\n else if(promedio >= 39 && promedio <= 57) \n simbolo = 'C';\n else if(promedio >= 58 && promedio <= 76) \n simbolo = 'D';\n else if(promedio >= 77 && promedio <= 95) \n simbolo = 'E';\n else if(promedio >= 96 && promedio <= 114) \n simbolo = 'F';\n else if(promedio >= 115 && promedio <= 133) \n simbolo = 'G';\n else if(promedio >= 134 && promedio <= 152) \n simbolo = 'H';\n else if(promedio >= 153 && promedio <= 171) \n simbolo = 'I';\n else if(promedio >= 172 && promedio <= 190) \n simbolo = 'J';\n else if(promedio >= 191 && promedio <= 209) \n simbolo = 'K';\n else if(promedio >= 210 && promedio <= 228) \n simbolo = 'L';\n else if(promedio >= 229 && promedio <= 256) \n simbolo = 'M';\n return simbolo;\n\n}", "function gradi_360(angolo){\n\n // angolo in gradi sessadecimali.\n // riporta l'angolo all'interno dell'intervallo 0° - 360° \n \n if (angolo>360){ while (angolo>360) {angolo=angolo-360;} }\n\nelse if (angolo<0 ){ while (angolo<0) {angolo=angolo+360;} }\n\n\nreturn angolo;\n\n}", "function hitungLuasSegiEmpat(sisi){\n //tidak ada nilai balik\n var luas = sisi * sisi\n return luas\n}", "generarMapa(){\n this.counterId = 1;\n this.salaActual = new Sala(true,NaN, NaN, \"0.txt\", 0 ,this.counterId);\n this.counterId++;\n var listaNodosAActualizar = [this.salaActual];\n this.inicio = this.salaActual;\n while (listaNodosAActualizar.length > 0)\n {\n var proximaProfundida = [];\n listaNodosAActualizar.forEach(sala => {\n\n var derecha = false, izquierda = false ,arriba = false ,abajo = false;\n //Genara la sala de la izuierda, que no necesariamente se va a utilizar\n if(sala.izquierda == null)\n {\n sala.izquierda = this.generarSala(posicionSala.izquierda, sala);\n izquierda = true;\n }\n\n //Genara la sala de la derecha\n if(sala.derecha == null) {\n sala.derecha = this.generarSala(posicionSala.derecha, sala);\n derecha = true;\n }\n //Genera la sala de arriba\n if(sala.arriba == null) {\n sala.arriba = this.generarSala(posicionSala.arriba, sala);\n arriba = true;\n }\n //genera la sala de abajo\n if(sala.abajo == null) {\n sala.abajo = this.generarSala(posicionSala.abajo, sala);\n abajo = true;\n }\n //Los mete en la proxima generacion\n if(izquierda) proximaProfundida.push(sala.izquierda);\n if(derecha) proximaProfundida.push(sala.derecha);\n if(arriba) proximaProfundida.push(sala.arriba);\n if(abajo) proximaProfundida.push(sala.abajo);\n\n\n\n\n });\n proximaProfundida = proximaProfundida.filter(x=> x.depth <= 3 );\n proximaProfundida = proximaProfundida.filter(x => x != this.inicio);\n listaNodosAActualizar = proximaProfundida;\n\n }\n }", "function jelKenta(niz)\n{\n\t/* make a set from an array */\n\tvar skup = napraviSet(niz);\n\tvar tmpn = Array.from(skup);\n\ttmpn.sort();\n\n\tif(skup.size === 5)\n\t{\n\t\tconsole.log(tmpn[4]);\n\t\t/* kandidat za kentu */\n\t\tif((tmpn[4] - tmpn[0]) === 4)\n\t\t{\n\t\t\t/* velika ili mala kenta? */\n\t\t\tif(tmpn[0] === 1)\n\t\t\t\treturn 75;\n\t\t\telse\n\t\t\t\treturn 80;\n\t\t}\n\t\telse\n\t\t\treturn 0;\n\t}\n\telse\n\t\treturn 0;\n\n}", "function determinarTipoProfesor(profesores) {\n //valor que se utilizará para comparar\n var resultado = 100000;\n //tupla que almacenará la posición más cercana \n var numeroTupla = 0;\n //for que recorre todos los datos como parámetro de la consulta \n //de la tabla profesores\n for (var i = 0; i < profesores.length; i++) {\n //variables utilizadas para determinar los valores finales de\n //cada uno de los valores de la consulta cambiandolos por números\n var generoTupla, autoEvaluacionTupla, disciplinaTupla,\n pcTupla, habWebTupla, expWebTupla = 0;\n \n //se proporciona un número dependiendo del sexo del profesor\n //o si no quiere mostrarlo\n switch(profesores[i].b){\n case \"F\": \n generoTupla = 1;\n break;\n case \"M\": \n generoTupla = 2;\n break;\n case \"NA\": \n generoTupla = 3;\n break;\n }\n //se proporciona un número dependiendo de la autoEvalución del profesor\n //de 1 a 3\n switch(profesores[i].c){\n case \"B\": \n autoEvaluacionTupla = 1;\n break;\n case \"I\": \n autoEvaluacionTupla = 2;\n break;\n case \"A\": \n autoEvaluacionTupla = 3;\n break;\n }\n //se proporciona un número dependiendo de la disciplina del profesor\n //desde 1 a 3\n switch(profesores[i].e){\n case \"DM\": \n disciplinaTupla = 1;\n break;\n case \"ND\": \n disciplinaTupla = 2;\n break;\n case \"o\": \n disciplinaTupla = 3;\n break;\n } \n \n //se proporciona un número dependiendo de las habilidades con la computadora\n //del profesor de 1 a 3\n switch(profesores[i].f){\n case \"L\": \n pcTupla = 1;\n break;\n case \"A\": \n pcTupla = 2;\n break;\n case \"H\": \n pcTupla = 3;\n break;\n }\n \n //se proporciona un número dependiendo de la experiencia \n //utilizando tecnologías web para enseñanza del profesor\n //de 1 a 3\n switch(profesores[i].g){\n case \"N\": \n habWebTupla = 1;\n break;\n case \"S\": \n habWebTupla = 2;\n break;\n case \"O\": \n habWebTupla = 3;\n break;\n }\n \n //se proporciona un número dependiendo de la experiencia \n //del profesor para utilizar páginas web para enseñanza del profesor\n //de 1 a 3\n switch(profesores[i].h){\n case \"N\": \n expWebTupla = 1;\n break;\n case \"S\": \n expWebTupla = 2;\n break;\n case \"O\": \n expWebTupla = 3;\n break;\n } \n //distancia euclidiana aplicada a los valores de las tuplas para definir distancia\n var sumatoria = Math.pow(profesores[i].a - (parseInt(document.getElementById('edad').value)), 2) + Math.pow(generoTupla - (parseInt(document.getElementById('genero').value)), 2) + \n Math.pow(autoEvaluacionTupla - (parseInt(document.getElementById('autoevaluacion').value)), 2) + Math.pow(profesores[i].d - (parseInt(document.getElementById('numeroVeces').value)), 2) +\n Math.pow(disciplinaTupla - (parseInt(document.getElementById('disciplina').value)), 2) + Math.pow(pcTupla - (parseInt(document.getElementById('habilidadPC').value)), 2) +\n Math.pow(habWebTupla - (parseInt(document.getElementById('habilidadWeb').value)), 2) + Math.pow(expWebTupla - (parseInt(document.getElementById('experienciaWeb').value)), 2);\n var distancia = Math.sqrt(sumatoria);\n \n //aquí comparan para mostrar el más cercano al que entra como parámetro\n //comparando los datos de la tupla y los ingresados\n if (resultado > distancia) {\n resultado = distancia;\n numeroTupla = i;\n }\n }\n //salida en pantalla del tipo de profesor\n document.getElementById('mensaje5').innerHTML = 'El profesor es de tipo ' + profesores[numeroTupla].clase + ' en la posición '+profesores[numeroTupla].id+'.';\n}", "function _GeraPericias(tabela_classe, tabela_geracao_classe, nivel) {\n if (tabela_geracao_classe.ordem_pericias == null) {\n // Nao possui ordem das pericias.\n return;\n }\n // Pra simplificar, usa so o basico + inteligencia.\n var num_pericias = tabela_classe.pontos_pericia + gPersonagem.atributos['inteligencia'].modificador;\n var max_pontos = nivel + 3;\n for (var i = 0; i < num_pericias && i < tabela_geracao_classe.ordem_pericias.length; ++i) {\n gPersonagem.pericias.lista[tabela_geracao_classe.ordem_pericias[i]].pontos = max_pontos;\n }\n}", "function ST_LUNA(njd,LON,LAT,ALT){\n\n // metodo iterativo per calcolare il sorgere e il tramontare della Luna\n // compresi gli azimut del sorgere e del tramontare.\n // nel calcolo si tiene conto della rifrazione, altitudine dell'osservatore e della parallasse lunare.\n // by Salvatore Ruiu Irgoli-Sardegna (Italy). 10 Dicembre 2011.\n\n var p_astro=0; // posizione della Luna. \n var tempo_sorgere=0; // tempo del sorgere.\n var tempo_tramonto=0; // tempo del tramonto.\n var tempo_transito=0; // tempo transito.\n var azimut_sorgere=0; // azimut sorgere.\n var azimut_tramonto=0; // azimut tramonto.\n var st_astri_sl=0; //\n\n njd=jdHO(njd); // riporta il g.g. della data all'ora H0(zero) del giorno. \n\n var njd1=njd; // giorno giuliano corretto per il sorgere o per il tramonto.\n var raggio=0.25; // raggio apparente della Luna.\n\n // **** inizio delle 10 iterazioni previste per il calcolo del Sorgere della Luna.\n\n for (a=0; a<10; a++) {\n\n p_astro=pos_luna(njd1); // recupera l'AR la DE e il raggio apparente del Sole.\n raggio=p_astro[6]/3600/2; // raggio della Luna in gradi.\n p_app=pos_app_pa(njd1,p_astro[0],p_astro[1],p_astro[5],LAT,LON,ALT); \n\n st_astri_sl=ST_ASTRO_DATA(njd1,p_app[0],p_app[1],LON,LAT,ALT,raggio);\n\n tempo_sorgere=st_astri_sl[2]; // istante del sorgere.\n njd1=njd+tempo_sorgere/24;\n }\n\n azimut_sorgere=st_astri_sl[0]; // azimut del sorgere.\n \n \n // **** inizio delle 10 iterazioni previste per il calcolo del transito della Luna.\n\n for (a=0; a<10; a++) {\n\n p_astro=pos_luna(njd1);\n raggio=p_astro[6]/3600/2; // astro di riferimento: sole.\n p_app=pos_app_pa(njd1,p_astro[0],p_astro[1],p_astro[5],LAT,LON,ALT);\n \n st_astri_sl=ST_ASTRO_DATA(njd1,p_app[0],p_app[1],LON,LAT,ALT,raggio);\n\n tempo_transito=st_astri_sl[3]; // istante del transito.\n njd1=njd+tempo_transito/24;\n }\n \n // **** inizio delle 10 iterazioni previste per il calcolo del tramontare della Luna.\n\n for (a=0; a<10; a++) {\n\n p_astro=pos_luna(njd1);\n raggio=p_astro[6]/3600/2;\n p_app=pos_app_pa(njd1,p_astro[0],p_astro[1],p_astro[5],LAT,LON,ALT);\n \n st_astri_sl=ST_ASTRO_DATA(njd1,p_app[0],p_app[1],LON,LAT,ALT,raggio);\n\n tempo_tramonto=st_astri_sl[4]; // istante del tramonto.\n njd1=njd+tempo_tramonto/24;\n }\n \n azimut_tramonto=st_astri_sl[1]; // azimut del tramontare.\n\n//alert(st_astri_sl[5]);\n\nvar tempi_st= new Array(azimut_sorgere,azimut_tramonto,tempo_sorgere,tempo_transito,tempo_tramonto) ; \n// VARIABILI RESTITUITE 0 1 2 3 4\n\nreturn tempi_st;\n\n}", "function botonPrecionado(peso) {\n\n switch (peso) {\n case 10:\n addPeso(peso);\n break;\n case 7.5://6.6\n addPeso(peso);\n break;\n case 4.3://3.3\n addPeso(peso);\n break;\n case 0:\n addPeso(peso);\n break;\n default:\n }\n indicePregunta++;\n if(indicePregunta < preguntas.length){\n cambiarPregunta();\n }\n else {\n analizarAptitudes();\n // document.getElementById(\"con1\").value = 1\n // document.getElementById(\"con2\").value = 1\n // document.getElementById(\"con3\").value = 1\n // document.getElementById(\"con4\").value = 1\n // document.getElementById(\"con5\").value = 1\n // document.getElementById(\"con6\").value = 1\n\n //enviar resultados a\n document.getElementById(\"voc-form\").submit();\n\n }\n }", "function valorAleatorio(pMaximo){\n\treturn Math.floor(Math.random()* (pMaximo));\n}", "function perimetroTiangulo(lado1,lado2,base) { \n return lado1+lado2+base; \n }", "function navegarCompra(liga){\r\n if(localStorage.getItem('totales')){\r\n // const url = liga + '?carrito=T';\r\n navegar(liga);\r\n }\r\n else{\r\n mostrarPopUp('No hay artículos que comprar');\r\n // alert('No hay artículos que comprar');\r\n }\r\n}", "function compraArma(i){\n\n if(mochilaArmas.length == 0){\n if(jogador1.grana < mercadoArmas[i].preco){\n console.log('Falta din!!!')\n }else{\n mochilaArmas.push(mercadoArmas[i])\n \n jogador1.grana -= mercadoArmas[i].preco \n }\n }else{\n for(let j in mochilaArmas){\n if(i == mochilaArmas[j].id){\n console.log('Já tem esta arma!')\n return\n }\n }\n if(jogador1.grana < mercadoArmas[i].preco){\n console.log('Falta din!!!')\n }else{\n jogador1.nArmas++;\n mochilaArmas.push(mercadoArmas[i])\n //localStorage.setItem(`arma${i}`, JSON.stringify(mercadoArmas[i]))\n jogador1.grana -= mercadoArmas[i].preco \n }\n }\n gravarLS('grana', jogador1.grana); \n mostraInfoJogador()\n}", "function calcularNovaPonta(conceitoContainer, ligacaoContainer){\r\n \tvar coordenadas = new Coordenadas(new Array(),new Array());\r\n \tvar coordenadasFinais = new Coordenadas(new Object(),new Object());\r\n \tvar conceitoX = parseFloat(conceitoContainer.x);\r\n \tvar conceitoY = parseFloat(conceitoContainer.y);\r\n \tvar ligacaoX = parseFloat(ligacaoContainer.x);\r\n \tvar ligacaoY = parseFloat(ligacaoContainer.y);\r\n \t\r\n \tvar larguraConceito = gerenciadorLigacao.getLargura(conceitoContainer);\r\n \tvar alturaConceito = gerenciadorLigacao.getAltura(conceitoContainer);\r\n \tvar larguraLigacao = gerenciadorLigacao.getLargura(ligacaoContainer);\r\n \tvar alturaLigacao = gerenciadorLigacao.getAltura(ligacaoContainer);\r\n \t\r\n \t\r\n \tfor(var i=0;i<8;i++){\r\n \t\tcoordenadas.conceito[i] = new Object();\r\n \t\tcoordenadas.ligacao[i] = new Object();\r\n \t}\r\n \t\r\n \t//para o conceito\r\n \tcoordenadas.conceito[0].x = conceitoX;\r\n \tcoordenadas.conceito[0].y = conceitoY;\r\n \t\r\n \tcoordenadas.conceito[1].x = conceitoX + (larguraConceito/2);\r\n \tcoordenadas.conceito[1].y = conceitoY;\r\n \t\r\n \tcoordenadas.conceito[2].x = conceitoX + (larguraConceito);\r\n \tcoordenadas.conceito[2].y = conceitoY;\r\n \t\r\n \tcoordenadas.conceito[3].x = conceitoX + (larguraConceito);\r\n \tcoordenadas.conceito[3].y = conceitoY + (alturaConceito/2);\r\n \t\r\n \tcoordenadas.conceito[4].x = conceitoX + (larguraConceito);\r\n \tcoordenadas.conceito[4].y = conceitoY + (alturaConceito);\r\n \t\r\n \tcoordenadas.conceito[5].x = conceitoX + (larguraConceito/2);\r\n \tcoordenadas.conceito[5].y = conceitoY + (alturaConceito);\r\n \t\r\n \tcoordenadas.conceito[6].x = conceitoX;\r\n \tcoordenadas.conceito[6].y = conceitoY + (alturaConceito);\r\n \t\r\n \tcoordenadas.conceito[7].x = conceitoX;\r\n \tcoordenadas.conceito[7].y = conceitoY + (alturaConceito/2);\r\n \t\r\n \t//para a ligacao\r\n \tcoordenadas.ligacao[0].x = ligacaoX;\r\n \tcoordenadas.ligacao[0].y = ligacaoY;\r\n \t\r\n \tcoordenadas.ligacao[1].x = ligacaoX + (larguraLigacao/2);\r\n \tcoordenadas.ligacao[1].y = ligacaoY;\r\n \t\r\n \tcoordenadas.ligacao[2].x = ligacaoX + (larguraLigacao);\r\n \tcoordenadas.ligacao[2].y = ligacaoY;\r\n \t\r\n \tcoordenadas.ligacao[3].x = ligacaoX + (larguraLigacao);\r\n \tcoordenadas.ligacao[3].y = ligacaoY + (alturaLigacao/2);\r\n \t\r\n \tcoordenadas.ligacao[4].x = ligacaoX + (larguraLigacao);\r\n \tcoordenadas.ligacao[4].y = ligacaoY + (alturaLigacao);\r\n \t\r\n \tcoordenadas.ligacao[5].x = ligacaoX + (larguraLigacao/2);\r\n \tcoordenadas.ligacao[5].y = ligacaoY + (alturaLigacao);\r\n \t\r\n \tcoordenadas.ligacao[6].x = ligacaoX;\r\n \tcoordenadas.ligacao[6].y = ligacaoY + (alturaLigacao);\r\n \t\r\n \tcoordenadas.ligacao[7].x = ligacaoX;\r\n \tcoordenadas.ligacao[7].y = ligacaoY + (alturaLigacao/2);\r\n \t\r\n \t\r\n \tif(ligacaoY >= coordenadas.conceito[6].y){ //pontaLigacao[1] � pontaConceito[5]\r\n \t\t\r\n \t\tcoordenadasFinais.conceito.x = coordenadas.conceito[5].x;\r\n \t\tcoordenadasFinais.conceito.y = coordenadas.conceito[5].y;\r\n \t\tcoordenadasFinais.ligacao.x = coordenadas.ligacao[1].x;\r\n \t\tcoordenadasFinais.ligacao.y = coordenadas.ligacao[1].y;\r\n \t\treturn coordenadasFinais;\r\n \t}\r\n \tif(ligacaoY < coordenadas.conceito[6].y && coordenadas.ligacao[4].x <= conceitoX){ //pontaLigacao[3] � pontaConceito[7]\r\n \t\t\r\n \t\tcoordenadasFinais.conceito.x = coordenadas.conceito[7].x;\r\n \t\tcoordenadasFinais.conceito.y = coordenadas.conceito[7].y;\r\n \t\tcoordenadasFinais.ligacao.x = coordenadas.ligacao[3].x;\r\n \t\tcoordenadasFinais.ligacao.y = coordenadas.ligacao[3].y;\r\n \t\treturn coordenadasFinais;\r\n \t}\r\n \tif(coordenadas.ligacao[5].y <= conceitoY){ //pontaLigacao[5] � pontaConceito[1]\r\n \t\t\r\n \t\tcoordenadasFinais.conceito.x = coordenadas.conceito[1].x;\r\n \t\tcoordenadasFinais.conceito.y = coordenadas.conceito[1].y;\r\n \t\tcoordenadasFinais.ligacao.x = coordenadas.ligacao[5].x;\r\n \t\tcoordenadasFinais.ligacao.y = coordenadas.ligacao[5].y;\r\n \t\treturn coordenadasFinais;\r\n \t}\r\n \tif(coordenadas.ligacao[6].y > conceitoY && coordenadas.ligacao[4].x >= conceitoX){ //pontaLigacao[3] � pontaConceito[7]\r\n \t\t\r\n \t\tcoordenadasFinais.conceito.x = coordenadas.conceito[3].x;\r\n \t\tcoordenadasFinais.conceito.y = coordenadas.conceito[3].y;\r\n \t\tcoordenadasFinais.ligacao.x = coordenadas.ligacao[7].x;\r\n \t\tcoordenadasFinais.ligacao.y = coordenadas.ligacao[7].y;\r\n \t\treturn coordenadasFinais;\r\n \t}\t\r\n }", "getAlumnosPgLimit(limit,progra){\n return querys.select(\"select DISTINCT on (uatf_datos.id_ra) * from uatf_datos \\\n INNER JOIN alumnos ON (alumnos.id_ra = uatf_datos.id_ra) where id_programa='\"+ progra +\"' limit \"+limit)\n }", "function puntosCultura(){\r\n\t\tvar a = find(\"//div[@id='lmid2']//b\", XPList);\r\n\t\tif (a.snapshotLength != 5) return;\r\n\r\n\t\t// Produccion de puntos de cultura de todas las aldeas\r\n\t\tvar pc_prod_total = parseInt(a.snapshotItem(2).innerHTML);\r\n\t\t// Cantidad de puntos de cultura actuales\r\n\t\tvar pc_actual = parseInt(a.snapshotItem(3).innerHTML);\r\n\t\t// Puntos de cultura necesarios para fundar la siguiente aldea\r\n\t\tvar pc_aldea_prox = parseInt(a.snapshotItem(4).innerHTML);\r\n\r\n\t\t// 下一个的村庄数\r\n\t\tvar aldeas_actuales = (check3X() )? pc2aldeas3X(pc_aldea_prox) : pc2aldeas(pc_aldea_prox) ;\r\n\t\t// 目前村庄数\r\n\t\tvar aldeas_posibles = (check3X() )? pc2aldeas3X(pc_actual) : pc2aldeas(pc_actual) ;\r\n\r\n\t\tvar texto = '<table class=\"tbg\" align=\"center\" cellspacing=\"1\" cellpadding=\"2\"><tr class=\"rbg\"><td>' + T('ALDEA') + '</td><td>' + T('PC') + \"</td></tr>\";\r\n\t\tvar j = pc_f = 0;\r\n\t\tfor (var i = 0; i < 3; i++){\r\n\t\t\tvar idx = i + j;\r\n\r\n\t\t\ttexto += '<tr><td>' + (aldeas_actuales + idx + 1) + '</td><td>';\r\n\r\n\t\t\t// 下一级需要的文明\r\n\t\t\tvar pc_necesarios = (check3X() )? aldeas2pc3X(aldeas_actuales + idx) : aldeas2pc(aldeas_actuales + idx) ;\r\n\r\n\t\t\t// Si hay PC de sobra\r\n\t\t\tif (pc_necesarios < pc_actual) {\r\n\t\t\t\ttexto += T('FUNDAR');\r\n\t\t\t\tpc_f = 1;\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\t// Tiempo en segundos hasta conseguir los puntos de cultura necesarios\r\n\t\t\t\tvar tiempo = ((pc_necesarios - pc_actual) / pc_prod_total) * 86400;\r\n\r\n\t\t\t\tvar fecha = new Date();\r\n\t\t\t\tfecha.setTime(fecha.getTime() + (tiempo * 1000));\r\n\t\t\t\tvar texto_tiempo = calcularTextoTiempo(fecha);\r\n\r\n\t\t\t\ttexto += T('FALTA') + ' <b>' + (pc_necesarios - pc_actual) + '</b> ' + T('PC') +'<br/>';\r\n\t\t\t\ttexto += T('LISTO') + \" \" + texto_tiempo;\r\n\t\t\t}\r\n\t\t\ttexto += '</td></tr>';\r\n\r\n\t\t\tif (pc_f && pc_necesarios >= pc_actual) {\r\n\t\t\t\tj = idx + 1;\r\n\t\t\t\tpc_f = i = 0;\r\n\t\t\t}\r\n\t\t}\r\n\t\ttexto += '</table>';\r\n\r\n\t\ta.snapshotItem(4).parentNode.innerHTML += \"<p>\" + texto + \"</p>\";\r\n\t}" ]
[ "0.64422095", "0.61768454", "0.61179996", "0.5892089", "0.5804307", "0.5803588", "0.5788157", "0.5760647", "0.5747325", "0.5740767", "0.57371205", "0.57371205", "0.57371205", "0.57371205", "0.57325304", "0.5719989", "0.5711199", "0.5709437", "0.570328", "0.5696191", "0.569617", "0.5679569", "0.5674146", "0.565999", "0.5657168", "0.56336945", "0.56289804", "0.5593515", "0.5582776", "0.55714804", "0.55630624", "0.55429256", "0.553765", "0.55352014", "0.55328315", "0.55205595", "0.5505588", "0.5501263", "0.54941684", "0.54928434", "0.5492283", "0.54906315", "0.54884124", "0.54856956", "0.54855144", "0.54716456", "0.54650486", "0.5464083", "0.54621464", "0.5453684", "0.5453165", "0.5444263", "0.54410905", "0.5440455", "0.54342425", "0.5424235", "0.5418489", "0.54078096", "0.54064333", "0.54056346", "0.53960663", "0.538504", "0.53776675", "0.53747773", "0.53679323", "0.53643906", "0.53608406", "0.5358731", "0.5358461", "0.5355112", "0.5348853", "0.53475493", "0.5339913", "0.5317598", "0.5315874", "0.5312571", "0.53120553", "0.5310815", "0.5303105", "0.5295103", "0.5294171", "0.5287588", "0.5283877", "0.5282865", "0.5281762", "0.52807784", "0.5273578", "0.526623", "0.5265746", "0.5263464", "0.5262692", "0.52608305", "0.52593416", "0.525893", "0.52573544", "0.5250547", "0.52457017", "0.524533", "0.5245273", "0.52399623" ]
0.5878641
4
gestire ordine in base ai valori
function ordina(){ for (var i = 0; i<persone.length; i++){ var minimoFinOra = i; for(var j=i+1; j<persone.length; j++){ if(persone[j].altezza<persone[minimoFinOra].altezza){ minimoFinOra = j; } } // Salvo il valore minimo var tmp = persone[i]; persone[i] = persone[minimoFinOra]; persone[minimoFinOra] = tmp; } //Visualizzo visualizzaPersone(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function afase_luna(njd){\n\n // calcola l'angolo di fase della luna per la data (njd)\n // gennaio 2012\n\n var dati_luna=pos_luna(njd); // recupero fase/elongazione (1)\n var dati_sole=pos_sole(njd);\n\n var elongazione1=dati_luna[4]; // elongazione in gradi sessadecimali.\n var dist_luna=dati_luna[7]/149597870; \n var dist_sole=dati_sole[4]; // distanza del sole in UA.\n\n elongazione=Math.abs(elongazione1)*1;\n\n var dist_sl=dist_luna*dist_luna+dist_sole*dist_sole-2*dist_luna*dist_sole*Math.cos(Rad(elongazione)); // distanza sole-luna\n dist_sl=Math.sqrt(dist_sl);\n\n // calcolo dell'angolo di fase in gradi . \n\n var Dpt= dist_luna; // distanza pianeta-terra.\n var Dts= dist_sole; // distanza terra-sole.\n var Dps= dist_sl; // distanza pianeta-sole.\n\n // teorema del coseno\n\n var delta_fase=(Dts*Dts+Dps*Dps-Dpt*Dpt)/(2*Dps*Dts);\n delta_fase=Math.acos(delta_fase); \n delta_fase=Rda(delta_fase);\n\n var angolo_fase=180-elongazione-delta_fase; // angolo di fase in gradi.\n\n if(elongazione1<0) {angolo_fase=-angolo_fase; }\n\n return angolo_fase;\n\n}", "function targetTerdekat(arr) {\n var index1 = 0;\n var index2 = 0;\n var tampung = 0;\n var arrX = [];\n var hasilakhir;\n\n if (arr.indexOf('x') === -1) {\n return 0;\n } else {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] === 'x') {\n index1 = i;\n arrX.push(index1);\n } else if (arr[i] === 'o') {\n index2 = i;\n arrX.push(index1);\n }\n var hasil = [];\n for (var j = 0; j < arrX.length; j++) {\n tampung = Math.abs(index2 - arrX[j]);\n hasil.push(tampung);\n hasil.sort();\n }\n hasilakhir = hasil;\n }\n return hasilakhir[0];\n }\n}", "function ordinamento (x, y) {\r\n return x - y;\r\n}", "function targetTerdekat(arr) {\n // you can only write your code here!\n let a = 0;\n let b = 0;\n let tampung = 0;\n let arrX = [];\n\n if(arr.indexOf('x') === -1){\n return 0;\n }\n else{\n for(var i = 0; i < arr.length; i++){\n if(arr[i] === 'x'){\n a = i;\n arrX.push(a);\n }\n else if(arr[i] === 'o'){\n b = i;\n }\n var hasil = [];\n for(var j = 0; j < arr.length; j++){\n tampung = Math.abs(b - arrX[j]);\n hasil.push(tampung);\n hasil.sort();\n }\n }\n return hasil[0]; \n }\n }", "function ArithGeoII(arr) {\n var faktor=0;\n var arithver=[];\n for(var i=1;i<arr.length;i++) {\n faktor=arr[i]-arr[i-1];\n arithver.push(faktor);\n }\n if(arithver[0]==arithver[arr.length-2]) return 'Arithmetic';\n var geover=[];\n for(i=1;i<arr.length;i++) {\n faktor=Math.abs(arr[i]/arr[i-1]);\n geover.push(faktor);\n }\n geover.sort(function(a,b){return a-b});\n if(geover[0]==geover[arr.length-2]) return 'Geometric';\n return -1;\n}", "function tentukanDeretGeometri(arr) {\n // you can only write your code here!\n var selisih=[];\n var benar=0;\n if(arr[0]<arr[1]){\n for(var a=0;a<(arr.length-1);a++){\n selisih +=arr[a+1]/arr[a];\n if(selisih.length>1&&selisih[a]===selisih[a-1]){\n benar +=1;\n }\n }\n return benar===(selisih.length-1);\n }\n }", "function targetTerdekat(arr) {\n // you can only write your code here!\n\n return arr.indexOf('x') - arr.indexOf('o') > 0 ? arr.indexOf('x') - arr.indexOf('o') : (arr.length-1) + (arr.indexOf('x') - arr.indexOf('o'));\n \n\n\n }", "function Gn(e,t){var a=e[t];e.sort(function(e,t){return P(e.from(),t.from())}),t=d(e,a);for(var n=1;n<e.length;n++){var r=e[n],f=e[n-1];if(P(f.to(),r.from())>=0){var o=G(f.from(),r.from()),i=U(f.to(),r.to()),s=f.empty()?r.from()==r.head:f.from()==f.head;n<=t&&--t,e.splice(--n,2,new Di(s?i:o,s?o:i))}}return new Oi(e,t)}", "function tentukanDeretGeometri(arr) {\n var hasilBagi = arr[1] / arr[0] // selisih dari hasil bagi\n var hitung = 0;\n var cek;\n for(var i = 0; i < arr.length-1; i++){\n \thitung = arr[i+1] / arr[i];\n \t//console.log(hitung); //cek hasil hitungan\n }\n cek = hitung === hasilBagi;\n return cek;\n}", "function buscarIndiceLetra(op, letra) {\n let i;\n \n abc.map((letraArr, indice) => {\n if(op == \"sumar\") {\n if(letra.toLowerCase() == letraArr) {\n i = indice + posiciones;\n };\n }else if(op == \"restar\") {\n if(letra.toLowerCase() == letraArr) {\n i = indice - posiciones;\n };\n }\n });\n \n // Si i es mas grande que el numero de letras en el abecedario empezara desde el comienzo.\n // Si i es mas bajo que el numero de letras en el abecedario empezara desde el final.\n if(i > abc.length - 1) {\n i = i - abc.length\n }else if(i < 0) {\n i = abc.length - Math.abs(i);\n };\n \n return abc[i];\n}", "getBoneEndDistance(b) {\nreturn this.distance[b];\n}", "cohesion(boids) {\n const neighborDist = 50\n const sum = new Vector(0, 0) // Start with empty vector to accumulate all positions\n let count = 0\n for (let other of boids) {\n const d = this.agent.location.dist(other.location)\n if ((d > 0) && (d < neighborDist)) {\n sum.add(other.position) // Add position\n count++\n }\n }\n if (count > 0) {\n sum.divide(count)\n return seek(sum) // Steer towards the position\n }\n else {\n return new Vector(0, 0)\n }\n }", "function angolo_H(njd,Ar,Long){\n\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) settembre 2010\n // njd= numero del giorno giuliano della data in T.U.\n // Ar= ascensione retta in ore decimali.\n // Long= Longitudine dell'ooseravtore. \n\nvar TSG=temposid (njd); // tempo siderale a Greenwich.\nvar TS_Loc=TSL(TSG,Long); // tempo siderale Locale.\nvar ang_H=TS_Loc-Ar; // angolo orario H.\n \n ang_H=ore_24(ang_H)*1; // H in ore decimali \n\nreturn ang_H;\n\n}", "calculer_distance() {}", "function tentukanDeretGeometri(arr) {\n // you can only write your code here!\n var difference= [];\n var correct= 0;\n if(arr[0] < arr[1]){\n for(var a = 0; a < (arr.length - 1); a++){\n difference +=arr[a + 1]/arr[a];\n if(difference.length > 1 && difference[a] === difference[a - 1]){\n correct += 1;\n }\n }\n return correct === (difference.length - 1);\n }\n}", "function afase_pianeta(njd,AR,DE,dist_ps,dist_pt){\n\n // funzione per il calcolo dell'angolo di fase per un pianeta.\n // AR,DE sono le coordinate equatoriali decimali, del pianeta.\n // njd= numero del giorno giuliano.\n // dist_ps=distanza pianeta-sole in UA.\n // dist_pt=distanza pianeta-Terra in UA.\n // by Salvatore Ruiu - gennaio 2013.\n\n var coo_sole=pos_sole(njd); // coordinate equatoriali decimali del Sole.\n var Rs=coo_sole[4]; // distanza Terra-Sole. \n var elongaz=elong(AR,DE,coo_sole[0],coo_sole[1]); // elongazione in gradi dal Sole.\n\n // calcolo dell'angolo di fase in gradi . \n\n var Dpt= dist_pt; // distanza pianeta-terra.\n var Dts= Rs; // distanza terra-sole.\n var Dps= dist_ps; // distanza pianeta-sole.\n\n // risolve il teorema del coseno (noti i 3 lati del triangolo).\n\n var delta_fase=(Dts*Dts+Dps*Dps-Dpt*Dpt)/(2*Dps*Dts);\n delta_fase=Math.acos(delta_fase); \n delta_fase=Rda(delta_fase);\n\n var angolo_fase=180-Math.abs(elongaz)-delta_fase; // risultato: angolo di fase in gradi.\n\nreturn angolo_fase;\n\n}", "get distance() {}", "calculateHeuristic(start, end) {\n let d1 = Math.abs(end.x - start.x);\n let d2 = Math.abs(end.y - start.y);\n return d1 + d2;\n }", "function volar(golondrina, distancia) {\n \n return{\n energia: golondrina.energia - (2*distancia), \n nombre:golondrina.nombre}\n}", "function jelKenta(niz)\n{\n\t/* make a set from an array */\n\tvar skup = napraviSet(niz);\n\tvar tmpn = Array.from(skup);\n\ttmpn.sort();\n\n\tif(skup.size === 5)\n\t{\n\t\tconsole.log(tmpn[4]);\n\t\t/* kandidat za kentu */\n\t\tif((tmpn[4] - tmpn[0]) === 4)\n\t\t{\n\t\t\t/* velika ili mala kenta? */\n\t\t\tif(tmpn[0] === 1)\n\t\t\t\treturn 75;\n\t\t\telse\n\t\t\t\treturn 80;\n\t\t}\n\t\telse\n\t\t\treturn 0;\n\t}\n\telse\n\t\treturn 0;\n\n}", "cohesion(boids) {\r\n let neighbordist = 50;\r\n let sum = createVector(0, 0); // Start with empty vector to accumulate all locations\r\n let count = 0;\r\n for (let i = 0; i < boids.length; i++) {\r\n let d = p5.Vector.dist(this.position, boids[i].position);\r\n if ((d > 0) && (d < neighbordist)) {\r\n sum.add(boids[i].position); // Add location\r\n count++;\r\n }\r\n }\r\n if (count > 0) {\r\n sum.div(count);\r\n return this.seek(sum); // Steer towards the location\r\n } else {\r\n return createVector(0, 0);\r\n }\r\n }", "function heuristica(a, b) {\r\n var x = Math.abs(a.x - b.x);\r\n var y = Math.abs(a.y - b.y);\r\n\r\n var dist = x + y;\r\n\r\n return dist;\r\n}", "function menoramayor(elem1, elem2){\n\n // return se encarga de finalizar la operacion y devolver el resultado\n return elem1 -elem2;\n}", "function heuristic(start, goal) {\n return Math.abs(start[0] - goal[0]) + Math.abs(start[1] - goal[1])\n}", "function _distFromCharger(pos) {\n\tvar delta = Math.abs(pos.x - _charger.x) + Math.abs(pos.y - _charger.y);\n\treturn delta;\n}", "cohesion(boids) {\n let neighbordist = 50;\n let sum = createVector(0, 0); // Start with empty vector to accumulate all locations\n let count = 0;\n for (let i = 0; i < boids.length; i++) {\n let d = p5.Vector.dist(this.position, boids[i].position);\n if ((d > 0) && (d < neighbordist)) {\n sum.add(boids[i].position); // Add location\n count++;\n }\n }\n if (count > 0) {\n sum.div(count);\n return this.seek(sum); // Steer towards the location\n } else {\n return createVector(0, 0);\n }\n }", "get endA() { return Math.max(this.fromA, this.toA - 1); }", "function longitudCola(){\n var lng = cola.length;\n var tam = 0;\n var i;\n for (i=0;i<lng;i++){\n tam += cola[i].datlng;\n }\n return tam;\n }", "function lookupWordEulersGallop(word) {\r\n \r\n if (!lookup(0)) return false; //if no words exist, ours doesn't either\r\n\r\n word = word.toLowerCase(); //for string compare to work\r\n\r\n //instead of a step size of a 1000, use gallop search for O(logn) instead of O(n/1000)\r\n var upper_bound = 1;\r\n var tries = 0;\r\n var upper_bound_found = false;\r\n while (lookup(upper_bound) && !upper_bound_found) { //if the dictionary is over, that's our upper bound\r\n if (lookup(upper_bound).toLowerCase() == word) //since our recursive depends on bounds being checked\r\n return upper_bound; \r\n else if (lookup(upper_bound).toLowerCase() > word) //this is our upper bound, kill the loop\r\n upper_bound_found = true; \r\n else upper_bound *= 2; //try again with twice the test bound\r\n tries++;\r\n }\r\n\r\n console.log();\r\n console.log('upper bound of ' + upper_bound + ' found in ' + tries + ' gallops');\r\n\r\n var lower_bound = Math.floor(upper_bound/2); //set the lower bound based on gallop search\r\n if (lookup(lower_bound).toLowerCase() == word) return lower_bound; //since our recursive depends on bounds being checked\r\n\r\n //both lower and upper bound have been checked before sending it in\r\n return EulersRecursive(lower_bound, upper_bound, word);\r\n}", "function dist() {\n let temp = Math.floor(\n findDistance(coord.lat, goal.lat, coord.long, goal.long)\n );\n\n return temp;\n }", "degree(u) {\n\t\tea && assert(this.validVertex(u));\n\t\tlet d = 0;\n\t\tfor (let e = this.firstAt(u); e != 0; e = this.nextAt(u,e)) d++;\n\t\treturn d;\n\t}", "function hachage(chaine) {\n let condensat = 0;\n \n for (let i = 0; i < chaine.length; i++) {\n condensat = (condensat +chaine.charCodeAt(i) * 3 ** i) % 65536;\n }\n \n return condensat;\n}", "function TNodes_doFindClosestLineDistance(nd,direction){\n var mysplit=nd.Parent;\n var myupnode=nd.Parent.UpNode;\n var mydownnode=nd; \n var resultnode={};\n \n // TOP ********************************************************\n if (direction=='top'){\n resultnode=myupnode; \n \n if (myupnode.HasChild==true){\n var ot=mysplit.Orientation;\n var maxTD=mydownnode.TopDistance - myupnode.Height;\n\n //console.log(mysplit.AbsoluteIndex + '.top element -> maxTD:' + maxTD); \n \n var n=(mydownnode.HasChild)?mydownnode.Child.AbsoluteIndex-1:this.Count;\n for (var i=myupnode.Child.AbsoluteIndex;i<=n;i++){\n if (this.Item[i].Level<=mysplit.Level) {\n break;\n }\n if (ot==this.Item[i].Orientation){\n if (this.Item[i].UpNode.TopDistance + this.Item[i].UpNode.Height>=maxTD){\n maxTD=this.Item[i].UpNode.TopDistance + this.Item[i].UpNode.Height;\n resultnode=this.Item[i].UpNode;\n //console.log(this.Item[i].UpNode.Ident + ' ' + i + '.top element -> maxTD:' + maxTD); \n }\n } \n }\n }\n //console.log('top: max topdistance -->' + maxTD + ' | ' + 'top resultnode->' ,resultnode);\n\n if (nd.Parent.AbsoluteIndex==resultnode.Parent.AbsoluteIndex){\n var upinterval=myupnode.Height + mydownnode.Height - zeroConstants.mingridheight \n }else{\n var upinterval=nd.Height + nd.TopDistance - resultnode.TopDistance - resultnode.Height - zeroConstants.mingridheight;\n }\n \n return upinterval;\n \n } // end top\n\n // BOTTOM *************************************\n if (direction=='bottom'){\n resultnode=mydownnode; \n \n if (mydownnode.HasChild==true){\n var ot=mysplit.Orientation;\n var minTD=mydownnode.TopDistance + mydownnode.Height;\n\n //console.log(mysplit.AbsoluteIndex + '.bottom element -> minTD:' + minTD); \n\n for (var i=mydownnode.Child.AbsoluteIndex;i<=this.Count; i++){\n if (this.Item[i].Level<=mysplit.Level) {\n break;\n }\n if (ot==this.Item[i].Orientation){\n if (this.Item[i].DownNode.TopDistance<=minTD){\n minTD=this.Item[i].DownNode.TopDistance;\n resultnode=this.Item[i].DownNode;\n //console.log(this.Item[i].DownNode.Ident + ' ' + i + '.element -> minTD:' + minTD); \n }\n } \n }\n }\n //console.log('bottom: min topdistance -->' + minTD + ' | ' + 'bottom resultnode -->' ,resultnode);\n\n if (nd.Parent.AbsoluteIndex==resultnode.Parent.AbsoluteIndex){\n var downinterval=zeroConstants.mingridheight; \n }else{\n if (nd.TopDistance>resultnode.TopDistance){\n alert('negative distance during finding bottomline ');\n downinterval=zeroConstants.mingridheight;\n }else{\n var downinterval=nd.Height - (resultnode.TopDistance - nd.TopDistance) + zeroConstants.mingridheight;\n }\n }\n\n return downinterval;\n \n }// end bottom\n\n\n // LEFT ********************************************************\n if (direction=='left'){\n resultnode=myupnode; \n \n if (myupnode.HasChild==true){\n var ot=mysplit.Orientation;\n var maxLD=mydownnode.LeftDistance - myupnode.Width;\n\n //console.log(mysplit.AbsoluteIndex + '.left element -> maxLD:' + maxLD); \n \n var n=(mydownnode.HasChild)?mydownnode.Child.AbsoluteIndex-1:this.Count;\n for (var i=myupnode.Child.AbsoluteIndex;i<=n;i++){\n if (this.Item[i].Level<=mysplit.Level) {\n break;\n }\n if (ot==this.Item[i].Orientation){\n if (this.Item[i].UpNode.LeftDistance + this.Item[i].UpNode.Width>=maxLD){\n maxLD=this.Item[i].UpNode.LeftDistance + this.Item[i].UpNode.Width;\n resultnode=this.Item[i].UpNode;\n //console.log(this.Item[i].UpNode.Ident + ' ' + i + '.left element -> maxLD:' + maxLD); \n }\n } \n }\n }\n //console.log('left max leftdistance -->' + maxLD + ' | ' + 'left resultnode->' ,resultnode);\n\n if (nd.Parent.AbsoluteIndex==resultnode.Parent.AbsoluteIndex){\n var upinterval=myupnode.Width + mydownnode.Width - zeroConstants.mingridwidth; \n }else{\n var upinterval=nd.Width + (nd.LeftDistance - resultnode.LeftDistance) - resultnode.Width - zeroConstants.mingridwidth;\n\n if (upinterval<zeroConstants.mingridwidth){\n console.log('negative distance during finding rightline '); \n upinterval=zeroConstants.mingridwidth;\n } \n }\n \n return upinterval;\n\n } // end left\n \n // RIGHT *************************************\n if (direction=='right'){\n resultnode=mydownnode; \n \n if (mydownnode.HasChild==true){\n var ot=mysplit.Orientation;\n var minLD=mydownnode.LeftDistance + mydownnode.Width;\n\n //console.log(mysplit.AbsoluteIndex + '.right element -> minLD:' + minLD); // + ' minTD:' + minTD); \n\n for (var i=mydownnode.Child.AbsoluteIndex;i<=this.Count; i++){\n if (this.Item[i].Level<=mysplit.Level) {\n break;\n }\n if (ot==this.Item[i].Orientation){\n if (this.Item[i].DownNode.LeftDistance<=minLD){\n minLD=this.Item[i].DownNode.LeftDistance;\n resultnode=this.Item[i].DownNode;\n //console.log(this.Item[i].DownNode.Ident + ' ' + i + '.element -> minLD:' + minLD); // + ' minTD:' + minTD); \n }\n } \n }\n }\n //console.log('right: min leftdistance -->' + minLD + ' | ' + 'right resultnode->' ,resultnode);\n \n if (nd.Parent.AbsoluteIndex==resultnode.Parent.AbsoluteIndex){\n var downinterval=zeroConstants.mingridwidth; \n }else{\n var downinterval=nd.Width - (resultnode.LeftDistance - nd.LeftDistance) + zeroConstants.mingridwidth;\n \n if (downinterval<zeroConstants.mingridwidth){\n console.log('negative distance during finding rightline '); \n downinterval=zeroConstants.mingridwidth;\n }\n }\n\n return downinterval;\n\n }// end right\n \n }", "getEnpassantFen() {\n const L = this.epSquares.length;\n if (!this.epSquares[L - 1]) return \"-\"; //no en-passant\n let res = \"\";\n this.epSquares[L - 1].forEach(sq => {\n res += V.CoordsToSquare(sq) + \",\";\n });\n return res.slice(0, -1); //remove last comma\n }", "getDistFromTile(tile)\n {\n let pos = this.position.copy();\n pos.subtract(tile.position);\n\n return pos.magnitude;\n }", "function desviacionEstandarMuestra(array) {\n\t\t\tlet desviacionEstandar = varianzaMuestra(array) ** (1/2);\n\t\t\treturn desviacionEstandar;\n\t\t}", "function h1(tablero) {\n\n let cordenadasObjetivo = ['3,3', '0,0', '0,1', '0,2', '0,3', '1,0', '1,1', '1,2', '1,3', '2,0', '2,1', '2,2', '2,3', '3,0', '3,1', '3,2'];\n let cordenadasTablero = ['0,0', '0,1', '0,2', '0,3', '1,0', '1,1', '1,2', '1,3', '2,0', '2,1', '2,2', '2,3', '3,0', '3,1', '3,2', '3,3'];\n let sumaDistancias = 0;\n\n for (let index = 0; index < tablero.length; index++) {\n let numero = tablero[index];\n let cordenadaCorrespondiente = cordenadasTablero[index]\n let cordenadaObjetivo = cordenadasObjetivo[numero]\n //console.log(`Numero: ${numero} ; Está en: ${cordenadaCorrespondiente} ; Vá en: ${cordenadaObjetivo}`);\n let distanciaX = Math.abs(Number(cordenadaCorrespondiente[0]) - Number(cordenadaObjetivo[0]));\n let distanciaY = Math.abs(Number(cordenadaCorrespondiente[2]) - Number(cordenadaObjetivo[2]));\n sumaDistancias += (distanciaX + distanciaY);\n }\n //console.log(`Heuristica: ${sumaDistancias}`);\n return sumaDistancias;\n\n}", "find_direction(distance_of_travel) {\r\n\r\n // As the distance_of_travel array will be up, right, down, left\r\n // lets use this to find and set a order to the directions the ghost will follow.\r\n // note if two distances are the same it will select then in the order above\r\n\r\n var i, direction, last_val = 9999, len = distance_of_travel.length;\r\n for (i = 0; i < len; i ++) {\r\n if (distance_of_travel[i].value < last_val) {\r\n last_val = distance_of_travel[i].value; // store last val for compare \r\n direction = distance_of_travel[i]; \r\n }\r\n }\r\n return direction;\r\n }", "function euclidian(punto1,punto2)\n\t\t\t{\n\t\t\t\tvar p1 = region.nodos[punto1];\n\t\t\t\tvar p2 = region.nodos[punto2];\n\t\t\t\tvar add = Math.pow(p2.x - p1.x,2) + Math.pow(p2.y-p1.y,2);\n\t\t\t\treturn Math.sqrt(add);\n\t\t\t}", "function kadanesAlgorithm(array) {\n\tlet maxSum = array[0] // -2 \n\tlet currentSum = array[0] // -2 \n\tfor (let i = 1; i < array.length; i++ ) {\n\t\tcurrentSum += array[i]\n\t\tcurrentSum = Math.max(array[i], currentSum)\n\t\tmaxSum = Math.max(currentSum, maxSum) \n\t}\n\treturn maxSum\n}", "geistBewegen() {\n //variablen heranholen zur leichteren lesbarkeit\n\n let knoten = this.knoten;\n let geist = this.geist;\n let pacman = this.pacMan;\n let level = this.level;\n let geistAltX = this.geist.posX;\n let geistAltY = this.geist.posY;\n geist.isMoving = false;\n if (knoten[geist.posY][geist.posX].nexthop(geist.richtungNeu) == geist.richtungNeu) { //prüfung ob der nächste schritt ein feld ist auf das man sich bewegen darf\n geist.richtung = geist.richtungNeu;\n switch (geist.richtung) {\n case Spielvariablen.Richtungen.hoch:\n {\n geist.posY--;\n geist.offsetY = this.factor;\n break;\n }\n case Spielvariablen.Richtungen.links:\n {\n geist.posX--;\n geist.offsetX = this.factor;\n break;\n }\n case Spielvariablen.Richtungen.rechts:\n {\n geist.posX++;\n geist.offsetX = -this.factor;\n break;\n }\n case Spielvariablen.Richtungen.runter:\n {\n geist.offsetY = -this.factor;\n geist.posY++;\n break;\n }\n } //richtungsänderung\n //positionsänderung mit evtl. übersprung auf andere seite\n if (geist.posX < 0)geist.posX = knoten[0].length - 1;\n if (geist.posY < 0)geist.posY = knoten.length - 1;\n if (geist.posX > knoten[0].length - 1)geist.posX = 0;\n if (geist.posY > knoten.length - 1)geist.posY = 0;\n if (pacman.posX == geist.posX && pacman.posY == geist.posY) this.beendet = true;\n\n if (!(geist.posX == geistAltX && geist.posY == geistAltY))geist.isMoving = true;\n\n }\n //ängstlich zurücksetzen wenn geist im haus\n if (level[geist.posY][geist.posX] == Spielvariablen.Feldtypen.geisterHaus || level[geist.posY][geist.posX] == Spielvariablen.Feldtypen.geistSpawn || level[geist.posY][geist.posX] == Spielvariablen.Feldtypen.tuer)zustand.aengstlich = false;\n geist.richtung = 5;\n\n\n if (this.beendet) {\n zustand.status = 3;\n Spielvariablen.Spielstart = false;\n }\n }", "function distancia_punto_punto(coord1,coord2)\n{\nreturn Math.sqrt(Math.pow(coord1[0]-coord2[0])+Math.pow(coord1[1]-coord2[1]));\n}", "function media(turma) {\n var soma = 0;\n var quantas_foram = 0;\n for (i = 0; i < turma.length; i++) {\n for (x = 0; x < 2; x++) {\n soma += turma[i].notas[x];\n quantas_foram += 1;\n }\n }\n var media = soma / quantas_foram /// Get the average value\n var devolve = 0;\n var diff = 21; /// set the min difference\n for (i = 0; i < turma.length; i++) {\n for (x = 0; x < 2; x++) {\n var closest = Math.abs(media - turma[i].notas[x]);\n if (closest < diff) {\n diff = closest; //// if closest value < difference devolve gets the value of the current grade\n devolve = turma[i].notas[x];\n }\n }\n }\n console.log(\"A média é: \", media);\n console.log(\"A nota mais proxima é: \", devolve);\n}", "function calculoangulochoquejug(ofjug, ofbola, tamjug, angulo) {\n let angulofinal = angulo;\n let aux;\n let poschoque = ofbola - ofjug;\n if ((angulo >= 90) && (angulo <= 270)) {\n if (poschoque == tamjug / 2) {\n angulofinal = 90;\n\n\n } else if (poschoque > tamjug / 2) {\n aux = (poschoque - (tamjug / 2)) / (tamjug / 2);\n aux = aux * 70;\n angulofinal = 10 + aux;\n\n } else if (poschoque < tamjug / 2) {\n aux = poschoque / (tamjug / 2);\n aux = aux * 70;\n angulofinal = 280 + aux;\n }\n }\n\n return angulofinal;\n }", "facteurPh(element,bacterie){\n\t\treturn (1 - ( Math.abs(bacterie.phIdeale - element.ph) / Math.abs(bacterie.phIdeale + element.ph) ))\n\t}", "function extendedEuclide(a,b) {\n\tvar phii=b;\n\tvar x=1 ; var xx=0;\n\tvar y=0; var yy=1;\t\t\t\n\twhile (b!=0) {\n\t\tvar q=Math.floor(a/b);\n\t\tvar o=store(a%b,b); a=o.v2 ; b=o.v1 ;\n\t\tvar o=store(x-q*xx,xx); x=o.v2 ; xx=o.v1 ;\n\t\tvar o=store(y-q*yy,yy); y=o.v2 ; yy=o.v1 ;\t\t\t\n\t}\n\tif (x<0) x+=phii;\n\treturn x;\n}", "function positionApresA(caractere){\n\treturn caractere.charCodeAt(0)-posA;\n}", "function high(x){\n const alphabet = 'abcdefghijklmnopqrstuvwxyz';\n let strArray = x.split(' '); \n let wordSums = {};\n let sortable = [];\n\n strArray.forEach(function(word){\n let sum = 0;\n word.split('').forEach(function(letter){\n sum += alphabet.indexOf(letter) + 1; \n })\n wordSums[word] = sum;\n })\n\n for (let word in wordSums) {\n sortable.push([word, wordSums[word]]);\n }\n\n sortable.sort(function(a, b) {\n return b[1] - a[1];\n });\n console.log(sortable);\n return sortable[0][0]; \n}", "calcFitness(){\n let d = dist(this.position.x, this.position.y, target.x, target.y);\n this.fitness = 1/d; //can square this \n }", "function obterAlturaMediana(){\n var alturas = [];\n for(var i=0; i<goldSaints.length; i++){\n alturas.push(goldSaints[i].alturaCm);\n }\n alturas.sort(function(a, b) {\n return a > b;\n });\n var mediana = -1;\n if(alturas.length % 2 === 0){ mediana = (alturas[alturas.length/2 - 1] + alturas[alturas.length/2])/2 }\n else{mediana = alturas[(alturas.length - 1) / 2];}\n return arredondamento(mediana/100);\n }", "distanceTo(p) {\n let x = (this.pos.x - p.translation[0]);\n let y = (this.pos.y - p.translation[1]);\n let euclDist = sqrt(pow(x, 2) + pow(y, 2));\n return euclDist;\n }", "function findIndexOfMaximumOfGain(liste) {\n var max = liste[0].gain;\n var index = 0;\n for(var i=1; i < liste.length; i++) {\n if(max != \"-E\" && liste[i].gain != \"-E\") {\n if(max > liste[i].gain) { // on utilise l'operateur > car c'est un nombre negative, alors le maximum de gain sera le plus petit\n max = liste[i].gain;\n index = i;\n }\n }\n if(max == \"-E\" && liste[i].gain != \"-E\") { // on change la valeur de max par le premier nombre différent de -E\n max = liste[i].gain;\n index = i;\n }\n }\n return index;\n }", "function ed(a){a=a.tc();for(var b=[],c=[],d=0;d<a.length;d++){var e=a[d].cA;e&&(e=e.call(a[d]))&&(e[2]?b.push(e):c.push(e))}c.sort(fd);b.sort(fd);return[c,b]}", "function dirReducMinimal(arr){\n \n let result = arr.reduce(function(accumulator, currentValue) {\n \n switch (currentValue) {\n case 'NORTH':\n accumulator[0] += 1;\n break;\n case 'SOUTH':\n accumulator[0] -= 1;\n break;\n case 'EAST':\n accumulator[1] += 1;\n break;\n default:\n accumulator[1] -= 1;\n }\n \n return accumulator;\n \n }, [0, 0]);\n\n\n if(result[0] > 0) {\n result[0] = Array(result[0]).fill('NORTH');\n } else {\n result[0] = Array(-1 * result[0]).fill('SOUTH');\n }\n \n if(result[1] > 0) {\n result[1] = Array(result[1]).fill('EAST');\n } else {\n result[1] = Array(-1 * result[1]).fill('WEST');\n }\n \n result = result[0].concat(result[1]);\n \n console.log(result);\n \n return result;\n}", "function levDist(s, t) {\n var d = []; //2d matrix\n\n // Step 1\n var n = s.length;\n var m = t.length;\n\n if (n == 0) return m;\n if (m == 0) return n;\n\n //Create an array of arrays in javascript (a descending loop is quicker)\n for (var i = n; i >= 0; i--) d[i] = [];\n\n // Step 2\n for (var i = n; i >= 0; i--) d[i][0] = i;\n for (var j = m; j >= 0; j--) d[0][j] = j;\n\n // Step 3\n for (var i = 1; i <= n; i++) {\n var s_i = s.charAt(i - 1);\n\n // Step 4\n for (var j = 1; j <= m; j++) {\n\n //Check the jagged ld total so far\n if (i == j && d[i][j] > 4) return n;\n\n var t_j = t.charAt(j - 1);\n var cost = (s_i == t_j) ? 0 : 1; // Step 5\n\n //Calculate the minimum\n var mi = d[i - 1][j] + 1;\n var b = d[i][j - 1] + 1;\n var c = d[i - 1][j - 1] + cost;\n\n if (b < mi) mi = b;\n if (c < mi) mi = c;\n\n d[i][j] = mi; // Step 6\n\n //Damerau transposition\n if (i > 1 && j > 1 && s_i == t.charAt(j - 2) && s.charAt(i - 2) == t_j) {\n d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);\n }\n }\n }\n // Step 7\n return d[n][m];\n}", "function dc3(cad){\n\t\n\t//construcción del alfabeto\n\tvar alf=[];\n\tfor(var i=0;i<cad.length;i++){\n\t\talf.push(cad.charCodeAt(i));\n\t}\n\t\n\t//console.log(alf)\n\talf=radixSort(alf);\n\t//console.log(alf)\n\t\n\tvar alfDict={};\n\t\tvar intCad=parseInt(cad)\n\t\t\n\t\tif(!(Number.isNaN(intCad))){\t\t\t\n\t\t\tfor(var i=0;i<alf.length;i++){\n\t\t\t\talfDict[String.fromCharCode(alf[i])]=parseInt(String.fromCharCode(alf[i]));\n\t\t\t} \t\n\t\t}\n\t\telse{\n\t\t\tvar index=0;\n\t\t\tvar lastChar=-1\n\t\t\tfor(var i=0; i<alf.length;i++){\n\t\t\t\tvar a=alf[i];\n\t\t\t\tif(a!=lastChar){\n\t\t\t\t\tindex+=1;\n\t\t\t\t\talfDict[String.fromCharCode(alf[i])]=index;\n\t\t\t\t}\n\t\t\t\tlastChar=a;\n\t\t\t}\n\t\t}\n\tconsole.log(alfDict);\n\tvar alfCad=[];\n\tfor(var i=0;i<cad.length;i++){\n\t\talfCad.push(alfDict[cad.charAt(i)]);\n\t}\n\talfCad.push(0);\n\tconsole.log(alfCad);\n\t\n\t\n\t//SAmple set\n\t\n\tvar b1=[];\n\tvar b2=[];\n\tvar b0=[];\n\tvar b12idx=[];\n\tvar idx=0;\n\t\n\tfor(var i=0; i<alfCad.length;i++){\n\t\tif(idx%3==1){\n\t\t\tb1.push([alfCad[i],idx]);\n\t\t}\n\t\telse if(idx%3==2){\n\t\t\tb2.push([alfCad[i],idx]);\n\t\t}\n\t\telse{\n\t\t\tb0.push([alfCad[i],idx]);\n\t\t}\n\t\tidx+=1;\n\t}\n\tvar b12=b1.concat(b2);\n\t\n\tconsole.log(b12);\n\t\n\tvar thriples=[];\n\tfor(var i=0;i<b12.length;i++){\n\t\tvar thriple=[];\n\t\tvar currentb=b12[i];\n\t\tconsole.log(currentb)\n\t\tif(currentb[1]!=(alfCad.length-1)){\n\t\t\t\tfor(var j=currentb[1];j<currentb[1]+3;j++){\n\t\t\t\t\tif(alfCad[j]!=undefined){\n\t\t\t\t\t\tthriple.push(alfCad[j]);\t\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tthriple.push(0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthriples.push([thriple,currentb[1]]);\n\t\t\t\tthriple=[];\n\t\t}\n\t}\n\tconsole.log(thriples);\n\t\n\tvar thriplesArray=[];\n\t\n\tfor(var i=0;i<thriples.length;i++){\n\t\tvar thrip='';\n\t\tvar currentT=thriples[i];\n\t\tfor (var j=0;j<currentT[0].length;j++){\n\t\t\tthrip+=currentT[0][j].toString();\n\t\t}\n\t\tthriplesArray.push([parseInt(thrip),currentT[1]]);\n\t}\n\t\n\t//console.log(thriplesArray);\n\t\n\tvar sortedThriples=radixSortTuple(thriplesArray);\n\tconsole.log(\"-----------sorted thriples-----------\")\n\tconsole.log(sortedThriples);\n\t\n\tvar tableRankThriple=[];\n\tvar lastThr=[-1,-1];\n\tvar currentRank=0;\n\tvar duplicates=false;\n\tvar b12IndexRank={};\n\t\n\tfor(var i=0;i<sortedThriples.length;i++){\n\t\tcurrentTh=sortedThriples[i];\n\t\tconsole.log(currentTh[0])\n\t\tif(currentTh[0]!=lastThr[0]){\n\t\t\tcurrentRank+=1;\n\t\t\ttableRankThriple.push([currentTh,currentRank]);\n\t\t\tb12IndexRank[currentTh[1].toString()]=currentRank;\n\t\t}\n\t\telse{\n\t\t\ttableRankThriple.push([currentTh,currentRank]);\n\t\t\tb12IndexRank[currentTh[1].toString()]=currentRank;\n\t\t\tduplicates=true;\n\t\t}\n\t\tlastThr=currentTh;\n\t}\n\tconsole.log(\"----------------tableRankThriple----------------\")\n\tconsole.log(tableRankThriple)\n\t\n b12IndexRank[cad.length.toString()]=0\n b12IndexRank[(cad.length+1).toString()]=0\n b12IndexRank[(cad.length+2).toString()]=0\n\t\n\t//console.log(tableRankThriple);\n\t\n\tvar b0Tuples21=[];\n\tconsole.log(duplicates);\n\tif(duplicates){\n\t\tnewArray=new Array(tableRankThriple.length+2);\n\t\t\n\t\tfor(var i=0;i<b12.length+2;i++){\n\t\t\tvar val=b12[i];\n\t\t\tif(val!=NaN && val!=undefined){\n\t\t\tnewArray[i]=b12IndexRank[b12[i][1].toString()];;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tnewArray[i]=0;\n\t\t\t}\n\t\t}\n\t\t\n\t\tconsole.log(newArray);\n\t\tvar str='';\n\t\tfor(var i=0;i<newArray.length;i++){\n\t\t\tstr+=newArray[i].toString();\n\t\t}\n\t\t\n\t\tvar recReturn=dc3(str);\n\t\tconsole.log(\"--------recurse returned-------\");\n\t\tconsole.log(recReturn);\n\t\t\n\t\tvar sortedB12=new Array(b12.length);\n\t\tfor(var i=1;i<recReturn.length;i++){\n\t\t\tb12Val=b12[recReturn[i]];\n\t\t\tsortedB12[i-1]=b12Val;\n\t\t}\n\t\t\n\t\tconsole.log(\"-------IndexRankOld-------\")\n\t\tconsole.log(b12IndexRank);\n\t\tfor(var i=0;i<sortedB12.length;i++){\n\t\t\tconsole.log(sortedB12[i][1].toString());\n\t\t\tb12IndexRank[sortedB12[i][1].toString()]=i+1;\n\t\t}\n\t\tconsole.log(\"-------updatedIndexRank------\")\n\t\tconsole.log(b12IndexRank);\n\t\t\n\t\t\n\t\tconsole.log(\"--------b0-------\");\n\t\tconsole.log(b0);\n\t\t\n\t\tfor(var j=0;j<b0.length;j++){\n\t\t\tvar intB=b12IndexRank[(b0[j][1]+1).toString()];\n\t\t\tvar stringB=intB.toString();\n\t\t\tconsole.log([intB,(b0[j][1]+1).toString()]);\n\t\t\tconsole.log(j)\n\t\t\tb0Tuples21.push([parseInt(((b0[j][0]).toString())+stringB),[ [b0[j][0],intB],b0[j][1] ]]);\n\t\t}\n\t\tconsole.log(\"------b0unsorted------\");\n\t\tconsole.log(b0Tuples21);\n\t\tb0Tuples21=radixSortTuple(b0Tuples21);\n\t\tconsole.log(\"------b0sorted------\");\n\t\tconsole.log(b0Tuples21);\n\t\t\n\t\tvar result=[];\n\t\tvar idx=0;\n\t\tvar idx2=0;\n\t\t\n\t\twhile(idx<b0Tuples21.length && idx2<sortedB12.length){\n\t\t\twhile(idx2<sortedB12.length && idx<b0Tuples21.length){\n\t\t\t\t//console.log(\"idx\",idx)\n\t\t\t\t//console.log(\"idx2\",idx2)\n\t\t\t\tvar currentB0=b0Tuples21[idx];\n\t\t\t\tvar idxB0=currentB0[1][1];\n\t\t\t\tvar currentB12=sortedB12[idx2];\n var idxB12=currentB12[1];\n\t\t\t\t//console.log(idxB12);\n\t\t\t\tif(idxB12%3==2){\n\t\t\t\t\tvar charB12=alfCad[idxB12];\n var charB0=alfCad[idxB0];\n\t\t\t\t\t//console.log(charB12);\n\t\t\t\t\t//console.log(charB0);\n if(charB0>charB12){\n result.push(idxB12);\n idx2=idx2+1;\n\t\t\t\t\t}\n else if(charB0<charB12){\n result.push(idxB0);\n idx=idx+1;\t\n\t\t\t\t\t}\n else{\n\t\t\t\t\t\tvar charB12P1=alfCad[idxB12+1];\n var charB0P1=alfCad[idxB0+1];\n if(charB0P1>charB12P1){\n result.push(idxB12);\n idx2=idx2+1\t;\n\t\t\t\t\t\t}\n else if(charB0P1<charB12P1){\n result.push(idxB0);\n idx=idx+1;\n\t\t\t\t\t\t}\n else{\n\t\t\t\t\t\t\tvar rankB0P2=b12IndexRank[(idxB0+2).toString()];\n var rankB12P2=b12IndexRank[(idxB12+2).toString()];\n\t\t\t\t\t\t\tconsole.log(idxB0+2);\n\t\t\t\t\t\t\tconsole.log(idxB12+2);\n if(rankB0P2>rankB12P2){\n result.push(idxB12);\n idx2=idx2+1;\n\t\t\t\t\t\t\t}\n else if(rankB0P2<rankB12P2){\n result.push(idxB0);\n idx=idx+1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} \n\t\t\t\t}\n\t\t\t\telse if(idxB12%3==1){\n\t\t\t\t\tvar charB12=alfCad[idxB12];\n var charB0=alfCad[idxB0];\n if(charB0>charB12){\n result.push(idxB12);\n idx2=idx2+1;\n\t\t\t\t\t}\n else if(charB0<charB12){\n result.push(idxB0);\n idx=idx+1;\n\t\t\t\t\t}\n else{\n\t\t\t\t\t\tvar rankB0P1=b12IndexRank[(idxB0+1).toString()];\n var rankB12P1=b12IndexRank[(idxB12+1).toString()];\n if(rankB0P1>rankB12P1){\n result.push(idxB12);\n idx2=idx2+1\t;\n\t\t\t\t\t\t}\n else if(rankB0P1<rankB12P1){\n result.push(idxB0);\n idx=idx+1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n \n\t\t\t}\n\t\t}\n\t\t\n\t\tif(idx>=tableRankThriple.length && idx2!=b0Tuples21.length){\n\t\t\tfor (var i=idx;i<b0Tuples21.length;i++){\n\t\t\t\tvar currentB0=b0Tuples21[i];\n var idxB0=currentB0[1][1];\n result.push(idxB0);\t\n\t\t\t}\n\t\t}\n else if(idx!=tableRankThriple.length && idx2>=b0Tuples21.length){\n\t\t\tfor(var i=idx2;i<tableRankThriple.length;i++){\n\t\t\t\tvar currentB12=tableRankThriple[i];\n var idxB12=currentB12[0][1];\n result.push(idxB12);\n\t\t\t}\n\t\t}\n return result; \n\t}\n\telse{\n\t\tb0.pop()\n\t\tfor(var i=0;i<b0.length;i++){\n\t\t\tvar intB=b12IndexRank[(b0[i][1]+1).toString()];\n\t\t\tvar stringB=intB.toString();\n\t\t\tb0Tuples21.push([parseInt((b0[i][0]).toString()+stringB),[[b0[i][0],intB],b0[i][1]]]);\n\t\t}\n\t\tb0Tuples21=radixSortTuple(b0Tuples21);\n\t\tconsole.log(b0Tuples21);\n\t\tvar result=[]\n var idx=0\n var idx2=0\n while(idx<b0Tuples21.length && idx2<tableRankThriple.length){\n\t\t\twhile(idx2<tableRankThriple.length && idx<b0Tuples21.length){\n\t\t\t\tvar currentB0=b0Tuples21[idx];\n var idxB0=currentB0[1][1];\n var currentB12=tableRankThriple[idx2];\n var idxB12=currentB12[0][1];\n if(idxB12%3==2){\n\t\t\t\t\tvar charB12=alfCad[idxB12];\n var charB0=alfCad[idxB0];\n if(charB0>charB12){\n result.push(idxB12);\n idx2=idx2+1;\n\t\t\t\t\t}\n else if(charB0<charB12){\n result.push(idxB0);\n idx=idx+1;\t\n\t\t\t\t\t}\n else{\n\t\t\t\t\t\tvar charB12P1=alfCad[idxB12+1];\n var charB0P1=alfCad[idxB0+1];\n if(charB0P1>charB12P1){\n result.push(idxB12);\n idx2=idx2+1;\t\n\t\t\t\t\t\t}\n else if(charB0P1<charB12P1){\n result.push(idxB0)\n idx=idx+1\t\n\t\t\t\t\t\t}\n else{\n var rankB0P2=b12IndexRank[(idxB0+2).toString()];\n var rankB12P2=b12IndexRank[(idxB12+2).toString()];\n if(rankB0P2>rankB12P2){\n result.push(idxB12);\n idx2=idx2+1;\n\t\t\t\t\t\t\t}\n else if(rankB0P2<rankB12P2){\n result.push(idxB0);\n idx=idx+1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n \n else if(idxB12%3==1){\n\t\t\t\t\tvar currentB12=tableRankThriple[idx2];\n var idxB12=currentB12[0][1];\n var charB12=alfCad[idxB12];\n var charB0=alfCad[idxB0];\n if(charB0>charB12){\n result.push(idxB12);\n idx2=idx2+1;\n\t\t\t\t\t}\n else if(charB0<charB12){\n result.push(idxB0);\n idx=idx+1;\t\n\t\t\t\t\t}\n else{\n\t\t\t\t\t\tvar rankB0P1=b12IndexRank[(idxB0+1).toString()];\n var rankB12P1=b12IndexRank[(idxB12+1).toString()];\n if(rankB0P1>rankB12P1){\n result.push(idxB12);\n idx2=idx2+1;\t\n\t\t\t\t\t\t}\n else if(rankB0P1<rankB12P1){\n result.push(idxB0);\n idx=idx+1;\t\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n \n\t\t\t}\n\t\t}\n\t\tif(idx>=tableRankThriple.length && idx2!=b0Tuples21.length){\n\t\t\tfor (var i=idx;i<b0Tuples21.length;i++){\n\t\t\t\tvar currentB0=b0Tuples21[i];\n var idxB0=currentB0[1][1];\n result.push(idxB0);\t\n\t\t\t}\n\t\t}\n else if(idx!=tableRankThriple.length && idx2>=b0Tuples21.length){\n\t\t\tfor(var i=idx2;i<tableRankThriple.length;i++){\n\t\t\t\tvar currentB12=tableRankThriple[i];\n var idxB12=currentB12[0][1];\n result.push(idxB12);\n\t\t\t}\n\t\t}\n\t\tconsole.log(\"---------result---------------\")\n\t\tconsole.log(result)\n return result; \n\t}\n}", "getDenomination(value, override) {\n let thisValue = value; // Don't mutate params\n let result = null;\n // Check if there are user created overrides\n thisValue = this.getOverrides(override, thisValue);\n // Find best match for each value\n DENOMINATIONS.forEach((denomination) => {\n if (thisValue >= denomination.value && !result) {\n result = DENOMINATIONS.find(res => res.value === denomination.value);\n }\n });\n return result;\n }", "function combToNumber(val,en)\n{\n var lastVal=0;\n var tot=0;\n var manEn=en-1;\n var manKay=val.length;\n val = deArray(val);\n\nfor (var cA=0;cA<val.length;cA++)\n {\n var dif = val[cA]-lastVal;\n lastVal=val[cA]+1;\n var levTot=0;\n manKay--;\n if (manKay==0)\n {\n levTot=dif\n }\n else{\n for (var cB=0;cB<dif;cB++)\n {\n// manEn--;\n levTot+=(new AFastCombinatorial(manEn,manKay)).prod\n manEn--;\n }\n }\n manEn--;\n tot+=levTot;\n }\n return tot;\n}", "function decidirGanador() {\n\n var arrayPosiciones = [];\n var indice;\n\n for (var i = 0; i < jugadores.length; i++) {\n mejorCombinacionPorJugador[i] = combinacionCartasGenerales(i);\n\n console.log(\"Mejor combinacion jugador \" + i + \" es \" + mejorCombinacionPorJugador[i]);\n\n if (mejorCombinacionPorJugador[i] > combinacionGanadoraActual) {\n combinacionGanadoraActual = mejorCombinacionPorJugador[i];\n }\n jugadores[i].manoGanadora = mejorCombinacionPorJugador[i];\n }\n\n indice = mejorCombinacionPorJugador.indexOf(combinacionGanadoraActual);\n while (indice !== -1) {\n arrayPosiciones.push(indice);\n indice = mejorCombinacionPorJugador.indexOf(combinacionGanadoraActual, indice + 1);\n }\n\n\n if (arrayPosiciones.length === 1) {\n return arrayPosiciones;\n } else if (arrayPosiciones.length > 1) {\n return decidirGanadorEmpate(arrayPosiciones);\n }\n}", "function ordena(num) {\n // teste++;\n // if (teste > 5) {\n // return console.log(\"a\");\n // }\n\n var verif = false;\n for (var i = 0; i < num.length - 1; i++) {\n\n if (parseInt(num[i]) < parseInt(num[i + 1])) {\n verif = true;\n var extra = num[i];\n num[i] = num[i + 1];\n num[i + 1] = extra;\n\n\n }\n\n }\n if (verif == true) {\n return ordena(num)\n } else {\n return num;\n }\n\n}", "round(coord) {\n const node = this.tree.add(coord)\n\n const prevNode = this.tree.prev(node)\n if (prevNode !== null && cmp(node.key, prevNode.key) === 0) {\n this.tree.remove(coord)\n return prevNode.key\n }\n\n const nextNode = this.tree.next(node)\n if (nextNode !== null && cmp(node.key, nextNode.key) === 0) {\n this.tree.remove(coord)\n return nextNode.key\n }\n\n return coord\n }", "function oe(e,t){var a=e.lines.length-t.lines.length;if(0!=a)return a;var n=e.find(),r=t.find(),f=P(n.from,r.from)||re(e)-re(t);if(f)return-f;var o=P(n.to,r.to)||fe(e)-fe(t);return o||t.id-e.id}", "function MenorAMayor(elem1, elem2){\n //return se encarga de finalizar la operación\n return elem1 - elem2;\n}", "function ArithGeo(arr) {\n\tlet addAmount = arr[1] - arr[0];\n\tlet multiplyRatio = arr[1] / arr[0];\n\tlet isArithmetic = true;\n\tlet isGeometric = true;\n\t// console.log(addAmount);\n\t// console.log(multiplyRatio);\n\tfor (let i = 1; i < arr.length; i++) {\n\t\tif (arr[i] - arr[i - 1] != addAmount) {\n\t\t\tisArithmetic = false;\n\t\t}\n\t}\n\n\tfor (let j = 1; j < arr.length; j++) {\n\t\tif (arr[j] / arr[j - 1] != multiplyRatio) {\n\t\t\tisGeometric = false;\n\t\t}\n\t}\n\tif (isArithmetic) {\n\t\treturn 'Arithmetic';\n\t} else if (isGeometric) {\n\t\treturn 'Geometric';\n\t} else {\n\t\treturn -1;\n\t}\n}", "function obli_ecli(njd){\n\n // calcola l'obliquità dell'eclittica.\n // per l'equinozio della data.\n // T= numero di secoli giuliani dallo 0.5 gennaio 1900.\n\n var T=(njd-2415020.0)/36525;\n\n var obli_eclittica=23.452294-0.0130125*T-0.00000164*T*T+0.000000503*T*T*T;\n\nreturn obli_eclittica; //obliquità in gradi\n\n}", "maxDegree() {\n\t\tlet d = 0;\n\t\tfor (let u = 1; u <= this.n; u++) d = Math.max(d, this.degree(u));\n\t\treturn d;\n\t}", "function pos_luna(njd){\n\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) ottobre 2010.\n // funzione per il calcolo della posizione della Luna.\n // njd= numero dei giorni giuliani per il T.U. di Greenwich.\n // coordinate equatoriali geocentriche per l'equinozio della data.\n\nvar T=(njd-2415020.0)/36525;\n\nvar L1=270.434164+481267.8831*T-0.001133*T*T+0.0000019*T*T*T; // longitudine media.\n\nvar M=358.475833+35999.04975*T-0.000150*T*T-0.0000033*T+T*T; // anomalia media del Sole\n\nvar M1=296.104608+477198.8491*T+0.009192*T*T+0.0000144*T*T*T; // anomalia media della Luna\n\nvar D=350.737486+445267.1142*T-0.001436*T*T+0.0000019*T*T*T; // elongazione media della Luna\n\nvar F=11.250889+483202.0251*T-0.003211*T*T-0.0000003*T*T*T; // distanza media della Luna dal suo nodo ascendente.\n\nvar N=259.183275-1934.1420*T+0.002078*T*T+0.0000022*T*T*T; // longitudine media del nodo ascendente della Luna.\n\n// termini additivi di correzione.\n\nvar Delta=0.003964*Math.sin(Rad(346.560+132.870*T-0.0091731*T*T));\n\nL1=L1+0.000233*Math.sin(Rad(51.2+20.2*T))+Delta;\n M= M-0.001778*Math.sin(Rad(51.2+20.2*T));\nM1=M1+0.000817*Math.sin(Rad(51.2+20.2*T))+Delta;\n D= D+0.002011*Math.sin(Rad(51.2+20.2*T))+Delta;\n\nL1=L1+0.001964*Math.sin(Rad(N));\nM1=M1+0.002541*Math.sin(Rad(N));\n D= D+0.001964*Math.sin(Rad(N));\n F= F-0.024691*Math.sin(Rad(N));\n F= F-0.004328*Math.sin(Rad(N+275.05-2.30*T));\n F= F+Delta;\n\nvar e=1-0.002495*T-0.00000752*T*T;\n\n// Calcola la Longitudine ecclittica.\n\nvar Long=L1+6.288750*Math.sin(Rad(M1))\n +1.274018*Math.sin(Rad(2*D-M1))\n +0.658309*Math.sin(Rad(2*D))\n +0.213616*Math.sin(Rad(2*M1))\n -0.185596*Math.sin(Rad(M))*e\n -0.114336*Math.sin(Rad(2*F))\n +0.058793*Math.sin(Rad(2*D-2*M1))\n +0.057212*Math.sin(Rad(2*D-M-M1))*e\n +0.053320*Math.sin(Rad(2*D+M1))\n +0.045874*Math.sin(Rad(2*D-M))*e\n +0.041024*Math.sin(Rad(M1-M))*e\n -0.034718*Math.sin(Rad(D))\n -0.030465*Math.sin(Rad(M+M1))*e\n +0.015326*Math.sin(Rad(2*D-2*F))\n -0.012528*Math.sin(Rad(2*F+M1))\n -0.010980*Math.sin(Rad(2*F-M1))\n +0.010674*Math.sin(Rad(4*D-M1))\n +0.010034*Math.sin(Rad(3*M1))\n +0.008548*Math.sin(Rad(4*D-2*M1))\n -0.007910*Math.sin(Rad(M-M1+2*D))*e\n -0.006783*Math.sin(Rad(2*D+M))*e\n +0.005162*Math.sin(Rad(M1-D))\n -0.005000*Math.sin(Rad(M+D))*e\n +0.004049*Math.sin(Rad(M1-M+2*D))*e\n +0.003996*Math.sin(Rad(2*M1+2*D))\n +0.003862*Math.sin(Rad(4*D))\n +0.003665*Math.sin(Rad(2*D-3*M1))\n +0.002695*Math.sin(Rad(2*M1-M))*e\n +0.002602*Math.sin(Rad(M1-2*F-2*D))\n +0.002396*Math.sin(Rad(2*D-M-2*M1))*e\n -0.002349*Math.sin(Rad(M1+D))\n +0.002249*Math.sin(Rad(2*D-2*M))*e*e\n -0.002125*Math.sin(Rad(2*M1+M))*e \n -0.002079*Math.sin(Rad(2*M))*e*e \n +0.002059*Math.sin(Rad(2*D-M1-2*M))*e*e\n -0.001773*Math.sin(Rad(M1+2*D-2*F))\n -0.001595*Math.sin(Rad(2*F+2*D))\n +0.001220*Math.sin(Rad(4*D-M-M1))*e\n -0.001110*Math.sin(Rad(2*M1+2*F))\n +0.000892*Math.sin(Rad(M1-3*D))\n -0.000811*Math.sin(Rad(M+M1+2*D))*e\n +0.000761*Math.sin(Rad(4*D-M-2*M1))*e\n +0.000717*Math.sin(Rad(M1-2*M))*e*e\n +0.000704*Math.sin(Rad(M1-2*M-2*D))*e*e\n +0.000693*Math.sin(Rad(M-2*M1+2*D))*e\n +0.000598*Math.sin(Rad(2*D-M-2*F))*e\n +0.000550*Math.sin(Rad(M1+4*D))\n +0.000538*Math.sin(Rad(4*M1))\n +0.000521*Math.sin(Rad(4*D-M))*e\n +0.000486*Math.sin(Rad(2*M1-D));\n \n// Calcolo della Latitudine ecclittica.\n\nvar Beta= 5.128189*Math.sin(Rad(F))\n +0.280606*Math.sin(Rad(M1+F))\n +0.277693*Math.sin(Rad(M1-F))\n +0.173238*Math.sin(Rad(2*D-F))\n +0.055413*Math.sin(Rad(2*D+F-M1))\n +0.046272*Math.sin(Rad(2*D-F-M1))\n +0.032573*Math.sin(Rad(2*D+F))\n +0.017198*Math.sin(Rad(2*M1+F))\n +0.009267*Math.sin(Rad(2*D+M1-F))\n +0.008823*Math.sin(Rad(2*M1-F))\n +0.008247*Math.sin(Rad(2*D-M-F))*e\n +0.004323*Math.sin(Rad(2*D-F-2*M1))\n +0.004200*Math.sin(Rad(2*D+F+M1))\n +0.003372*Math.sin(Rad(F-M-2*D))*e\n +0.002472*Math.sin(Rad(2*D+F-M-M1))*e\n +0.002222*Math.sin(Rad(2*D+F-M))*e\n +0.002072*Math.sin(Rad(2*D-F-M-M1))*e\n +0.001877*Math.sin(Rad(F-M+M1))*e\n +0.001828*Math.sin(Rad(4*D-F-M1))\n -0.001803*Math.sin(Rad(F+M))*e\n -0.001750*Math.sin(Rad(3*F))\n +0.001570*Math.sin(Rad(M1-M-F))*e\n -0.001487*Math.sin(Rad(F+D))\n -0.001481*Math.sin(Rad(F+M+M1))*e\n +0.001417*Math.sin(Rad(F-M-M1))*e\n +0.001350*Math.sin(Rad(F-M))*e\n +0.001330*Math.sin(Rad(F-D))\n +0.001106*Math.sin(Rad(F+3*M1))\n +0.001020*Math.sin(Rad(4*D-F))\n +0.000833*Math.sin(Rad(F+4*D-M1))\n +0.000781*Math.sin(Rad(M1-3*F))\n +0.000670*Math.sin(Rad(F+4*D-2*M1))\n +0.000606*Math.sin(Rad(2*D-3*F))\n +0.000597*Math.sin(Rad(2*D+2*M1-F))\n +0.000492*Math.sin(Rad(2*D+M1-M-F))*e\n +0.000450*Math.sin(Rad(2*M1-F-2*D))\n +0.000439*Math.sin(Rad(3*M1-F))\n +0.000423*Math.sin(Rad(F+2*D+2*M1))\n +0.000422*Math.sin(Rad(2*D-F-3*M1))\n -0.000367*Math.sin(Rad(M+F+2*D-M1))*e\n -0.000353*Math.sin(Rad(M+F+2*D))*e\n +0.000331*Math.sin(Rad(F+4*D))\n +0.000317*Math.sin(Rad(2*D+F-M+M1))*e\n +0.000306*Math.sin(Rad(2*D-2*M-F))*e*e\n -0.000283*Math.sin(Rad(M1+3*F));\n\n var omega1=0.0004664*Math.cos(Rad(N));\n var omega2=0.0000754*Math.cos(Rad(N+275.05-2.30));\n\n var Lat=Beta*(1-omega1-omega2); // latitudine ecclittica.\n\n // Calcolo della parallasse.\n\n var parallasse=0.950724\n +0.051818*Math.cos(Rad(M1))\n +0.009531*Math.cos(Rad(2*D-M1))\n +0.007843*Math.cos(Rad(2*D))\n +0.002824*Math.cos(Rad(2*M1))\n +0.000857*Math.cos(Rad(2*D+M1))\n +0.000533*Math.cos(Rad(2*D-M))*e\n +0.000401*Math.cos(Rad(2*D-M-M1))*e\n +0.000320*Math.cos(Rad(M1-M))*e\n -0.000271*Math.cos(Rad(D))\n -0.000264*Math.cos(Rad(M1+M))*e\n -0.000198*Math.cos(Rad(2*F-M1))\n +0.000173*Math.cos(Rad(3*M1))\n +0.000167*Math.cos(Rad(4*D-M1))\n -0.000111*Math.cos(Rad(M))*e\n +0.000103*Math.cos(Rad(4*D-2*M1))\n -0.000084*Math.cos(Rad(2*M1-2*D))\n -0.000083*Math.cos(Rad(2*D+M))*e\n +0.000079*Math.cos(Rad(2*D+2*M1))\n +0.000072*Math.cos(Rad(4*D))\n +0.000064*Math.cos(Rad(2*D-M+M1))*e\n -0.000063*Math.cos(Rad(2*D+M-M1))*e\n +0.000041*Math.cos(Rad(M+D))*e\n +0.000035*Math.cos(Rad(2*M1-M))*e\n -0.000033*Math.cos(Rad(3*M1-2*D))\n -0.000030*Math.cos(Rad(M1+D))\n -0.000029*Math.cos(Rad(2*F-2*D))\n -0.000029*Math.cos(Rad(2*M1+M))*e\n +0.000026*Math.cos(Rad(2*D-2*M))*e*e\n -0.000023*Math.cos(Rad(2*F-2*D+M1))\n +0.000019*Math.cos(Rad(4*D-M-M1))*e;\n\n Long=gradi_360(Long); // La longitudine all'interno dell'intervallo 0-360.\n\n var dati_luna=trasf_ecli_equa(njd,Long,Lat); // calcola le coordinate equatoriali geocentriche.\n\n // dati del Sole.\n\n var dat_sole=pos_sole(njd); // calcola la longitudine del sole\n var Long_sole=dat_sole[2]; // longitudine vera del sole.\n \n // CALCOLO DELLA FASE E DELL'ELONGAZIONE\n\n var Elongazione=elong(dati_luna[0],dati_luna[1],dat_sole[0],dat_sole[1]); // elongazione in gradi dal Sole.\n\n var Fase_luna=0.5*(1-Math.cos(Rad(Elongazione))); // FASE\n \n var dist_luna=6378.14/Math.sin(Rad(parallasse));\n dist_luna=dist_luna.toFixed(0); // Distanza in Km.\n\n var dim_app=Math.atan(3476.2/dist_luna); \n dim_app=Rda(dim_app)*3600;\n dim_app=dim_app.toFixed(2); // Diametro apparente in secondi d'arco.\n\n // elenco delle variabili restituite dalla funzione [pos_luna].\n\n // dati_luna[0]= ascensione retta già in ore decimali (diviso per 15).\n // dati_luna[1]= declinazione in gradi sessadecimali.\n dati_luna[2]= Long; // in gradi sessadecimali.\n dati_luna[3]= Fase_luna; // fase lunare.\n dati_luna[4]= Elongazione; // elongazione in gradi sessadecimali.\n dati_luna[5]= parallasse; // parallasse della Luna in gradi. \n dati_luna[6]= dim_app; // diametro apparente in secondi d'arco.\n dati_luna[7]= dist_luna; // distanza della Luna in Km. \n\n return dati_luna;\n\n}", "closestCommonAncestor(vampire) {\n let vamp1 = this;\n let vamp2 = vampire; \n// the distance from og is not the same, run the function until they are the same distance from the og. At that point, if they are the same person, we know thats the ancestor. If they are not the same person, then we can creep up the ladder until we find one. \nconst getclose = function(user1, user2){\n if (user1.numberOfVampiresFromOriginal > user2.numberOfVampiresFromOriginal){\n user1 = user1.creator; \n getclose(user1, user2);\n } else if (user2.numberOfVampiresFromOriginal > user1.numberOfVampiresFromOriginal){\n user2 = user2.creator;\n getclose(user1, user2);\n } else {\n vamp1 = user1;\n vamp2 = user2; \n }\n };\n getclose(vamp1, vamp2);\n\n const anscestor = function(user1, user2) {\n if (vamp1 === vamp2){\n return vamp1; \n } else if (vamp1.creator === vamp2.creator){\n return vamp1.creator;\n } else if (!vamp1.creator || !vamp2.creator){\n if (!vamp1.creator){\n return vamp1;\n } else {\n return vamp2;\n }\n } else {\n vamp1 = vamp1.creator; \n vamp2 = vamp1.creator;\n return anscestor(vamp1, vamp2);\n }\n };\n return anscestor(vamp1, vamp2)\n}", "function volver_estacionamiento(coord_punto,adyacentes_actual,grafo,grafo_posiciones)\n{\nvar id=nodo_distancia_menor(coord_punto,grafo_posiciones);\n\treturn obtener_ruta(1,[id],adyacentes_actual,grafo_pi(grafo,grafo_posiciones,coord_punto));\n}", "function tentukanDeretGeometri(arr) {\n var hasilBagiDrt = arr[1] / arr[0];\n var deretGeometri = true;\n for(var i = 1; i < arr.length -1; i++) {\n var bagiTmp = arr[i+1]/arr[i];\n if(bagiTmp !== hasilBagiDrt) {\n deretGeometri = false;\n }\n }\n return deretGeometri;\n}", "size() {\n // return position minus deposition\n return this.position - this.deposition;\n }", "function getAIMovement() {\n /**\n * In het geval de ai uit het scherm wil lopen, gaat hij nu aan de tegenovergestelde kant weer verder\n */\n ai_position_x += ai_movement_x;\n ai_position_y += ai_movement_y;\n\n //tilecount - 1, moet omdat hij anders aan de zijkant terecht komt\n if (ai_position_x < 0) {\n ai_position_x = tilecount_x - 1;\n }\n if (ai_position_x > tilecount_x - 1) {\n ai_position_x = 0;\n }\n if (ai_position_y < 0) {\n ai_position_y = tilecount_y - 1;\n }\n if (ai_position_y > tilecount_y - 1) {\n ai_position_y = 0;\n }\n }", "overpressureToDistance(overPressurekPa)\n{\n const a1 = -0.214362789151;\n const b1 = 1.35034249993;\n const c01 = 2.78076916577;\n const c11 = -1.6958988741;\n const c21 = -0.154159376846;\n const c31 = 0.514060730593;\n const c41 = 0.0988554365274;\n const c51 = -0.293912623038;\n const c61 = -0.0268112345019;\n const c71 = 0.109097496421;\n const c81 = 0.001628467556311;\n const c91 = -0.0214631030242;\n const c101 = 0.0001456723382;\n const c111 = 0.00167847752266;\n \n //Tolerancia del cálculo\n const tolerance = 0.001;\n\n //Valor de inicio del calculo de dsitancia x a la de sobrepresion overPressureTNT;\n let xTNT = 0;\n \n //Presion inicial para el cálculo este numero es el maximo reportado por EPA en kPA\n var pres = 33000;\n \n //Calculo de Masa equivalente de TNT\n let masaEQTNT = (this.fe*this.hCombKJKG*this.mass)/DHCTNT;\n \n //Calculo de la distancia por iteracion\n for (xTNT = 1; pres > overPressurekPa; xTNT = xTNT + tolerance)\n {\n //Distancia Escalada (m/kg^1/3)\n const z = xTNT/Math.pow(masaEQTNT, 1.0/3.0);\n \n let ablog = a1+b1*Math.log10(z);\n let c = c01+c11*ablog+c21*Math.pow(ablog, 2)+c31*Math.pow(ablog, 3)+c41*Math.pow(ablog, 4)+c51*Math.pow(ablog, 5)+c61*Math.pow(ablog, 6)+c71*Math.pow(ablog, 7)+c81*Math.pow(ablog, 8)+c91*Math.pow(ablog, 9)+c101*Math.pow(ablog, 10)+c111*Math.pow(ablog, 11);\n pres = Math.pow(10, c);\n }\n return xTNT;\n\n}", "function rougher(pts) {\n var mids = [];\n var diffs = [];\n var npts = [pts[0]];\n for (var i = 1; i < pts.length; i++) {\n var last = pts[i-1];\n var pt = pts[i];\n var diff = pt.y - last.y; \n var mp = midPt(pt,last);\n var my = last.y + diff / 2;\n //mids.push(mp);\n\n //diffs.push(diff);\n //var xd = (pt.x - last.x) / 3;\n \n var a = newPt(last.x +1, my + diff/20);\n var b = newPt(last.x + 2, my - diff/20);\n npts.push(a);\n npts.push(b);\n npts.push(newPt(pt.x,pt.y));\n }\n \n return npts;\n}", "function calcularDerechoGym (genero, edad){\n if(genero === 'M'){\n if (edad <10){\n return 0;\n } \n else if((edad >= 10) && (edad<20)){\n return 20000;\n }\n else if((edad >= 20) && (edad<40)){\n return 15000;\n }\n else if (genero === 'F'){\n \n }\n \n }\n \n }", "function getKey(p) {\n const arr = [\n {\n key: '180',\n distance: 180 - p[1]\n },\n {\n key: '-180',\n distance: Math.abs(-180 - p[1])\n },\n {\n key: '0',\n distance: Math.abs(p[1])\n }\n ];\n return arr.sort(comparator)[0].key;\n}", "function dehash(resultat, taille) {\n\t// Stock le modulo\n\tlet modulo;\n\n\t// La réponse à trouver\n\tlet mystere = \"\";\n\n\t// On va faire taille fois l'inverse de ce qui est fait\n\tfor (let i = 0; i < taille; i++) {\n\t\t// Modulo 37 pour connaitre le reste\n\t\tmodulo = resultat % 37;\n\t\t\n\t\t// Le reste correspond à indexOf sur lettresPossibles, on concatène la lettre trouvée\n\t\tmystere += lettresPossibles.charAt(modulo);\n\n\t\t// On soustrait le modulo et on divise par 37 pour remonter la boucle\n\t\tresultat = (resultat - modulo) / 37;\n\t}\n\n\t// Le résultat est inversé, on doit le remettre à l'endroit\n\tmystere = mystere.split(\"\").reverse().join(\"\");\n\n\treturn mystere;\n}", "getAcc(other) {\n var force = this.getForce(other);\n var mag = force / this.mass;\n\n var dir = p5.Vector.sub(this.pos, other.pos);\n dir.normalize();\n\n var a = dir.mult(mag);\n return a;\n }", "function calculaIdade(data,dataHoje) {\n\tvar x = data.split(\"/\");\n\tvar h = dataHoje.split(\"/\");\n\tvar anosProvisorio = h[2] - x[2];\n\n\tif(h[1] < x[1]) {\n\t\tanosProvisorio -= 1;\n\t}else if(h[1] == x[1]) {\n\t\tif(h[0] < x[0]) {\n\t\t\tanosProvisorio -= 1;\n\t\t};\n\t};\n\t\n\treturn anosProvisorio;\n}", "function minglemerge(Av,Ax,s,e,b){\n \n if(e-s>mergcach.length) mergcach=new Array(ntain((e-s)*3,0,Av.length))\n for(var h=0,j=s,ee=e-s;h<ee; ) mergcach[h++]=Ax[j++] \n \n var wrpos=e-1, clonx=e-s-1, hipt=s-1, bhipt=hipt, lep=1 \n\n ///skip to first insert \n while( (clonx>=0) && !compar( Av[Ax[hipt]],Av[mergcach[clonx]] ) ) // is not jdest\n { clonx--,wrpos-- } \n \n while(clonx>=0)// ix of copyel to place\n {\n bhipt=hipt\n \n while( (hipt>=b) && compar( Av[Ax[hipt]],Av[mergcach[clonx]] ) ) // is not jdest\n { hipt-- } \n \n for(var c=bhipt,d=c+wrpos-bhipt; c>hipt; ){\n Ax[d--]=Ax[c--] \n }\n \n wrpos-=(bhipt-hipt)\n Ax[wrpos]=mergcach[clonx]\n wrpos--,clonx--\n \n }//while\n\n return wrpos<b? s-wrpos+1 : s-wrpos //merge underflowed\n //returns ... dunnonow...\n }", "function gramajeRef(codigoArticulo){\n if(promedios[codigoArticulo].gramajes.promedioDown.lotes > promedios[codigoArticulo].gramajes.promedioUp.lotes){\n return promedios[codigoArticulo].gramajes.promedioDown;\n }else{\n return promedios[codigoArticulo].gramajes.promedioUp;\n }\n}", "function findedge (l, p1 , p2) {\n var m = (p1[1] - p2[1])/(p1[0] - p2[0]);\n var b = p1[1] - m*p1[0];\n var y = l + p1[1];\n \n return [(y - b)/m, y];\n }", "Ij_chords(){\n let A_chord = this.Atc + this.Abc\n let De = this.Dj - this.Ytc - this.Ybc\n\n return this.Atc*this.Abc*Math.pow(De,2)/A_chord + this.Itc + this.Ibc\n }", "function trasf_ecli_equa(njd,long,lat){\n\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) dicembre 2009\n // funzione per trasformare le coordinate eclittiche in equatoriali.\n // long e lat: coordinate ecclittiche dell'astro in gradi sessadecimali.\n // njd=numero del giorno giuliano.\n\nvar obli_eclittica=obli_ecli(njd);\n obli_eclittica=obli_eclittica/180*Math.PI; \n \nlong=long/180*Math.PI;\n lat= lat/180*Math.PI;\n\nvar y=Math.sin(long)*Math.cos(obli_eclittica)-Math.tan(lat)*Math.sin(obli_eclittica);\nvar x=Math.cos(long);\n\nvar ascensione_retta=quadrante(y,x)/15;\n\nvar declinazione=Math.sin(lat)*Math.cos(obli_eclittica)+Math.cos(lat)*Math.sin(obli_eclittica)*Math.sin(long);\n declinazione=Math.asin(declinazione);\n declinazione=declinazione*180/Math.PI;\n\nvar coord_equa= new Array(ascensione_retta,declinazione) ; // restituisce le variabili AR e DEC .\n\nreturn coord_equa;\n\n}", "previousClue(number, direction) {\n let last, result = 0;\n for (let i in this.puzzle[direction]) {\n last = i;\n if (i < number && i > result) {\n result = parseInt(i);\n }\n if (i >= number && result !== 0) {\n return this.puzzle[direction][result][this.puzzle[direction][result].length - 1];\n }\n }\n return this.puzzle[direction][last][this.puzzle[direction][last].length - 1];\n\n }", "getUtoTmapping( u, distance ) {\n\n\t\t\tconst arcLengths = this.getLengths();\n\n\t\t\tlet i = 0;\n\t\t\tconst il = arcLengths.length;\n\n\t\t\tlet targetArcLength; // The targeted u distance value to get\n\n\t\t\tif ( distance ) {\n\n\t\t\t\ttargetArcLength = distance;\n\n\t\t\t} else {\n\n\t\t\t\ttargetArcLength = u * arcLengths[ il - 1 ];\n\n\t\t\t}\n\n\t\t\t// binary search for the index with largest value smaller than target u distance\n\n\t\t\tlet low = 0, high = il - 1, comparison;\n\n\t\t\twhile ( low <= high ) {\n\n\t\t\t\ti = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats\n\n\t\t\t\tcomparison = arcLengths[ i ] - targetArcLength;\n\n\t\t\t\tif ( comparison < 0 ) {\n\n\t\t\t\t\tlow = i + 1;\n\n\t\t\t\t} else if ( comparison > 0 ) {\n\n\t\t\t\t\thigh = i - 1;\n\n\t\t\t\t} else {\n\n\t\t\t\t\thigh = i;\n\t\t\t\t\tbreak;\n\n\t\t\t\t\t// DONE\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\ti = high;\n\n\t\t\tif ( arcLengths[ i ] === targetArcLength ) {\n\n\t\t\t\treturn i / ( il - 1 );\n\n\t\t\t}\n\n\t\t\t// we could get finer grain at lengths, or use simple interpolation between two points\n\n\t\t\tconst lengthBefore = arcLengths[ i ];\n\t\t\tconst lengthAfter = arcLengths[ i + 1 ];\n\n\t\t\tconst segmentLength = lengthAfter - lengthBefore;\n\n\t\t\t// determine where we are between the 'before' and 'after' points\n\n\t\t\tconst segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;\n\n\t\t\t// add that fractional amount to t\n\n\t\t\tconst t = ( i + segmentFraction ) / ( il - 1 );\n\n\t\t\treturn t;\n\n\t\t}", "function CalcFromCurrentToEndWeight_hh(){ // FromCurrentToEndWeight_hh[] // Calc h for all nodes\n\t\tvar Target = GetXandYvalues(targetLeaf);\n\t\tvar TargetX = Target[0];\n\t\tvar TargetY = Target[1];\n\tfor(var a : int = 0; a < LeavesActiveInSceneInt.Length; a++){\n\t\tvar curr = LeavesActiveInSceneInt[a];\n\t\tvar cur = GetXandYvalues(curr);\n\t\tvar curX = cur[0];\n\t\tvar curY = cur[1];\n\t\tFromCurrentToEndWeight_hh[a] = Mathf.Sqrt(((TargetX-curX)*(TargetX-curX))+((TargetY-curY)*(TargetY-curY)));\n\t\t}\n}", "function _GEA(a, l, h, y) {\n\t var i = h + 1;\n\t while (l <= h) {\n\t var m = l + h >>> 1,\n\t x = a[m];\n\t if (x >= y) {\n\t i = m;\n\t h = m - 1;\n\t } else {\n\t l = m + 1;\n\t }\n\t }\n\t return i;\n\t}", "function z(e,t){return Math.max(e.first,Math.min(t,e.first+e.size-1))}", "function findCoordination(input) {\n\t\t// easy calculation, no need to write code \n}", "extractMax(){\r\n if(this.values.length === 1) return this.values.pop();\r\n const oldRoot = this.values[0];\r\n this.values[0] = this.values[this.values.length-1];\r\n this.values.pop();\r\n let idx = 0;\r\n let child1 = (2*idx) + 1;\r\n let child2 = (2*idx) + 2;\r\n\r\n while(this.values[idx] < this.values[child1] || \r\n this.values[idx] < this.values[child2]){\r\n child1 = (2*idx) + 1;\r\n child2 = (2*idx) + 2;\r\n if(this.values[child1] >= this.values[child2]){\r\n let temp = this.values[child1];\r\n this.values[child1] = this.values[idx];\r\n this.values[idx] = temp;\r\n idx = child1;\r\n } else {\r\n let temp = this.values[child2];\r\n this.values[child2] = this.values[idx];\r\n this.values[idx] = temp;\r\n idx = child2;\r\n }\r\n }\r\n return oldRoot;\r\n }", "getResultatCodificat(){ // SI EL MÈTODE NO PASSA ALGUN VALOR, SE LI POSSA this. MÉS EL ATRIBUT CORRESPONENT.\n this.eliminarEspaisBlanc();\n this.senseAccent();\n for (var i = 0; i < this._entrada.length; i++){\n\n // IGUALEM LA LLARGADA DE LA CLAU A LA DE L'ENTRADA\n var y = 0;\n var max_lenght = this._entrada.length;\n while (this._entrada.length != this._clau.length){\n\n this._clau = this._clau + this._clau[y];\n\n if(y >= max_lenght){\n\n y = 0;\n }\n else{\n\n y++;\n }\n }\n\n // BUSQUEM ON ESTAN SITUATS TANT LA LLETRA DE L'ENTRADA COM DE LA CLAU\n var posicio_lletra_entrada = this._alfabet.indexOf(this._entrada[i]);\n var posicio_lletra_clau = this._alfabet.indexOf(this._clau[i]);\n\n // SUMEM LES DUES POSICIONS\n var suma_posicions = posicio_lletra_entrada + posicio_lletra_clau;\n\n // ANEM RESTANT MENTRE QUE EL MOD SIGUI MÉS GRAN QUE EL LENGTH DEL ABECEDARI\n while (suma_posicions >= this._alfabet.length){\n\n suma_posicions = suma_posicions - this._alfabet.length;\n }\n \n // ARA BUSQUEM LA LLETRA AMB LA QUAL SUBSTITUIREM L'ENTRADA\n this._resultat = this._resultat + this._alfabet[suma_posicions];\n }\n\n // RETORNEM EL RESULTAT\n return (document.form.sortida.value = this._resultat);\n }", "function dist2(r,c) {\n\t\tvar d = 0;\n\t\t\tfor(var k=0;k<nv;k++)\n\t\t\t\td += (r[graph.ivalues[k]]-c[k])*(r[graph.ivalues[k]]-c[k]);\n\t\treturn d;\n\t}", "entropy(Array){\n var to_compute = this.twodto1d(Array);\n var sum = 0;\n for (var i = 0; i < to_compute.length; i++){\n if (to_compute[i] != 0){\n sum = sum + to_compute[i] * Math.log2(to_compute[i]);\n }\n }\n return -sum;\n }", "function cercaBinaria (array, elem)\r\n{\r\n var inici = 0;\r\n var fi = array.length - 1;\r\n var trobat = false;\r\n var mig;\r\n\r\n while (inici <= fi && !trobat)\r\n {\r\n var mig = parseInt ((fi + inici) / 2);\r\n\r\n if (generate(array[mig].paraula.toLowerCase()) == elem.toLowerCase()) {\r\n trobat = true;\r\n }\r\n else\r\n {\r\n if (array[mig].paraula.toLowerCase() < elem.toLowerCase()) {\r\n inici = mig + 1;\r\n }\r\n else {\r\n fi = mig - 1;\r\n }\r\n }\r\n }\r\n if (trobat)\r\n {\r\n return mig;\r\n }\r\n else\r\n {\r\n return -1;\r\n }\r\n}", "function getDistorsionValue() {\n var pos = logToPos(k);\n return parseFloat(pos).toFixed(1);\n }", "equivalentMove(_move,size){\n const move =_move.split('');\n let inverted = '';\n let depth;\n if(move[0]==='0'){\n depth = size - parseInt(move[1]) + 1;\n }\n else{\n depth = size - parseInt(move[0]+move[1]) + 1;\n }\n \n if(depth<10){\n inverted+=`0${depth}`\n }\n else{\n inverted+=`${depth}`\n }\n \n switch(move[2]){\n case 'F':\n inverted+='B';\n break;\n case 'f':\n inverted+='b';\n break;\n case 'U':\n inverted+='D';\n break;\n case 'u':\n inverted+='d';\n break;\n case 'R':\n inverted+='L';\n break;\n case 'r':\n inverted+='l';\n break;\n case 'B':\n inverted+='F';\n break;\n case 'b':\n inverted+='f';\n break;\n case 'L':\n inverted+='R';\n break;\n case 'l':\n inverted+='r';\n break;\n case 'D':\n inverted+='U';\n break;\n case 'd':\n inverted+='u';\n break;\n default:\n }\n \n if(move.length<4) inverted+=\"'\";\n return inverted;\n \n }", "size(){ return this.end-this.start }", "function r2max(R)\n{\n // returned the square of the smallest positive root of the derivative of the distorsion polynomial\n // which tells where the distorsion might no longer be bijective.\n var roots = cardan_cubic_roots(7 * R[2], 5 * R[1], 3 * R[0], 1);\n var imax = -1;\n for (var i in roots) if (roots[i] > 0 && (imax == -1 || roots[imax] > roots[i])) imax = i;\n if (imax == -1) return Infinity; // no roots : all is valid !\n return roots[imax];\n}", "calcolaArea() {\n\n return (this.base * this.altezza) / 2; \n }" ]
[ "0.55788004", "0.54666215", "0.54242295", "0.5423678", "0.5421097", "0.53369373", "0.5245887", "0.52254087", "0.5220401", "0.5202418", "0.51871294", "0.51262957", "0.512494", "0.5070953", "0.5052998", "0.5047292", "0.5030834", "0.50111616", "0.49746653", "0.4942044", "0.49388638", "0.49220663", "0.49145648", "0.49133086", "0.4899376", "0.48924023", "0.4874269", "0.48710796", "0.48696464", "0.48397225", "0.4823722", "0.48186234", "0.48142242", "0.48050258", "0.47996965", "0.47917107", "0.47820774", "0.47785354", "0.47738934", "0.47657508", "0.47410548", "0.4733943", "0.47300947", "0.47229964", "0.47215146", "0.4720327", "0.47113785", "0.47076184", "0.47046834", "0.47044453", "0.4697066", "0.4695706", "0.46923319", "0.46814394", "0.46802318", "0.4679116", "0.4664892", "0.4655523", "0.46521792", "0.46497735", "0.4649698", "0.46496323", "0.4644547", "0.46431756", "0.4634501", "0.4634491", "0.46344164", "0.463331", "0.46327844", "0.4632294", "0.4628269", "0.46271637", "0.46257603", "0.4623725", "0.46218196", "0.4620933", "0.46208084", "0.46150708", "0.4612026", "0.46100953", "0.4604838", "0.46039966", "0.4603031", "0.4602561", "0.45946065", "0.45931312", "0.45868874", "0.4585013", "0.45848873", "0.45827854", "0.45796904", "0.45778656", "0.4577553", "0.45740217", "0.45692363", "0.45678326", "0.45634645", "0.4562023", "0.4561876", "0.45617887" ]
0.5561543
1
Used only with promisify. Transform callback to promise result.
function translateError(err, result) { if (!err) { return this.resolve(result); } if (typeof err === 'object') { if (err instanceof Error) { return this.reject(ret); } return this.reject(Object.assign(new Error(err.message), { errCode: err.errCode })); } else if (typeof err === 'string') { return this.reject(new Error(err)); } this.reject(Object.assign(new Error(), { origin: err })); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function promisify () {\n\t var callback;\n\t var promise = new Promise(function (resolve, reject) {\n\t callback = function callback (err, value) {\n\t if (err) reject(err);\n\t else resolve(value);\n\t };\n\t });\n\t callback.promise = promise;\n\t return callback\n\t}", "function promisify(fn) {\n return function(...args) {\n return new Promise( function(resolve, reject) {\n function cb(result) {\n resolve(result)\n }\n\n fn.apply(this, args.concat(cb))\n })\n }\n }", "function promisify(func) {\n var deferred = $q.defer();\n\n func(function(){\n deferred.resolve();\n });\n\n return deferred.promise;\n }", "_asyncWrapper(result) {\r\n if (typeof result === 'object' && 'then' in result) {\r\n return result;\r\n } else {\r\n return new Promise(function(resolve) {\r\n resolve(result);\r\n });\r\n }\r\n }", "function promisify(inner) {\n return new Promise((resolve, reject) =>\n inner((err, res) => {\n if (err) return reject(err);\n else return resolve(res);\n })\n );\n}", "function promisify(fn) {\n //it must return a function\n //to let defer the execution\n return function() {\n //we need the arguments to feed fn when the time comes\n let args = Array.from(arguments);\n\n //we must return a Promise\n //because this is a promisification\n return new Promise(function(resolve, reject) {\n //call the callback-based function and let be notified\n //when it's finished\n //'this' belongs to the function call,\n //therefore it must be set explicitly.\n fn.call(null, ...args, (err, value) => {\n if (err) {\n reject(err);\n } else {\n resolve(value);\n }\n });\n });\n };\n}", "function promisify(func) {\n let deferred = $q.defer();\n\n func((response) => {\n if (response && response.error) {\n deferred.reject(response);\n } else {\n deferred.resolve(response);\n }\n\n $rootScope.$apply();\n });\n\n return deferred.promise;\n }", "function promisify(fn) {\n var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;\n\n var boundFn = fn.bind(context);\n\n return function (data) {\n return new Promise(function (resolve, reject) {\n boundFn(data, function (err, resp) {\n if (err) {\n reject(err);\n } else {\n resolve(resp);\n }\n });\n });\n };\n}", "function promisify(func) {\n return function(...args) {\n // return a wrapper function\n return new Promise((resolve, reject) => {\n function callback(error, result) {\n // our customj callback for func\n if (error) {\n return reject(error);\n } else {\n resolve(result);\n }\n }\n\n args.push(callback); // append our custom callback to the end of arguments\n\n func.call(this, ...args); // call the original function\n });\n };\n}", "function promisify(request) {\r\n return new Promise(function (resolve, reject) {\r\n request.onsuccess = function () {\r\n resolve(request.result);\r\n };\r\n request.onerror = function () {\r\n reject(request.error);\r\n };\r\n });\r\n}", "function promisify(request) {\r\n return new Promise(function (resolve, reject) {\r\n request.onsuccess = function () {\r\n resolve(request.result);\r\n };\r\n request.onerror = function () {\r\n reject(request.error);\r\n };\r\n });\r\n}", "function promisify(request) {\r\n return new Promise(function (resolve, reject) {\r\n request.onsuccess = function () {\r\n resolve(request.result);\r\n };\r\n request.onerror = function () {\r\n reject(request.error);\r\n };\r\n });\r\n}", "function promisify(request) {\n return new Promise(function (resolve, reject) {\n request.onsuccess = function () {\n resolve(request.result);\n };\n request.onerror = function () {\n reject(request.error);\n };\n });\n}", "function promisify(request) {\n return new Promise(function (resolve, reject) {\n request.onsuccess = function () {\n resolve(request.result);\n };\n request.onerror = function () {\n reject(request.error);\n };\n });\n}", "function promisify(request) {\n return new Promise(function (resolve, reject) {\n request.onsuccess = function () {\n resolve(request.result);\n };\n\n request.onerror = function () {\n reject(request.error);\n };\n });\n}", "function promisify(fn) {\n return () => {\n const { client } = this;\n const args = Array.prototype.slice.call(arguments);\n\n return new Promise((resolve, reject) => {\n args.push((err, result) => {\n if (err) reject(err);\n else resolve(result);\n });\n\n client[fn](...args);\n });\n };\n}", "function callbackToPromise(fn, context, callbackArgIndex) {\n if (callbackArgIndex === void 0) { callbackArgIndex = void 0; }\n /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types */\n return function () {\n var callArgs = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n callArgs[_i] = arguments[_i];\n }\n var thisCallbackArgIndex;\n if (callbackArgIndex === void 0) {\n // istanbul ignore next\n thisCallbackArgIndex = callArgs.length > 0 ? callArgs.length - 1 : 0;\n }\n else {\n thisCallbackArgIndex = callbackArgIndex;\n }\n var callbackArg = callArgs[thisCallbackArgIndex];\n if (typeof callbackArg === 'function') {\n fn.apply(context, callArgs);\n return void 0;\n }\n else {\n var args_1 = [];\n // If an explicit callbackArgIndex is set, but the function is called\n // with too few arguments, we want to push undefined onto args so that\n // our constructed callback ends up at the right index.\n var argLen = Math.max(callArgs.length, thisCallbackArgIndex);\n for (var i = 0; i < argLen; i++) {\n args_1.push(callArgs[i]);\n }\n return new Promise(function (resolve, reject) {\n args_1.push(function (err, result) {\n if (err) {\n reject(err);\n }\n else {\n resolve(result);\n }\n });\n fn.apply(context, args_1);\n });\n }\n };\n}", "function callbackified(){var args=[];for(var i=0;i<arguments.length;i++){args.push(arguments[i]);}var maybeCb=args.pop();if(typeof maybeCb!=='function'){throw new TypeError('The last argument must be of type Function');}var self=this;var cb=function cb(){return maybeCb.apply(self,arguments);};// In true node style we process the callback on `nextTick` with all the\n// implications (stack, `uncaughtException`, `async_hooks`)\noriginal.apply(this,args).then(function(ret){process.nextTick(cb,null,ret);},function(rej){process.nextTick(callbackifyOnRejected,rej,cb);});}", "function callbackified(){var args=[];for(var i=0;i<arguments.length;i++){args.push(arguments[i])}var maybeCb=args.pop();if(typeof maybeCb!==\"function\"){throw new TypeError(\"The last argument must be of type Function\")}var self=this;var cb=function(){return maybeCb.apply(self,arguments)};// In true node style we process the callback on `nextTick` with all the\n// implications (stack, `uncaughtException`, `async_hooks`)\noriginal.apply(this,args).then(function(ret){process.nextTick(cb.bind(null,null,ret))},function(rej){process.nextTick(callbackifyOnRejected.bind(null,rej,cb))})}", "function promisifyVinyl(vinyl) {\n return new Promise(function(resolve, reject) {\n vinyl.on('end', resolve) // TODO: handle error?\n })\n}", "function promisify(func) {\n return function promisified() {\n var args = Array.prototype.slice.call(arguments);\n var context = this;\n\n return new Promise(function(resolve, reject) {\n try {\n func.apply(context, args.concat(function(err, data) {\n if (err) {\n return reject(err);\n }\n\n resolve(data);\n }));\n } catch(err) {\n reject(err);\n }\n });\n };\n}", "function promisify(f, thisContext) {\n return function () {\n let args = Array.prototype.slice.call(arguments);\n return new Promise((resolve, reject) => {\n args.push((err, result) => err ? reject(err) : resolve(result));\n f.apply(thisContext, args);\n });\n };\n}", "function sc_makePromise(proc) {\n var isResultReady = false;\n var result = undefined;\n return function() {\n\tif (!isResultReady) {\n\t var tmp = proc();\n\t if (!isResultReady) {\n\t\tisResultReady = true;\n\t\tresult = tmp;\n\t }\n\t}\n\treturn result;\n };\n}", "function callbackified(){var args=[];for(var i=0;i<arguments.length;i++){args.push(arguments[i]);}var maybeCb=args.pop();if(typeof maybeCb!=='function'){throw new TypeError('The last argument must be of type Function');}var self=this;var cb=function(){return maybeCb.apply(self,arguments);};// In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this,args).then(function(ret){process.nextTick(cb.bind(null,null,ret));},function(rej){process.nextTick(callbackifyOnRejected.bind(null,rej,cb));});}", "callback(error, res) {\n getResolvedResult(resolve, reject, error, res);\n }", "callback(error, res) {\n getResolvedResult(resolve, reject, error, res);\n }", "function promiseToServiceCallback(promise) {\n if (typeof promise.then !== \"function\") {\n throw new Error(\"The provided input is not a Promise.\");\n }\n return (cb) => {\n promise\n .then((data) => {\n return process.nextTick(cb, undefined, data.parsedBody, data.request, data);\n })\n .catch((err) => {\n process.nextTick(cb, err);\n });\n };\n}", "function promiseToServiceCallback(promise) {\n if (typeof promise.then !== \"function\") {\n throw new Error(\"The provided input is not a Promise.\");\n }\n return (cb) => {\n promise\n .then((data) => {\n return process.nextTick(cb, undefined, data.parsedBody, data.request, data);\n })\n .catch((err) => {\n process.nextTick(cb, err);\n });\n };\n}", "function callbackWrapper(callback) {\n return function(err, result){\n if(err) {\n callback(err);\n } else {\n callback(null, resultToArray(result));\n }\n };\n }", "function promisify(fn) {\n // Check if the input is not function\n if (!lo.isFunction(fn)) {\n throw new Error('Promisify input is not a Function')\n }\n // Return with new proxy function\n return function promisifier() {\n let self = this\n // Get arguments from proxy\n let args = Array.from(arguments)\n // Return promise to user\n return new Promise((resolve, reject) => {\n // Push callback handler as the last argument\n args.push(callback)\n // Run the callback function\n fn.apply(self, args)\n // Define callback handler\n function callback(err, r) {\n // Get return value as Array\n let rArray = Array.prototype.slice.call(arguments, 1)\n // Check error status\n if (err) {\n reject(err)\n } else {\n if (rArray.length > 1) {\n // Resolve callback resolve as Array\n resolve(rArray)\n } else {\n resolve(r)\n }\n }\n }\n })\n }\n}", "function promisify(original) {\n return function promise_wrap() {\n const args = Array.prototype.slice.call(arguments);\n return new Promise((resolve, reject) => {\n original.apply(this, args.concat((err, value) => {\n if (err) return reject(err);\n resolve(value);\n }));\n });\n };\n}", "wrap(callback) {\n\t\t\treturn ((...args) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst res = callback.apply(null, [...args]);\n\t\t\t\t\tif (res instanceof Promise) {\n\t\t\t\t\t\tres.catch(this.handleBound);\n\t\t\t\t\t}\n\t\t\t\t\treturn res;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tthis.handle(err);\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t});\n\t\t}", "function promisify(original) {\n if ('promisify' in util) {\n return util.promisify(original); // let nodejs do it's thing thing, if it is supported\n }\n else {\n return innerPromisify(original); // Do it ourselves\n }\n}", "wrapCallback(callback) {\r\n return (error, value) => {\r\n if (error) {\r\n this.reject(error);\r\n }\r\n else {\r\n this.resolve(value);\r\n }\r\n if (typeof callback === 'function') {\r\n // Attaching noop handler just in case developer wasn't expecting\r\n // promises\r\n this.promise.catch(() => { });\r\n // Some of our callbacks don't expect a value and our own tests\r\n // assert that the parameter length is 1\r\n if (callback.length === 1) {\r\n callback(error);\r\n }\r\n else {\r\n callback(error, value);\r\n }\r\n }\r\n };\r\n }", "function callbackAsap(cb, err, res) {\n\t asap(function() { cb(err, res); });\n\t}", "function wrapCallback(callback, convertResult) {\n return callback && function (error, result) {\n if (error) {\n callback(error);\n } else if (typeof convertResult === \"function\") {\n callback(error, convertResult(result));\n } else {\n callback(error, result);\n }\n };\n }", "function accept(result, async) {\n if (async) {\n return Promise.resolve(result);\n } else {\n return result;\n }\n}", "function query_promise_then(result) {\n\n\n }", "function query_promise_then(result) {\n\n\n }", "function callbackAsap(cb, err, res) {\n asap(function () {\n cb(err, res);\n });\n}", "done(callback) {\n return this.then(callback);\n }", "function promisifyDBCall (obj) {\n return Q.Promise(function (resolve, reject) {\n obj.exec(function (error, result) {\n if (error) {\n return reject(error)\n } else {\n return resolve(result)\n }\n })\n })\n}", "function handle() {\n var args = _.toArray(arguments);\n var fn = args.shift();\n var result = fn.apply(this, args);\n if (result instanceof Promise) {\n return result;\n } else {\n return Promise.resolve(result);\n }\n}", "function promiseToCallback(promise) {\n if (typeof promise.then !== \"function\") {\n throw new Error(\"The provided input is not a Promise.\");\n }\n // eslint-disable-next-line @typescript-eslint/ban-types\n return (cb) => {\n promise\n .then((data) => {\n // eslint-disable-next-line promise/no-callback-in-promise\n return cb(undefined, data);\n })\n .catch((err) => {\n // eslint-disable-next-line promise/no-callback-in-promise\n cb(err);\n });\n };\n}", "function promiseToCallback(promise) {\n if (typeof promise.then !== \"function\") {\n throw new Error(\"The provided input is not a Promise.\");\n }\n // eslint-disable-next-line @typescript-eslint/ban-types\n return (cb) => {\n promise\n .then((data) => {\n // eslint-disable-next-line promise/no-callback-in-promise\n return cb(undefined, data);\n })\n .catch((err) => {\n // eslint-disable-next-line promise/no-callback-in-promise\n cb(err);\n });\n };\n}", "function asPromise(func, path, data, options, errMsg = \"\", processOut = arg => arg, processErr = processOut) {\n\treturn new Promise((resolve, reject) => {\n\t\tlet callback = (err, stdout, stderr) => {\n\t\t\tif (err != null) {\n\t\t\t\tconsole.log(errMsg);\n\t\t\t\treject(processErr(stderr));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tresolve(processOut(stdout));\n\t\t\t}\n\t\t};\n\n\t\tlet args = (data == null) ? [path, options, callback] : [path, data, options, callback];\n\n\t\tfunc(...args);\n\t});\n}", "function callbackified() {\n var args = [];\n\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n\n var self = this;\n\n var cb = function cb() {\n return maybeCb.apply(self, arguments);\n }; // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n\n\n original.apply(this, args).then(function (ret) {\n process.nextTick(cb, null, ret);\n }, function (rej) {\n process.nextTick(callbackifyOnRejected, rej, cb);\n });\n }", "function callback(deferred) {\n return (err, result) => {\n if (err) deferred.reject(err);else deferred.resolve(result);\n };\n}", "function query_promise_then(result) {\n }", "function query_promise_then(result) {\n }", "function callbackified() {\n var args = [];\n\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n\n var self = this;\n\n var cb = function () {\n return maybeCb.apply(self, arguments);\n }; // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n\n\n original.apply(this, args).then(function (ret) {\n $QcjV$var$process.nextTick(cb, null, ret);\n }, function (rej) {\n $QcjV$var$process.nextTick($QcjV$var$callbackifyOnRejected, rej, cb);\n });\n }", "function done(err, result) {\n callback(err, result);\n }", "function done(err, result) {\n callback(err, result);\n }", "always(callback) {\n return this.then(callback, callback);\n }", "function callbackified() {\n var args = [];\n\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n\n var self = this;\n\n var cb = function () {\n return maybeCb.apply(self, arguments);\n }; // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n\n\n original.apply(this, args).then(function (ret) {\n process.nextTick(cb, null, ret);\n }, function (rej) {\n process.nextTick(callbackifyOnRejected, rej, cb);\n });\n }", "function callbackified() {\n var args = [];\n\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n\n var self = this;\n\n var cb = function () {\n return maybeCb.apply(self, arguments);\n }; // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n\n\n original.apply(this, args).then(function (ret) {\n process.nextTick(cb, null, ret);\n }, function (rej) {\n process.nextTick(callbackifyOnRejected, rej, cb);\n });\n }", "function callbackified() {\n var args = [];\n\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n\n var self = this;\n\n var cb = function () {\n return maybeCb.apply(self, arguments);\n }; // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n\n\n original.apply(this, args).then(function (ret) {\n process.nextTick(cb, null, ret);\n }, function (rej) {\n process.nextTick(callbackifyOnRejected, rej, cb);\n });\n }", "function callback() {}", "function callback() {}", "function callback() {}", "function callback() {}", "function callback() {}", "async function thenify(fn) {\n return await new Promise(function(resolve, reject) {\n function callback(err, res) {\n if (err) return reject(err);\n return resolve(res);\n }\n\n fn(callback);\n });\n}", "function callbackified() {\n var args = [];\n\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n\n var self = this;\n\n var cb = function cb() {\n return maybeCb.apply(self, arguments);\n }; // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n\n\n original.apply(this, args).then(function (ret) {\n process.nextTick(cb, null, ret);\n }, function (rej) {\n process.nextTick(callbackifyOnRejected, rej, cb);\n });\n }", "function callbackified() {\n var args = [];\n\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n\n var self = this;\n\n var cb = function cb() {\n return maybeCb.apply(self, arguments);\n }; // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n\n\n original.apply(this, args).then(function (ret) {\n process.nextTick(cb, null, ret);\n }, function (rej) {\n process.nextTick(callbackifyOnRejected, rej, cb);\n });\n }", "function callbackified() {\n var args = [];\n\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n\n var self = this;\n\n var cb = function cb() {\n return maybeCb.apply(self, arguments);\n }; // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n\n\n original.apply(this, args).then(function (ret) {\n process.nextTick(cb, null, ret);\n }, function (rej) {\n process.nextTick(callbackifyOnRejected, rej, cb);\n });\n }", "function chainCallback(promise, callback) {\n if (callback) {\n return promise.then(function fulfilled(result) {\n callback(null, result);\n }, function rejected(reason) {\n callback(reason);\n });\n } else {\n return promise;\n }\n }", "function asPromised(fn) {\n const promiseWrappedHandler = Promise.method(fn);\n return function (msg, cb) {\n return promiseWrappedHandler.call(this, msg).catch(function (err) {\n console.error('io call error for msg=' + msg + ':\\n\\t' + (err.stack ? err.stack : err));\n return Promise.reject(err instanceof Error ? err.message : err);\n }).asCallback(cb);\n };\n}", "function handleCallback(callback, err, result) {\n try {\n callback(err, result);\n } catch (err) {\n process.nextTick(function() {\n throw err;\n });\n }\n}", "function handleCallback(callback, err, result) {\n try {\n callback(err, result);\n } catch (err) {\n process.nextTick(function() {\n throw err;\n });\n }\n}", "function _wrapPromise(val) {\n if (val && angular.isFunction(val.then)) {\n return val;\n }\n return $q.resolve(val);\n }", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n \n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }", "function callback(err, r) { console.log(`callback: result=${r}; error=${err}`); }", "function wrapInPromise(func){\r\n var promise = new Promise((resolve, reject) => {\r\n resolve(func);\r\n });\r\n return promise;\r\n}", "function coerce(promise){var deferred=defer();Q.nextTick(function(){try{promise.then(deferred.resolve,deferred.reject,deferred.notify);}catch(exception){deferred.reject(exception);}});return deferred.promise;}", "function promisify(func, argumentsObject) {\n var args = Array.prototype.slice.call(argumentsObject);\n var self = this;\n\n return new Promise(function(resolve, reject) {\n var result;\n args.push(function(err) {\n if (err) reject(err);\n else resolve(result);\n });\n\n result = func.apply(self, args);\n });\n}", "function createApplyPromise(result){\n var promise;\n if (typeof result === 'boolean'){\n var deferred = $q.defer();\n if (result){\n deferred.resolve();\n } else {\n deferred.reject();\n }\n promise = deferred.promise;\n } else {\n promise = $q.when(result);\n }\n return promise;\n }", "function promisify(func, manyArgs = false) {\n return function(...args) {\n return new Promise((resolve, reject) => {\n function callback(error, ...results) {\n // our custom callback for func\n if (error) {\n return reject(error);\n } else {\n // resolve with all callback results if manyArgs is specified\n resolve(manyArgs ? results : results[0]);\n }\n }\n\n args.push(callback);\n\n func.call(this, ...args);\n });\n };\n}", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret); },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb); });\n }", "function toPromise2v(fun) {\n return toPromise2(fun);\n }", "function callback(){}", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }", "function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb, null, ret) },\n function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });\n }" ]
[ "0.7245928", "0.6800695", "0.63663805", "0.63389796", "0.6273299", "0.6189637", "0.61894166", "0.6179876", "0.6132731", "0.61184716", "0.61184716", "0.61184716", "0.6102181", "0.6102181", "0.60698295", "0.60670626", "0.6028015", "0.59939146", "0.59934825", "0.59591895", "0.5951672", "0.59440804", "0.59203506", "0.59073937", "0.59044856", "0.59044856", "0.590166", "0.590166", "0.5875381", "0.58529425", "0.5844122", "0.5779134", "0.57668936", "0.57559806", "0.57496065", "0.57028496", "0.5698389", "0.5695449", "0.5695449", "0.5692901", "0.56829655", "0.56723005", "0.5668951", "0.5668742", "0.5668742", "0.5652734", "0.55842245", "0.5584125", "0.5564974", "0.5564974", "0.555084", "0.55508065", "0.55508065", "0.5528306", "0.55119526", "0.55119526", "0.55119526", "0.5491142", "0.5491142", "0.5491142", "0.5491142", "0.5491142", "0.547681", "0.5472923", "0.5472923", "0.5472923", "0.5459457", "0.5401114", "0.53864", "0.53864", "0.53669167", "0.53668636", "0.5360621", "0.5359498", "0.53240263", "0.5312597", "0.53076977", "0.5304881", "0.52974916", "0.52928275", "0.5290111", "0.52823895", "0.52823895", "0.52823895", "0.52823895", "0.52823895", "0.52823895", "0.52823895", "0.52823895", "0.52823895", "0.52823895", "0.52823895", "0.52823895", "0.52823895", "0.52823895", "0.52823895", "0.52823895", "0.52823895", "0.52823895", "0.52823895", "0.52823895" ]
0.0
-1
Display Voucher with Item From localStroage
function vouchertable() { var localstorageitem = localStorage.getItem('cart'); // var notes = note; if (localstorageitem) { var localstorageitem = JSON.parse(localstorageitem); var mycart = localstorageitem.mycart; var tbodytable =''; var foottable=''; var subtotal =0; var total=0; var tax=25; var total_tax =0; var shipping = 2500; var j=1; $.each(mycart,function (i,v) { if (v) { var id = v.id; var name = v.name; var price = v.price; var photo = v.image; var qty = v.qty; console.log("voucherqty - "+qty); var eachtotal = price * qty; tbodytable +='<tr>'+ '<td>'+j+'</td>'+ '<td>'+name+'</td>'+ '<td>'+price+'</td>'+ '<td>'+qty +'</td>'+ '<td>'+eachtotal+'</td>'+ '</tr>'; subtotal += (price*qty); total_tax = parseInt(subtotal) + parseInt(tax); j++; } }) total += total_tax; console.log(total); foottable +='<tr>'+ '<td colspan="2" rowspan="4">'+ '<p> NOTES : </p>'+ '<p> '+note+' </p>'+ '</td>'+ '<td colspan="2">'+ '<p> Subtotal </p>'+ '</td>'+ '<td colspan="2">'+ '<p> '+subtotal+' </p>'+ '</td>'+ '</tr>'; foottable +='<tr>'+ '<td colspan="2"> Tax </td>'+ '<td> 5% </td>'+ '</tr>'; foottable +='<tr>'+ '<td colspan="2" style="color: red; font-size:20px;"> Total Amount:</td>'+ '<td>'+total+'</td>'+ '</tr>'; $('#voucher_tbody').html(tbodytable); $('tfoot').html(foottable); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function displayInventory() {\n\tqueryStr = 'SELECT * FROM bamazondb.products';\n\tconnection.query(queryStr, function(err, data) {\n\t\tif(err) throw err;\n\n\t\tconsole.log(\"Current Inventory: \");\n\t\tconsole.log(\"...........................................................................................................\\n\");\n\n\t\tvar strOut = '';\n\t\tfor (var i = 0; i < data.length; i++) {\n\t\t\tstrOut = '';\n\t\t\tstrOut = 'Item ID: ' + data[i].item_id + ' // ';\n\t\t\tstrOut += 'Product Name: ' + data[i].product_name + ' // ';\n\t\t\tstrOut += 'Department: ' + data[i].department_name + ' // ';\n\t\t\tstrOut += 'Price: $' + data[i].customer_price + ' // ';\n\t\t\tstrOut += 'Quantity: ' + data[i].stock_quantity + '\\n';\n\n\t\t\tconsole.log(strOut);\n\t\t}\n\n\t\tconsole.log(\"-----------------------------------------------------------------------------------------------------------\\n\");\n\t\tpromptUserPurchase();\n\t})\n}", "function purchaseItem() {}", "function purchaseItem() {}", "function purchaseItem() {}", "function purchaseItem() {}", "function purchaseItem() {}", "function purchaseItem() {}", "fetchInventoryItem(id){\r\n return Api().get('/inventory/' + id)\r\n }", "async index({ params: { companyId }, request, response, view }) {\n const company = await Company.find(companyId);\n //const user = await auth.getUser()\n\n const inventory = new Inventory();\n inventory = await company.inventory().fetch();\n\n response.status(200).json({\n message: 'Inventario',\n data: inventory,\n });\n }", "function getInventory(){\n axios.get('/inventory')\n .then(res => setItems(res.data))\n .catch(err => alert(err))\n }", "async showItemsForSale() {\n const character = this.character;\n\n let description = character.location.getDescription(character)\n + character.location.getShopDescription(character, this.info.type);\n\n let attachments = new Attachments().add({\n title: \"What do you want to buy?\",\n fields: character.getFields(),\n color: COLORS.INFO\n });\n\n [description, attachments] = this.getEquipmentForSale(character, description, attachments);\n [description, attachments] = this.getSpellsForSale(character, description, attachments);\n [description, attachments] = this.getItemsForSale(character, description, attachments);\n\n attachments.addButton(\"Cancel\", \"look\", { params: { resetDescription: \"true\" } });\n\n await this.updateLast({ description, attachments });\n }", "function displayInventory() {\n\t// console.log('___ENTER displayInventory___');\n\n\t// Construct the db query string\n\tqueryStr = 'SELECT * FROM products';\n\n\t// Make the db query\n\tconnection.query(queryStr, function(err, data) {\n\t\tif (err) throw err;\n\n\t\tconsole.log('Existing Inventory: ');\n\t\tconsole.log('...................\\n');\n\n\t\tvar strOut = '';\n\t\tfor (var i = 0; i < data.length; i++) {\n\t\t\tstrOut = '';\n\t\t\tstrOut += 'Item ID: ' + data[i].item_id + ' // ';\n\t\t\tstrOut += 'Product Name: ' + data[i].product_name + ' // ';\n\t\t\tstrOut += 'Department: ' + data[i].department_name + ' // ';\n\t\t\tstrOut += 'Price: $' + data[i].price + '\\n';\n\n\t\t\tconsole.log(strOut);\n\t\t}\n\n\t \tconsole.log(\"---------------------------------------------------------------------\\n\");\n\n\t \t//Prompt the user for item/quantity they would like to purchase\n\t \tpromptUserPurchase();\n\t})\n}", "function purchasedItem(listItem) {\n listItem.hide();\n purchased.append(listItem);\n listItem.show('slow');\n }", "function showItemDetails(){\n\n\tvar symbol = document.getElementsByClassName(\"symbol\")[0].innerHTML;\n\n\tsearchReturnItem(parsedText,symbol);\n\t// var showAsset = document.getElementsByClassName(\"symbol\").innerHTML = asset.price;\n\t// var asset = searchReturnAsset(parsedText,asset);\n\t// return document.getElementsByClassName(\"price\").innerHTML = asset.price;\n\t// return console.log(asset.price);\n}", "function showPurchases() {\n app.getView().render('account/giftregistry/purchases');\n}", "function displayInv() {\n connection.query(\"SELECT * FROM products\", function (err, results) {\n if (err) throw err;\n console.log(\"\\n______________WELCOME TO BAMAZON!______________\")\n console.log(\"\\n-------------- Current Inventory --------------\\n\")\n console.log(\" ID: | Name: | Dept: | Price: |\");\n for (let i = 0; i < results.length; i++) {\n var inv = results[i];\n console.log(\"\\n\" + \" \" + inv.item_id + \" | \" + inv.product_name +\n \" | \" + inv.department_name + \" | \" + inv.price +\n \" | \");\n }\n console.log(\"\\n---------------------------------------------\\n\")\n\n shop();\n })\n\n}", "function inventory() {\n connection.query(\"SELECT * FROM products\", function (err, res) {\n displayForManager(res);\n purchasePrompt();\n });\n}", "function fetchVendorItems(id){\n fetch(`https://easysource-backend.herokuapp.com/api/v1/vendors/${vendorId}`)\n .then(res=>res.json())\n .then(vendorDetails=>showAllVendorItems(vendorDetails))\n }", "function displayItem(myItemObj) {\r\n\tcurrItemCode = myItemObj.code; //assign current item with code of current item being viewed. \r\n\tcurrItemCategory = myItemObj.category; //assign current item with code of current item being viewed. \r\n\tcurrItemName = myItemObj.simpleName;\r\n\tget(\"vBoxEquip\").style.display = \"none\";\r\n\tget(\"vBoxAccept\").style.display = \"none\";\r\n\tget(\"vBoxUse\").style.display = \"none\";\r\n\tget(\"vBoxContent\").style.display = \"none\";\r\n\tget(\"vBoxDrop\").style.display = \"none\";\r\n\tget(\"vBoxCancel\").style.display = \"none\";\r\n\tget(\"vBoxDesc\").style.display = \"block\";\r\n\r\n\tif(myItemObj.category == \"potion\") {\r\n\t\tget(\"vBoxHeader\").innerHTML = myItemObj.fullName;\r\n\t\tget(\"vBoxDesc\").innerHTML = myItemObj.desc;\r\n\t\tget(\"vBoxContent\").innerHTML = \"<strong>Effect: </strong>\" + myItemObj.effect + \"<br><strong>Uses: </strong>\" + myItemObj.uses;\r\n\t\tget(\"vBoxUse\").style.display = \"inline\";\r\n\t\tget(\"vBoxDrop\").style.display = \"inline\";\r\n\t\tget(\"vBoxCancel\").style.display = \"inline\";\r\n\t\tget(\"vBoxContent\").style.display = \"block\";\r\n\t}\r\n\telse if(myItemObj.category == \"item\") {\r\n\t\tget(\"vBoxHeader\").innerHTML = myItemObj.fullName;\r\n\t\tget(\"vBoxDesc\").innerHTML = myItemObj.desc;\r\n\t\tget(\"vBoxUse\").style.display = \"inline\";\r\n\t\tget(\"vBoxDrop\").style.display = \"inline\";\r\n\t\tget(\"vBoxCancel\").style.display = \"inline\";\r\n\t}\r\n\telse if(myItemObj.category == \"weapon\") {\r\n\t\tget(\"vBoxHeader\").innerHTML = myItemObj.fullName;\r\n\t\tget(\"vBoxDesc\").innerHTML = myItemObj.desc;\r\n\t\tget(\"vBoxContent\").innerHTML = \"<strong>Damage: </strong>\" + myItemObj.effect;\r\n\t\tget(\"vBoxEquip\").style.display = \"inline\";\r\n\t\tget(\"vBoxDrop\").style.display = \"inline\";\r\n\t\tget(\"vBoxCancel\").style.display = \"inline\";\r\n\t\tget(\"vBoxContent\").style.display = \"block\";\r\n\t}\r\n\telse if(myItemObj.category == \"armor\") {\r\n\t\tget(\"vBoxHeader\").innerHTML = myItemObj.fullName;\r\n\t\tget(\"vBoxDesc\").innerHTML = myItemObj.desc;\r\n\t\tget(\"vBoxContent\").innerHTML = \"<strong>Effect: </strong>\" + myItemObj.effect;\r\n\t\tget(\"vBoxEquip\").style.display = \"inline\";\r\n\t\tget(\"vBoxDrop\").style.display = \"inline\";\r\n\t\tget(\"vBoxCancel\").style.display = \"inline\";\r\n\t\tget(\"vBoxContent\").style.display = \"block\";\r\n\t}\r\n}", "function showItems() {\n connection.query(\"SELECT * FROM products\", function (err, results) {\n if (err) throw err;\n var resultsArr = [];\n for (i = 0; i < results.length; i++) {\n resultsArr.push(\"\\nITEM ID: \" + results[i].item_id + \" || ITEM: \" + results[i].product_name + \" || PRICE: \" + results[i].price + \" || QUANTITY: \" + results[i].stock_quantity + \"\\n\\n--------------------------------------------------------------------------\");\n }\n console.log(\"\\nITEMS FOR SALE:\\n\" + resultsArr.join(\"\\n\"));\n userPurchase();\n });\n}", "function viewProducts() {\n connection.query(\"SELECT item_id, product_name, price, stock_quantity FROM products\", function (err, res) {\n //error occurs\n if (err) {\n throw err;\n }\n\n console.table(\"\\nInventory\", res);\n returnToMenu();\n });\n}", "function printItem(res) {\n console.log(`ID: #${res.item_id}`);\n console.log(`Description: ${res.product_name}`);\n console.log(`Price: ${formatter.format(res.price)}`);\n}", "function displayStock() {\n\n //table creation using cli-table package\n var table = new Table({\n head: ['ID', 'PRODUCT', 'PRICE', 'IN STOCK'],\n colWidths: [6, 32, 14, 14],\n style: {'padding-left': 2, 'padding-right': 2}\n });\n for (var i = 0; i < stock.length; i++) {\n var item = stock[i];\n\n //if item is in stock, push to the table\n if (stock[i].StockQuantity > 0) {\n table.push([item.ItemID, item.ProductName, \"$\" + item.Price, item.StockQuantity]);\n }\n }\n clear();\n console.log(\"----------------------------------------------------------------------\");\n console.log(\" WELCOME TO BAMAZON CUSTOMER VIEW \");\n console.log(\" \");\n console.log(\" HERE IS WHAT WE HAVE IN STOCK \");\n console.log(\"----------------------------------------------------------------------\");\n //displays the table\n console.log(table.toString());\n}", "function displayItems() {\n connection.query(\"SELECT * FROM PRODUCTS\", function(error, data) {\n if (error) throw error;\n data.forEach(item => {\n if (item.stock > 0) {\n console.log(\n `######################\nItem ID: ${item.item_id}\nProduct: ${item.prod_name}\nDepartment: ${item.dept_name}\nPrice: ${item.price}\nItems Available: ${item.stock}\n######################\\n`\n );\n }\n });\n userProdID = getProdID(data);\n });\n}", "function display () {\n connection.query(\"SELECT * FROM products\", function (err, res) {\n if (err) throw err;\n console.log(\"Welcome to Bamazon! Here's what we have for sale:\")\n // for loop to loop through each item in the sql file for display\n for (var i=0; i < res.length; i++) {\n console.log(\"Item ID: \" + res[i].id + ' ' + res[i].product_name + ' $' + res[i].price);\n }\n purchase();\n })\n}", "function displaySelectedItem() {\n var fi = findItem();\n if (fi) {\n $scope.item.category = fi.category;\n $scope.item.text = fi.text;\n $scope.item.amount = fi.amount;\n }\n else\n {\n //item add\n $scope.item.category={};\n $scope.item.text = '';\n $scope.item.amount = '';\n $rootScope.editMode = false;\n }\n }", "fetchInventory () {\r\n return Api().get('inventory')\r\n }", "function getBookingItemForDisplay(id) {\n var url = 'data/bookingDetailData-' + id + '.json';\n return $http.get(url, {\n transformResponse: transformBookingItemForDisplay\n })\n .then(sendResponseData)\n .catch(sendGetBookingError);\n }", "buyItem(item) {\n console.log(\"Buying Item:\", item.name);\n }", "function list_cart_items() {\r\n\tvar location_id = document.getElementById(\"txt_location_id\").value;\r\n\tvar status = document.getElementById(\"txt_status\").value;\r\n\tvar cart_session_id = document.getElementById(\"txt_session_id\").value;\r\n\tvar vouchertype_id = document.getElementById(\"txt_vouchertype_id\").value;\r\n\tvar voucher_so_id = document.getElementById(\"txt_soid\").value;\r\n\tif (voucher_so_id != '0') {\r\n\t\tshowHintAccount('../accounting/invoice-details2.jsp?' + 'voucher_so_id=' + voucher_so_id + '&status=' + status + '&location_id=' + location_id + '&cart_session_id=' + cart_session_id\r\n\t\t\t\t+ '&cart_vouchertype_id=' + vouchertype_id + '&list_cartitems=yes', 'invoice_details');\r\n\t} else {\r\n\t\tshowHintAccount('../accounting/invoice-details2.jsp?' + 'status=' + status + '&location_id=' + location_id + '&cart_session_id=' + cart_session_id + '&cart_vouchertype_id=' + vouchertype_id\r\n\t\t\t\t+ '&list_cartitems=yes', 'invoice_details');\r\n\t}\r\n}", "function ViewBasketItem(){\n let locationid = localStorage.getItem('locationId');\n let customerid = localStorage.getItem('customerId');\n let url = 'https://localhost:5001/Location/get/order/' + locationid + '/' + customerid;\n fetch(url)\n .then(result => result.json())\n .then(result => {\n document.querySelectorAll('#basket tbody tr').forEach(element => element.remove());\n let table = document.querySelector('#basket tbody');\n for(let i = 0; i < result.orderItems.length; ++i)\n {\n \n let row = table.insertRow(table.rows.length);\n\n let nCell = row.insertCell(0);\n nCell.innerHTML = fetch('https://localhost:5001/Location/get/product/' + result.orderItems[i].productId)\n .then(r => r.json())\n .then(r => nCell.innerHTML =r.name);\n\n let pCell = row.insertCell(1);\n pCell.innerHTML = result.orderItems[i].totalPrice;\n }\n \n });\n\n \n}", "function displayInventory() {\n\n var inventMsg = \"Inventory:\" + inventory;\n\n updateDisplay(inventMsg);\n\n }", "function viewProd(item){\n connection.query(\"SELECT item_id, product_name, department_name, price, stock_quantity FROM products WHERE ?;\", \n \t{ item_id: item }, function(err, res){\n\t if(err) throw err;\n\t // console.log(res);\n\t\tvar aligns = [null, null, null, 'right', 'right'];\n // instantiate \n var tableInventory = new Table({\n \thead: ['Item ID', 'Product Name', 'Department', 'Price', 'Quantity']\n , colWidths: [10, 48, 18, 10, 10]\n , colAligns: aligns\n });\n\n\t// the tableInventory is an Array, so you can `push`, `unshift`, `splice` and the rest \n\ttableInventory.push(\n\t [res[0].item_id, res[0].product_name, res[0].department_name, res[0].price.toFixed(2), res[0].stock_quantity] // .toFixed(2) forces trailing zeros in prices\n\t); \n console.log(tableInventory.toString());\n\n // adding space after rendered table\n console.log(oneLine);\n // return original inquirer list for manager's choice\n startMeUp();\n });\n}", "function viewSale() {\n connection.query(\"SELECT * FROM products\", function (err, res) {\n if (err) throw err;\n for (var i = 0; i < res.length; i++) {\n console.log();\n console.log(\"---------------------------------------------\");\n console.log(res[i].item_id + \" | \" + res[i].product_name + \" | \" + res[i].department_name + \" | $\" + res[i].price + \" | \" + res[i].stock_quantity);\n }\n });\n manager();\n}", "function showInventory() {\n connection.query(\"SELECT * FROM products\", function (err, results) {\n if (err) throw err;\n console.table(results);\n selectItem();\n })\n}", "static displayBook(){\n // //Imaginary local storage for trial purpose\n // const bookstore=[\n // {\n // title: 'Book One',\n // author: 'John Doe',\n // isbn: '345678'\n // },\n // {\n // title: 'Book Two',\n // author: 'Nobel Reo',\n // isbn: '348982'\n // }\n // ];\n const books = Store.getBooks();\n books.forEach((book) => UI.addBookToList(book));\n }", "function customerView () {\n common.openConnection(connection);\n let querySQL = 'SELECT item_id, product_name, stock_quantity, price FROM products where stock_quantity > 0'; // exclude from \"where\" to premit out-of-stock items\n connection.query(querySQL, (error, result) => {\n if (error) throw error;\n let msg = ''; \n let title = 'LIST OF PRODUCTS FOR SALE';\n common.displayProductTable(title, result) // pass title and queryset to function that will print out information\n console.log('\\n');\n customerSelect();\n });\n \n}", "function inventoryString(item){\n\n\t var url =\"inventoryContent/content.php?inventory=\"+item.id;\n\t return \"<div class='inventoryElem'>\"+\n\t\t\t\t\"<div class='squareBox'>\"+\n\t\t\t\t\"<a href='\"+url+\"'>\"+\n\t\t\t\t\t\"<div class='circle squareContent' style='background-color: initial;'>\"+\n\t\t\t\t\t\"<div class='circle squareContent' style='margin: 0;border: none;background-color:\"+item.color+\";background-image:url(img/inventoryIcon.png);'>\"+\n\t\t\t\t\t\"</div></div></a>\"+\n\t\t\t\t\"</a>\"+\n\t\t\t\t\"</div><span class='inventoryName'>\"+item.name+\"</span>\"+\n\t\t\t\t\"</div>\";\n }", "function btn_displayInventory() {\n var msg = \"Inventory: \" + inventory;\n updateDisplay(msg);\n}", "fetchCurrency(shelf) {\n axios\n .get(`http://localhost:5000/item/${shelf}`)\n .then(res => {\n console.log(res);\n this.setState({ item: res.data, loading: false });\n //this.setState({ employee: res.data[0].employee });\n //console.log(this.state.item.name);\n })\n .catch(e => {\n console.log(\"error happened\", e);\n });\n }", "function displayInventory() {\n connection.query(\"SELECT * FROM products\", function(err, res) {\n for (var i = 0; i < res.length; i++) {\n console.log(res[i].item_id + \" | \" + res[i].product_name + \" | \" + res[i].department_name + \" | \" + res[i].price + \" | \" + res[i].stock_quantity);\n }\n console.log(\"-----------------------------------\");\n });\n }", "function viewItemToEdit(item) {\n\t\tOverlayModule.enableOverlay();\n\t\tvar viewProduct = findItem(item)[0];\n\t\tvar div = document.getElementById(\"itemImage\");\n\t\tdiv.src = \"images/\"+item+\".jpg\";\n\n\n\t\tvar itemFullName = viewProduct.p_variation + \" \" + viewProduct.p_name;\n\t\tvar itemCurrency = viewProduct.c_currency;\n\t\tvar itemName = viewProduct.p_name;\n\t\tvar itemMRPrice = viewProduct.p_originalprice;\n\t\tvar itemPrice = viewProduct.p_price;\n\t\tvar itemAvailSizes = viewProduct.p_available_options.sizes;\n\t\tvar itemAvailColors = viewProduct.p_available_options.colors;\n\t\t$(\"#iId\").attr(\"value\", viewProduct.p_id);\n\t\t$(\"#iFullName\").html(itemFullName);\t\n\t\t$(\"#iCurrency\").html(itemCurrency);\n\t\t$(\"#iName\").html(itemName);\t\t\t\t\n\t\t$(\"#iMRPrice\").html(itemMRPrice);\t\t\t\t\n\t\t$(\"#iPrice\").html(itemPrice);\t\t\t\t\n\n\t\tif (itemMRPrice === itemPrice) {\n\t\t\t$(\"#iMRPrice\").css(\"visibility\", \"hidden\");\n\t\t\t$(\"#iMRPrice\").html(\"\");\n\t\t}\n\n\t\tfor (var i=0; i < itemAvailColors.length; i++){\n\t\t\t$('ul#iColorOption').append(\"<li id='\"+itemAvailColors[i].hexcode+\"' class='colorOps' style = 'background-color:\"+itemAvailColors[i].hexcode+\"' title='\"+itemAvailColors[i].name+\"'></li>\");\n\t\t}\n\t\tfor (var i=0; i < itemAvailSizes.length; i++){\n\t\t\t$('#iSizeOption').append(new Option(itemAvailSizes[i].code.toUpperCase(), itemAvailSizes[i].name));\n\t\t}\n\t\treturn;\n\t}", "function displayInventory() {\n\tconnection.query('SELECT * FROM products', function(err, res){\n\t\tif (err) throw err;\n console.log('=============================What would you like to buy?==============================');\n \n for(var i = 0; i<res.length;i++){\n console.log(\"ID: \" + res[i].item_id + \" | \" + \n \"Product: \" + res[i].product_name + \" | \" + \n \"Department: \" + res[i].department_name + \" | \" + \n \"Price: \" + res[i].price + \" | \" + \n \"QTY: \" + res[i].stock_quantity);\n console.log('======================================================================================'); \n };\n buyItem();\n });\n}", "function loadGiftBoxDetailsForItem(itemUUID) {\n\teditedItemUUID = itemUUID;\n\tvar cObj = YAHOO.ebauer.utilities.asyncRequest('GET', getBaseURL() + '/ajax/loadGiftBoxDetails.jsp?uuid=' + editedItemUUID, callbackLoadGiftBox);\n}", "function setupPurchase() {\r\n // Get chosen package information\r\n var depFlight = JSON.parse(localStorage.getItem('departure'));\r\n var hotel = JSON.parse(localStorage.getItem('hotel'));\r\n var retFlight = JSON.parse(localStorage.getItem('return'));\r\n\r\n // Display correct package price numbers\r\n document.getElementById('hotel').innerHTML = 'Hotel: $' + numberWithCommas(parseInt(hotel.price));\r\n document.getElementById('flight').innerHTML = 'Flight: $' + numberWithCommas(parseInt(depFlight.price) + parseInt(retFlight.price));\r\n document.getElementById('total').innerHTML = localStorage.getItem('total');\r\n}", "function viewCadet(item)\n{\n\tcadet = cadetsArr[item];\n\t\n\n\tif(cadetsArr.length==0)\n\t{\n\t\tclearCart();\n\t}\n\telse\n\t{\n\n\t\tlocalStorage.setItem(\"company\", JSON.stringify(cadet.company));\n\t\tlocalStorage.setItem(\"firstName\", JSON.stringify(cadet.firstName));\n\t\tlocalStorage.setItem(\"lastName\", JSON.stringify(cadet.lastName));\n\t\tlocalStorage.setItem(\"DOB\", JSON.stringify(cadet.DOB));\n\t\tlocalStorage.setItem(\"age\", JSON.stringify(cadet.age));\n\t\tlocalStorage.setItem(\"race\", JSON.stringify(cadet.race));\n\t\tlocalStorage.setItem(\"sex\", JSON.stringify(cadet.sex));\n\t\tlocalStorage.setItem(\"city\", JSON.stringify(cadet.city));\n\t\tlocalStorage.setItem(\"county\", JSON.stringify(cadet.county));\n\t\tlocalStorage.setItem(\"departure\", JSON.stringify(cadet.departure));\n\t\tlocalStorage.setItem(\"id\", JSON.stringify(cadet.id));\n\t}\n\n\twindow.location=\"/editCadetRecord\";\n}", "function retrieve_item() {\n let qty_in_store = localStorage.getItem('Qty');\n if(qty_in_store){\n qty = JSON.parse(qty_in_store);\n }\n}", "function viewSaleProduct() {\n connection.query(\"SELECT * FROM store\", function (err, results) {\n if (err) throw err;\n console.table(results);\n })\n}", "function displayItemsForSale() {\n connection.query(\"SELECT item_id, product_name, price, department_name,stock_quantity FROM products\", function (err, result) {\n if (err) throw err;\n\n if (result.length == 0) {\n console.log(\"There are no items for sale.\");\n }\n\n for (var i = 0; i < result.length; i++) {\n console.log(colors.green(\"\\nBook ID: \" + result[i].item_id.toString() + \"\\n\" +\n \"Book Name: \" + result[i].product_name + \"\\n\" +\n \"Book Price: \" + parseInt(result[i].price).toFixed(2) + \"\\n\" +\n \"Department: \" + result[i].department_name + \"\\n\" +\n \"Stock: \" + result[i].stock_quantity));\n }\n chooseMenu();\n });\n}", "function displayItems() {\n\tconsole.log(\"\\nWelcome, Customer!\");\n\tconsole.log(\"\\nItems available: \\n\");\n\tconnection.query(\"SELECT * FROM products\", function(err, res) {\n\t\tif (err) throw err;\n\t\t// console.log(res);\n\t\tfor (var i = 0; i < res.length; i++) {\n\t\t\tvar row = res[i];\n\t\t\tconsole.log(\"\\n----------\\n\");\n\t\t\tconsole.log(\"Item ID: \" + row.item_id);\n\t\t\tconsole.log(\"Product Name: \" + row.product_name);\n\t\t\tconsole.log(\"Price: $\" + row.price);\n\t\t};\n\t\tpromptCustomer();\n\t});\n}", "function render_all(items, user) {\n\t$(\"#wddp-mu-cash\").text(\"You have \" + user.total_money + \" left in your account\");\n\titems = Object.values(items);\n\t$(\"#wddp-mu-items\").html(items.map((x)=>(x.render(\"store\"))).join(\"\"));\n}", "function viewLowInventory() {\n con.query(\"SELECT * from vw_LowInventory\", function (err, result) {\n if (err) {\n throw err;\n }\n else {\n var table = new Table({\n\t\t head: ['Product Id', 'Product Name', 'Department','Price', 'Quantity'],\n\t\t style: {\n\t\t\t head: ['blue'],\n\t\t\t compact: false,\n\t\t\t colAligns: ['center','left','left','right', 'right']\n\t\t }\n\t });\n\n\t //loops through each item in the mysql database and pushes that information into a new row in the table\n\t for(var i = 0; i < result.length; i++) {\n\t\t table.push(\n\t\t\t [result[i].Product_Id, result[i].Product_Name, result[i].Department, result[i].Price, result[i].Quantity]\n\t\t );\n\t }\n \n console.log(table.toString());\n runManageBamazon();\n }\n });\n}", "function showItem(shownItem) {\n var breadcrumbArr = [];\n\n fullBreadcrumbArr();\n // let us make a Breadcrumb arr\n function fullBreadcrumbArr() {\n var breadcrumbEnd = {\n name: shownItem.name,\n url: '/' + shownItem.vendorCode,\n active: true\n };\n breadcrumbArr.push(breadcrumbEnd);\n\n recursBreadcrumbArrPush(shownItem.groups);\n\n function recursBreadcrumbArrPush(currentCatId) {\n let currentCat = shopCategoriesArr.filter(function(cat) {\n return cat.catId == currentCatId;\n });\n let breadcrumbPart = {\n name: currentCat[0].catName,\n url: '/' + currentCat[0].catAlias,\n active: false\n };\n breadcrumbArr.push(breadcrumbPart);\n if (\n currentCat[0].catFatherId &&\n !(currentCat[0].catFatherId == 'absent')\n )\n recursBreadcrumbArrPush(currentCat[0].catFatherId);\n }\n\n var breadcrumbShop = {\n name: 'Каталог',\n url: 'shop',\n active: false\n };\n breadcrumbArr.push(breadcrumbShop);\n var breadcrumbMainPage = {\n name: 'Главная',\n url: '/',\n active: false\n };\n breadcrumbArr.push(breadcrumbMainPage);\n breadcrumbArr.reverse();\n\n //urls in arr are not full yet, so:\n let fullUrl = '';\n for (let i = 0; i < breadcrumbArr.length; i++) {\n breadcrumbArr[i].url = fullUrl + breadcrumbArr[i].url;\n fullUrl = breadcrumbArr[i].url;\n }\n }\n //console.log(breadcrumbArr);\n\n testimonial\n .find({ shopitemid: shownItem.vendorCode, approved: true })\n .then(testimonialArr => {\n testimonialArr.reverse();\n //console.log(shownItem);\n res.render(viewsView, {\n transData: {\n shopItemsArr,\n shopCategoriesArr,\n user: { _id, login, group },\n shownItem,\n breadcrumbArr,\n shopCart,\n showDiscountChooser,\n discount,\n priceSettings,\n testimonialArr\n }\n });\n })\n .catch(err => {\n console.log('K8 ERROR: Нет доступа к базе.' + err);\n res.render('error', {\n transData: {\n user: { _id, login, group }\n },\n message: 'Ошибка сервера, попробуйте позже!',\n error: { code: 503 }\n });\n });\n\n //console.log(shownItem);\n }", "function displayInventory() {\n\tconnection.query('SELECT * FROM Products', function (err, res) {\n\t\tif (err) { console.log(err) };\n\t\tvar table = new Table({\n\t\t\thead: ['item_id', 'item_name', 'department_name', 'price', 'stock_quantity'],\n\t\t\tcolWidths: [10, 30, 30, 20, 20]\n\t\t});\n\t\tfor (i = 0; i < res.length; i++) {\n\t\t\ttable.push(\n\t\t\t\t[res[i].item_id, res[i].product_name, res[i].department_name, res[i].price, res[i].stock_quantity]\n\t\t\t);\n\t\t}\n\t\tconsole.log(table.toString());\n\t\tinventoryUpdates();\n\t});\n}", "function showInventory() {\n connection.query('SELECT ItemID, ProductName, Price FROM products', function(err, rows, fields) {\n if (err) throw err;\n console.log('Available products:');\n for(var i = 0; i < rows.length; i++) {\n console.log('Item ID: ' + rows[i].ItemID + ' Product Name: ' + rows[i].ProductName + ' Price: $' + rows[i].Price);\n }\n runPrompt();\n });\n}", "function onGetItemByIdSuccess(items) {\n $(\"#message-text\").val(\"Thank You!!!\");\n $(\"#change-returned\").val(\n items.quarters + \" quarters, \" + items.dimes + \" dimes, \" + items.nickels + \" nickels, \" + items.pennies + \" pennies\"\n );\n\n}", "function showPurchaseList() {\n purchased_items = [];\n $(\"#purchase_list_items\").empty();\n $(\"#purchase_list_items\").append(loading);\n var out = '<div><ul data-role=\"listview\" data-inset=\"true\" data-theme=\"a\">';\n $.ajax({\n type: \"GET\",\n url: config.api_url + \"module=admin&action=purchase_list\",\n dataType: \"json\",\n cache: false,\n success: function (data) {\n if (data.error == false) {\n $(\"#purchase_list_items\").empty();\n $.each(data.data, function (index, row) {\n purchased_items.push({id: row.id, supplier_name: row.supplier_name, price: row.price, qty: row.quantity, date: row.date, total: row.total_amount, item_name: row.item_name, cheque: row.chq_no});\n out = out + '<li><a class=\"ui-btn ui-btn-corner-all\" href=\"#view_purchased_item?id=' + row.id + '\">#' + row.id + '. on ' + $.format.date(row.date, \"dd-MMM-yy\") + ' value of &#8377; ' + parseInt(row.total_amount) + '</a></li>';\n });\n out = out + '</ul></div>';\n $(out).appendTo(\"#purchase_list_items\").enhanceWithin();\n }\n },\n error: function (request, status, error) {\n $(\"#purchase_list_items\").empty();\n $(\"#purchase_list_items\").append(\"Loading failed try again!!\");\n }\n });\n}", "function onQueryVATId() {\n var vatId = $(\"#query-vat-id\").val();\n console.log(\"Fetching data from\", vatId);\n showCompany(vatId);\n }", "function displayItemDetails()\n {\n var item = Office.cast.item.toItemRead(Office.context.mailbox.item);\n var from = Office.cast.item.toMessageRead(item).from;\n var email = from.emailAddress;\n\n var name = from.displayName.substr(0, from.displayName.indexOf(' '));\n $(\"#name\").val(name);\n\n var surname = from.displayName.substr(from.displayName.indexOf(' ') + 1);\n $(\"#surname\").val(surname);\n\n var domain = email.substr(email.indexOf('@') + 1);\n var company = domain.substr(0, domain.indexOf('.'));\n $(\"#company\").val(company);\n }", "function getInventory() {\n connection.query(\"SELECT * FROM products\", function(err, inventoryRes) {\n if (err) {\n console.log(\"ERROR: \", err);\n }\n\n console.log(\"CURRENT INVENTORY: \");\n printTable(inventoryRes);\n console.log(\"\");\n\n purchase();\n });\n}", "function viewLowInventory() {\n\n var query = \"SELECT * FROM products\";\n connection.query(query, function(err, res) {\n if (err) throw err;\n console.log(\"All items that need to be restocked:\\n\");\n console.log(\"\\n-----------------------------------------\\n\");\n for (var i = 0; i < res.length; i++) {\n if (res[i].stock_quantity <= 5) {\n console.log(\"Id: \".bold + res[i].item_id + \" | Product: \".bold + res[i].product_name + \" | Department: \".bold + res[i].department_name + \" | Price: \".bold + \"$\".green.bold +res[i].price + \" | QOH: \".bold + res[i].stock_quantity);\n }\n }\n console.log(\"\\n-----------------------------------------\\n\");\n });\n\n\n}", "function list_cart_items() {\r\n\tvar location_id = document.getElementById(\"txt_location_id\").value;\r\n\tvar status = document.getElementById(\"txt_status\").value;\r\n\tvar cart_session_id = document.getElementById(\"txt_session_id\").value;\r\n\tvar vouchertype_id = document.getElementById(\"txt_vouchertype_id\").value;\r\n\tvar voucher_so_id = document.getElementById(\"txt_soid\").value;\r\n\tif (voucher_so_id !='0'){\r\n\t\tshowHintFootable('../accounting/invoice-details.jsp?'\r\n\t\t\t\t+ 'voucher_so_id=' + voucher_so_id\r\n\t\t\t\t+ '&status=' + status\r\n\t\t\t\t+ '&location_id=' + location_id\r\n\t\t\t\t+ '&cart_session_id=' + cart_session_id\r\n\t\t\t\t+ '&cart_vouchertype_id=' + vouchertype_id\r\n\t\t\t\t+ '&list_cartitems=yes', 'invoice_details');\r\n\t}else{\r\n\tshowHintFootable('../accounting/invoice-details.jsp?'\r\n\t\t\t+ 'status=' + status\r\n\t\t\t+ '&location_id=' + location_id\r\n\t\t\t+ '&cart_session_id=' + cart_session_id\r\n\t\t\t+ '&cart_vouchertype_id=' + vouchertype_id\r\n\t\t\t+ '&list_cartitems=yes', 'invoice_details');\r\n\t}\r\n}", "print(request, response) {\n let repoSeller = new repoSellers();\n // console.log('ici 3')\n repoSeller.getallSellersinMyBdd().then(allSellersinMyDbb => {\n // on place allSellersinMyDbb qui est un un tableau comme variable a utilisé dans pug dans le rendu de la repose : { allSellersinMyDbb }\n // C'est ici qu on refere le chemin de la vue liste_homeview \n response.render('home', { allSellersinMyDbb });\n });\n }", "function displayItems() {\n connection.query(\"SELECT * FROM products\", function(err, res) {\n if (err) {\n throw err;\n } else {\n console.table(res);\n }\n shopping();\n \n });\n \n}", "function displayInventory() {\n\t\t\tvar text = \"Inventory: \";\n\t\t\tif (Inventory.length > 1) {\n\t\t\t\tfor (var x = 0; x < Inventory.length; x++) {\n\t\t\t\ttext = text + Inventory[x] + \", \";\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfor (var x = 0; x < Inventory.length; x++) {\n\t\t\t\ttext = text + Inventory[x];\n\t\t\t\t}\n\t\t\t}\n\t\t\tdocument.getElementById(\"Inventory\").innerHTML = text;\n\t\t\t\n\t}", "function displayItems()\n{\n\t//Select All from (products) table within (bamazon) DB\n\tconnection.query(\"SELECT * FROM products\", function(err, res)\n\t{\n\n\t\tif(err) throw err;\n\n\t\t//Display all products in table by looping through each row inside table\n\t\tfor(var i = 0; i < res.length; i++)\n\t\t{\n\t\t\tconsole.log(\"ID: \" + res[i].item_id + \" | \" +\n\t\t\t\t\t\t\"Product Name: \" + res[i].product_name + \" | \" +\n\t\t\t\t\t\t\"Category: \" + res[i].department_name + \" | \" +\n\t\t\t\t\t\t\"Price: \" + res[i].price );\n\t\t}\n\n\t\tconsole.log(\"-----------------------------------------------------------------\\n\");\n\n\t\t//Allow Customer to make purchase\n\t\tbuy();\n\n\t});\n}", "function viewLowInv() {\n connection.query(\"SELECT * FROM products WHERE stock_quantity <= 30\", function (err, results) {\n if (err) throw err;\n for (let i = 0; i < results.length; i++) {\n console.log(\"Item \" + results[i].item_id + \"| Product Name: \" + results[i].product_name + \"| Price: \" + results[i].price + \"| In Stock: \" + results[i].stock_quantity);\n }\n\n });\n connection.end();\n}", "function displayProducts(){\n \n\tconnection.query(sql, function(err, data) {\n\t if (err) {\n\t console.log(err);\n\t }\n\n\t var items = '';\n\t\t\tfor (var i = 0; i < data.length; i++) {\n\t\t\t\titems = '';\n\t\t\t\titems += 'ID: ' + data[i].item_id + ' | ';\n\t\t\t\titems += 'Product: ' + data[i].product_name + ' | ';\n\t\t\t\titems += 'Dept: ' + data[i].department_name + ' | ';\n\t\t\t\titems += '$' + data[i].price + ' | ';\n\t\t\t\titems += 'Quantity: ' + data[i].stock_quantity;\n\t\t console.log(\"------------------------------------------------------------------------\");\n\t console.log(items);\n\t\t\t};\n\n\t\tpurchase();\n\n\t});\n\n}", "function showItems() {\n connection.query( query , function (err, result, fields){\n if (err) throw err;\n for(i = 0; i < result.length; i++){\n console.log(\"\\n\" + colors.green(result[i].id) + \") \" + \"Item: \".yellow + result[i].product_name + \" |\".blue + \" Department: \".yellow + result[i].department + \" |\".blue + \" Price: \".yellow + \"$\"+ result[i].price + \" |\".blue + \" Stock: \".yellow + result[i].stock_qty + \"\\n------------------------------------\".blue);\n }\n })\n}", "function viewProducts() {\n console.log('Here is the current inventory: ');\n var table = new Table({\n head: ['Item ID', 'Product Name', 'Price', 'Quantity']\n });\n connection.query(\"SELECT * FROM products\", function (err, res) {\n for (let i = 0; i < res.length; i++) {\n table.push(\n [res[i].item_id, res[i].product_name, res[i].price, res[i].stock_quantity]\n );\n }\n console.log(table.toString());\n console.log('\\n*******************');\n managerOptions();\n })\n}", "function viewLowInventory() {\n var query = \"SELECT item_id, product_name, price, stock_quantity FROM products WHERE stock_quantity < 5\";\n connection.query(query, function (err, res) {\n //error occurs\n if (err) {\n throw err;\n }\n\n console.table(\"\\nLow Inventory\", res);\n returnToMenu();\n });\n}", "function viewProducts() {\n connection.query(\"SELECT * FROM products\", function(err, results) {\n if (err) throw err;\n console.log(\"\\n\" + colors.yellow(\"---------------------PRODUCTS FOR SALE---------------------\") + \"\\n\");\n var table = new cliTable({ head: [\"ID\", \"Item\", \"Price\", \"Quantity\"] });\n for (var i = 0; i < results.length; i++) {\n table.push([results[i].id, results[i].productName, results[i].price, results[i].stockQuantity]);\n }\n console.log(table.toString() + \"\\n\");\n actionPrompt();\n });\n}", "function showTable() {\n\t\tlet menuString = localStorage.getItem('menulist');\n\t\tif (menuString) {\n\n\t\t\t$('#div-voucher').show();\n\t\t\t\n\t\t\t// ** show in html \n\t\t\tlet menuArray = JSON.parse(menuString);\n\t\t\tif (menuArray != 0) {\t\n\n\t\t\t\tlet total = 0;\n\t\t\t\tlet tbodyData = '', tfootData = '';\n\t\t\t\t\n\t\t\t\t// looping \n\t\t\t\t$.each(menuArray, function(i, v) {\n\t\t\t\t\tlet name = v.name;\n\t\t\t\t\tlet price = v.price;\n\t\t\t\t\tlet qty = v.qty;\n\t\t\t\t\tlet subtotal = price * qty;\n\n\t\t\t\t\ttotal += subtotal;\n\n\t\t\t\t\t// in plus and minus button data-id is set with array index\n\t\t\t\t\ttbodyData += `<tr>\n\t\t\t\t\t\t\t\t\t\t\t\t\t<td>${name}<br><em class=\"text-muted font-weight-light\">${price} Ks</em></td>\n\t\t\t\t\t\t\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<button type=\"button\" class=\"btn-minus btn btn-sm btn-secondary\" data-id=\"${i}\">&#45;</button>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"mx-2\">${qty}</span>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<button type=\"button\" class=\"btn-plus btn btn-sm btn-secondary\" data-id=\"${i}\">&#43;</button>\n\t\t\t\t\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t\t\t\t\t\t<td>${subtotal} Ks</td>\n\t\t\t\t\t\t\t\t\t\t\t\t\t<td align=\"center\">\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<button type=\"button\" class=\"btn btn-danger btn-sm btn-remove\" data-id=\"${i}\">&times;</button>\n\t\t\t\t\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t\t\t\t\t<tr>`;\n\n\t\t\t\t});\t// looping end\n\t\t\t\t\n\t\t\t\ttfootData += `<tr>\n\t\t\t\t\t\t\t\t\t\t\t\t<td colspan=\"4\">\n\t\t\t\t\t\t\t\t\t\t\t\t\t<button type=\"button\" class=\"btn btn-light btn-block\" id=\"btn-checkout\">Check Out</button>\n\t\t\t\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t\t\t\t</tr>`;\n\n\t\t\t\t$('#payment').html(tbodyData);\n\t\t\t\t$('tfoot').html(tfootData);\n\n\t\t\t} else { \n\n\t\t\t\t// although array is existed and value is empty\n\t\t\t\t$('#div-voucher').hide();\n\t\t\t\n\t\t\t}\n\n\t\t} else {\n\t\t\t$('#div-voucher').hide();\n\t\t}\n\t}", "function get_item(item) {\n money_count += item.price;\n return items[item.id];\n}", "function viewProduct() {\n var query =\n 'SELECT item_id, product_name, price, stock_quantity FROM products WHERE stock_quantity > 0';\n connection.query(query, function(err, res) {\n console.table(res);\n reset();\n });\n}", "function displayAcct(){\n var info = JSON.parse(window.localStorage.getItem('currentUser')).split(',');\n document.getElementById('bodyList').innerHTML = '<tr><td>UserName:</td><td>' + info[0] + '</td></tr>'\n + '<tr><td>First Name:</td><td>' + info[1] + '</td><td>Favorite Charity:</td><td>' + info[12] + '</td></tr>'\n + '<tr><td>Last Name:</td><td>' + info[2] + '</td><td>First Donation:</td><td>$' + info[13] + '</td></tr>'\n + '<tr><td>Email:</td><td>' + info[8] + '</td><td>Site Rating (1-10):</td><td>' + info[14] + '</td></tr>'\n + '<tr><td>Birthday:</td><td>' + info[11] + '</td></tr>' \n + '<tr><td>Telephone #:</td><td>' + info[9] + '</td><td>Credit Card #:</td><td>' + info[15] + '</td></tr>'\n + '<tr><td>Address:</td><td>' + info[4] + '</td><td>Card CVV#:</td><td>' + info[16] + '</td></tr>'\n + '<tr><td>City:</td><td>' + info[5] + '</td><td>Card Type:</td><td>' + info[20] + '</td></tr>'\n + '<tr><td>State:</td><td>' + info[6] + '</td><td>Card Expiration Date:</td><td>' + info[19] + '</td></tr>'\n + '<tr><td>ZipCode:</td><td>' + info[7] + '</td><td>First Name on Card:</td><td>' + info[17] + '</td></tr>'\n + '<tr><td>Country:</td><td>' + info[10] + '</td><td>Last Name on Card:</td><td>' + info[18] + '</td></tr>';\n}", "function onSelectedItemClicked(e) {\r\n checkForSuccessfulPurchase();\r\n\r\n\r\n var item = $(this);\r\n var idForUser = item.data('idforuser');\r\n var idForServer = item.data('idforserver');\r\n\r\n var itemIdDisplay = $('#itemIdDisplay');\r\n if (itemIdDisplay.val() != idForUser) {\r\n $('#messagesDisplay').val(\"\");\r\n }\r\n\r\n itemIdDisplay.val(idForUser);\r\n itemIdDisplay.data('idforserver', idForServer);\r\n}", "function pushTableItem(item, index){\n divDataTransaksi.dataTransaksi.push({\n invoice : obj[index].invoice,\n kodeService : obj[index].kodeService, \n namaPelanggan : obj[index].namaPelanggan, \n waktu : obj[index].waktu, \n total : obj[index].total\n }); \n }", "function newItem() {\n console.log(\"\\nnewItem clicked\");\n this_contract.newItem(\"Test 2\", 500, 10, {from: from_account, gas: 500000}).then(function(value) {\n console.log(value.valueOf());\n console.log(web3.eth.getTransactionReceipt(value));\n }).catch(function(e) {\n console.log(e);\n });\n}", "function displayItems(items, store, prices) {\n\tvar xhttp = new XMLHttpRequest();\n\txhttp.open(\"GET\", \"ItemsHelper.jsp?items=\"+items+\"&store=\"+store+\"&prices=\"+prices, false);\n\txhttp.send();\n\tif (xhttp.responseText.trim().length > 0) {\n\t\tdocument.getElementById(\"itemsList\").innerHTML = xhttp.responseText;\n\t}\n}", "function showItems() {\n connection.query(\"SELECT item_id, product_name, price FROM products\", function (err, res) {\n if (err) throw err;\n console.table(res)\n // for (var i = 0; i < res.length; i++) {\n // console.log(\"Item ID: \" + res[i].item_id + \"\\n\" + \"Product Name: \" + res[i].product_name + \"\\n\" + \"Price: \" + res[i].price + \"\\n-------------------------\");\n // }\n orderItemsPrompt();\n });\n}", "function inventory(){\n connection.query(\"SELECT * FROM products\", function(err, res){\n if (err) throw err;\n res.forEach(function(item){\n console.log(`Item Name: ${item.product_name} \\n Department: ${item.department_name} \\n Price: ${item.price} \\n Quantity: ${item.stock_quantity}`);\n console.log(\"----------------------------------------------------\")\n })\n returntoMenu();\n });\n}", "function actualizarPrecioCarritoDlt(item){\n \n totalCarrito = totalCarrito - item.precioItem;\n $(\".shoppingCartTotal\").html(`$ ${totalCarrito.toFixed(2)}`);\n $(\".shoppingCartTotal\").hide()\n $(\".shoppingCartTotal\").fadeIn(\"slow\")\n localStorage.setItem( \"total\", JSON.stringify(totalCarrito));\n}", "function ListNormal() {\n $.get(\"/api/inventory\", function(data) {\n for (var i = 0; i < data.length; i++) {\n if (data[i].isCritical === false) {\n var crit = \"NO\";\n var ingredItem = `<tr class='normalAmount'><td id='item'> ${data[i].item} </td> \n <td> ${data[i].qty} </td>\n <td id='unit'> ${data[i].unit} </td>\n <td> ${crit} </td>\n <td id=\"snackbar\"> ${data[i].item} added to orders!</td></tr>`;\n ingredList.append(ingredItem);\n }\n }\n //This adds to localstorage to be used for orders.\n $(\".normalAmount\").click(function() {\n var x = this.children[4];\n x.className = \"show\";\n setTimeout(function() {\n x.className = x.className.replace(\"show\", \"\");\n }, 3000);\n var item = this.children[0].innerText;\n var unit = this.children[2].innerText;\n localStorage.setItem(item, unit);\n });\n });\n }", "function show() {\n\tnums = JSON.parse(localStorage.getItem('nums'));\n\tadds = JSON.parse(localStorage.getItem('adds'));\n\tvar text = adds.map (function(itm,i){\n return [ (i + 1) + '.' + \" \" + itm + \" \" + \" - \" + \" \" + nums[i]];\n}).join('\\n');\n\talert('DELIVERY LIST:' + '\\n' + '\\n' + text + '\\n' + '\\n' + 'Total: $' + nums.reduce(getSum, 0).toFixed(2));\n}", "function getItems(){\n var dist=\"Distributor : \" + db.getItem(\"adist\");\n var item=\"Item : \" + db.getItem(\"aitem\");\n var quantity=\"Quantity : \" + db.getItem(\"aquantity\");\n var amount=\"Amount : \" + db.getItem(\"aamount\");\n var ordered=\"Ordered? : \" + db.getItem(\"aordered\");\n var orderdate=\"Order Date : \" + db.getItem(\"aorderdate\");\n var note=\"Notes : \" + db.getItem(\"anote\");\n \n var viewItems = [\n dist,\n item,\n quantity,\n amount,\n ordered,\n orderdate,\n note\n ];\n \n // hide div:main show div:clear //\n document.getElementById(\"main\").style.display = \"none\";\n document.getElementById(\"clear\").style.display = \"block\";\n // depending on what distributor - show image //\n var dist2= db.getItem(\"adist\"); \n if (dist2==\"BestMeats\") {\n document.getElementById(\"distpic1\").style.display =\"block\";\n }else if (dist2==\"USFoods\") {\n document.getElementById(\"distpic2\").style.display =\"block\";\n }else if (dist2==\"Condiments\") {\n document.getElementById(\"distpic3\").style.display =\"block\";\n }\n // list item info //\n var getMyList = document.getElementById(\"list\");\n for (var i=0, j=viewItems.length; i<j; i++){\n var newP = document.createElement(\"p\");\n var itemTxt = document.createTextNode(viewItems[i]);\n newP.appendChild(itemTxt);\n getMyList.appendChild(newP);\n }\n //alert(viewItems);\n \n}", "function displayCheckout(){\n\n let productNumb = localStorage.getItem('cartNumbers');\n let totalCartCost = localStorage.getItem('totalCost');\n\n $('.basket-total-cost').html(\"Basket Total (\"+ productNumb +\" items): $\"+totalCartCost + \",00\");\n\n}", "function viewLowInventory(){\n var query = connection.query(\"SELECT ID, Product_Name , Price, Stock_QTY FROM products WHERE Stock_Qty < 20;\", function(err, res) {\n console.log(\"\");\n console.table(res);\n console.log(\"\");\n managerAsk();\n });\n }", "function viewLowInventory() {\n clearConsole();\n connection.query(\"SELECT * FROM products WHERE stock_quantity < 5\", function (err, response) {\n if (err) throw err;\n displayInventory(response);\n userOptions();\n })\n}", "function viewInventory() {\n connection.query(\"SELECT * FROM products WHERE stock_quantity < 5\",\n function (err, res) {\n for (var i = 0; i < res.length; i++) {\n console.log(res[i].product_name + \"\\n----------------------\\n\");\n }\n }\n )\n }", "display() {\n for (let i = 0; i < this.data.stock.length; i++) {\n console.log(i + 1 + \". \" + this.data.stock[i].corporation);\n }\n }", "_listProduct() {\r\n //Limpia el texto cada vez que se sobrescribe\r\n this._text = \"\";\r\n for (let i = 0; i < this._inventory.length; i++) {\r\n //console.log(this._inventory[i].toString());\r\n this._text += this._inventory[i].toString() + \"<br>\";\r\n };\r\n }", "function take_item() {\r\n\r\n\t\titem_ladle \t\t= new proto_item(0, \"Ladle\", \"This is a very dull wooden ladle its mostly for soup and acid, but mostly soup.\");\r\n\t\titem_silver_key = new proto_item(1, \"Silver Key\", \"This is a key, and it happens to be silver, who would have thought.\");\r\n\t\titem_lockbox \t= new proto_item(2, \"Lockbox\", \"This is a box shaped container, it is also locked. You need a key to open it.\");\r\n\t\titem_keycard \t= new proto_item(3, \"Keycard\", \"This is a card that can open doors, much like a real key, but however it is in the shape of a card.\");\r\n\r\n\r\n\t\tswitch (currentlocation) {\r\n\t\t\tcase 0: \r\n\t\t\t\t\tinventoryArray[0] = item_ladle\r\n\t\t\t\t\tupdatetext (\"Your inventory now contains the Ladle.\")\r\n\t\t\t\t\t\r\n\t\t\t\t\tbreak;\r\n\t\t\tcase 9:\r\n\t\t\t\t\tinventoryArray[3] = item_card\r\n\t\t\t\t\tupdatetext (\"Your inventory now contains the card.\")\r\n\t\t\t\t\t\r\n\t\t\t\t\tbreak;\r\n\t\t\tcase 8:\r\n\t\t\t\t\tinventoryArray[2] = item_lockbox\r\n\t\t\t\t\tupdatetext (\"Your inventory now contains the lockbox.\")\r\n\t\t\t\t\t\r\n\t\t\t\t\tbreak;\r\n\t\t\tcase 7:\r\n\t\t\t\t\tinventoryArray[1] = item_silver_key\r\n\t\t\t\t\tupdatetext (\"Your inventory now contains the Silver Key.\")\r\n\t\t\t\t\t\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}", "async show({ request, response }) {\n try {\n const id = request.params.id\n let redisKey = `DownPayment_${id}`\n let cached = await RedisHelper.get(redisKey)\n if (cached) {\n return response.status(200).send(cached)\n }\n const data = await DownPayment.find(id)\n if (!data) {\n return response.status(400).send(ResponseParser.apiNotFound())\n }\n await data.load(\"target\")\n\n let parsed = ResponseParser.apiItem(data.toJSON())\n await RedisHelper.set(redisKey, parsed)\n return response.status(200).send(parsed)\n } catch (e) {\n ErrorLog(request, e)\n return response.status(500).send(ResponseParser.unknownError())\n }\n }", "function displayItems() {\n \n // build MySQL query string\n var queryString = 'SELECT * FROM ??'\n\n // query MySQL database\n connection.query(queryString, [\"products\"], function(err, res){\n if (err) {\n return console.log(\"There was an error \", err)\n } \n console.log(lineBreak + \"ITEMS FOR SALE\")\n\n // loop through response and format data for print\n res.forEach(function(element){\n var resPrint = element.item_id + \". \" + element.product_name + divider + \"Dept: \" + element.department_name + divider + \"Price: $\" + element.price + divider + \"In-stock: \" + element.stock_quantity\n console.log(resPrint)\n })\n\n console.log(lineBreak);\n selectItem();\n })\n}", "async showQuantities() {\n const character = this.character;\n const item = this.info.item;\n const buyItem = Items.new(item);\n let actions = new Actions();\n\n let style = buyItem.canBePurchasedBy(character, 1) ? 'default' : 'danger';\n actions.addButton(\"Buy 1\", COMMAND_NAME, { params: { action: ACTION_BUY, item, quantity: 1 }, style });\n\n style = buyItem.canBePurchasedBy(character, 5) ? 'default' : 'danger';\n actions.addButton(\"Buy 5\", COMMAND_NAME, {params: { action: ACTION_BUY, item, quantity: 5 }, style });\n\n style = buyItem.canBePurchasedBy(character, 10) ? 'default' : 'danger';\n actions.addButton(\"Buy 10\", COMMAND_NAME, { params: { action: ACTION_BUY, item, quantity: 10 }, style });\n\n style = buyItem.canBePurchasedBy(character, 25) ? 'default' : 'danger';\n actions.addButton(\"Buy 25\", COMMAND_NAME, { params: { action: ACTION_BUY, item, quantity: 25 }, style });\n\n actions.addButton(\"Cancel\", \"look\", { params: { resetDescription: \"true\" } });\n\n await this.updateLast({\n attachments: Attachments.one({\n title: \"How many do you want to buy?\",\n fields: this.character.getFields(),\n actions\n })\n });\n }", "function voucher_logo_details(){\r\n\tvar voucher_logo = document.getElementById(\"cmp-pic\");\r\n\tvoucher_logo.src = localStorage.getItem(\"company-logo\");\r\n\tvoucher_logo.style.backgroundSize = \"cover\";\r\n\tvar voucher_details = document.getElementById(\"voucher-details\");\r\n\tvar string = localStorage.getItem(\"company\");\r\n\tvar company_details = JSON.parse(string);\r\n\tvoucher_details.innerHTML = \"<div style='font-size:35px;text-transform:capitalize;font-family:Righteous;font-weight:bold'>\"+company_details.cmp_name+\"</div><address style='margin-bottom:5px;margin-left:2px;font-size:18px'> venue : \"+company_details.address+\"</address>\"+\"call : \"+company_details.phone;\r\n}", "function displayItems() {\n console.log(\"\\n Hello! Welcome to Bamazon! Below are some of our products available for purchase.\\n\");\n connection.query(\"SELECT * FROM products\", function (err, res) {\n if (err) \n throw err;\n \n for (var i = 0; i < res.length; i++) {\n console.log(\"\\n\", \"Product ID: \" + res[i].item_id + \"\\n\", \"Product Name: \" + res[i].product_name + \"\\n\", \"Product Price: $ \" + res[i].price + \"\\n\",)\n }\n console.log(\"----------------------------------------------------\");\n // console.log(res);\n });\n customerInquiryAlert();\n}", "function salvage(name,id,key,item) {\r\n\t\r\n\t\tif (xhr != null || /Salvaged/.test(item.textContent) || !confirm('Salvage ' + name + '?')) return;\r\n\t\t\r\n\t\tvar target = item.querySelector('.fd2 > div');\r\n\t\tvar xhr = [target,target.textContent,new XMLHttpRequest()];\r\n\t\txhr[2].open('POST','/?s=Bazaar&ss=fr&filter=' + getType(name),true);\r\n\t\txhr[2].setRequestHeader('Content-Type','application/x-www-form-urlencoded');\r\n\t\txhr[2].onload = function(x) {\r\n\t\t\r\n\t\t\tif (xhr[2].readyState != 4) return;\r\n\t\t\t\r\n\t\t\tvar temp = document.createElement('div'), result;\r\n\t\t\ttemp.innerHTML = xhr[2].responseText;\r\n\t\t\t\r\n\t\t\tvar message = temp.querySelector('#messagebox');\r\n\t\t\tif (message) {\r\n\t\t\t\tvar results = temp.querySelector('#messagebox .cmb6:last-child').textContent.trim();\r\n\t\t\t\tresult = 'Salvaged: ' + ( /No usable/.test(results) ? ' no usable materials ' : results.replace(/^Salvaged\\s/,'') );\r\n\t\t\t} else {\r\n\t\t\t\txhr[0].parentNode.parentNode.removeAttribute('class');\r\n\t\t\t\tresult = xhr[1]\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\txhr[0].textContent = result;\t\t\t\r\n\t\t\txhr = null;\r\n\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\txhr[0].textContent = 'Salvaging...';\t\t\r\n\t\txhr[0].parentNode.parentNode.className = 'salvaging';\r\n\t\txhr[2].send('select_item=' + id + '&select_action=salvage');\r\n\r\n\t}", "vendItem(productIndex) {\n //check if valid\n let product = vm.products[productIndex]\n // IF Exists we have some you have enough money\n if (product && product.quantity > 0 && vm.currentTransaction >= product.price) {\n this.processTransaction(product)\n return JSON.parse(JSON.stringify(product))\n }\n return false\n }" ]
[ "0.5848599", "0.5817837", "0.5817837", "0.5817837", "0.5817837", "0.5817837", "0.5817837", "0.5790922", "0.57839847", "0.576355", "0.57463163", "0.5733274", "0.5714628", "0.5688417", "0.56780815", "0.562454", "0.56078476", "0.56077284", "0.5576948", "0.55680764", "0.556762", "0.5551263", "0.5546015", "0.55402887", "0.5537875", "0.5529739", "0.5510082", "0.55097485", "0.54986036", "0.549266", "0.548275", "0.547434", "0.54623973", "0.54610926", "0.54606044", "0.54595697", "0.5449747", "0.5440111", "0.5436932", "0.5411834", "0.5408149", "0.53958935", "0.53876394", "0.5376899", "0.5376421", "0.53541154", "0.53517437", "0.53428644", "0.53367156", "0.5328151", "0.5319737", "0.5318656", "0.5314754", "0.5307645", "0.5300026", "0.52757376", "0.5270948", "0.52633667", "0.52607644", "0.5260065", "0.52531075", "0.5253001", "0.5251111", "0.5247024", "0.52417314", "0.52321315", "0.5227214", "0.5226065", "0.5223938", "0.52202487", "0.52188027", "0.5210831", "0.52094793", "0.52058566", "0.52002776", "0.51993084", "0.519667", "0.51949775", "0.519473", "0.51927155", "0.5189759", "0.5186463", "0.51862943", "0.5185559", "0.51845485", "0.5182542", "0.51755863", "0.51729655", "0.5172304", "0.51701856", "0.5169723", "0.51673347", "0.5165149", "0.5159975", "0.5159261", "0.51581204", "0.5152718", "0.514868", "0.5137702", "0.51288766" ]
0.51944053
79
getEmailFromLocalStorage function gets the user email from local storage, it returns false if value is not found in local storage. email is stored as email in local storage
function getEmailFromLocalStorage() { if (localStorage.getItem("email")) { return localStorage.getItem("email"); } else { return false; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function get_user_email(){ return localStorage['logged_in_as']; }", "function checkAccount() {\n console.log(localStorage);\n if (localStorage.getItem(\"email\") === null) {\n\n } else {\n existingAccount = true;\n }\n}", "function isEmailUnique() {\n\n var email = document.getElementById(\"password\")\n\n var user_email_input = $(\"#email_input\").val();\n var parsedLocalStorage = JSON.stringify(localStorage);\n\n if(parsedLocalStorage.indexOf(user_email_input) == -1){\n return true;\n }\n return false;\n}", "function saveInfoLocal(email) {\n localStorage.setItem('email', email);\n}", "function lookupEmail (email) {\n for (let key in users) {\n if (email === users[key].email){\n return users[key];\n }\n }\n return false;\n}", "function getUser(enteredEmail) {\n for (let user in users ) {\n if (users[user].email === enteredEmail) {\n return users[user];\n }\n } \n return false;\n}", "function existeUsuario(pEmail) {\n let existe = false;\n let i = 0;\n let favoritos = window.localStorage.getItem(\"AppProductosFavoritos\");\n let favoritosJSON = JSON.parse(favoritos);\n if (favoritosJSON !== null) {\n while (!existe && i < favoritosJSON.length) {\n let unFav = favoritosJSON[i];\n let unEmail = unFav.usuario;\n if (pEmail == unEmail) {\n existe = true;\n }\n i++;\n }\n }\n return existe;\n}", "static currentUserName() {\n const userName = localStorage.getItem('username');\n return userName.trim() || localStorage.getItem('email');\n }", "function guardarEmail(email) {\n email = prompt(\"Ingrese su email\");\n let arrEmail = email.split(\"\");\n if (arrEmail.includes(\"@\") && arrEmail.includes(\".\")) {\n localStorage.setItem(\"email\", email);\n enviarMail(mailTo);\n } else {\n alert(\"Datos invalidos\");\n }\n }", "function checkEmail(email) {\n const savedEmail = \"[email protected]\";\n const loginEmail = email.toLowerCase().trim();\n return savedEmail === loginEmail ? true : false;\n}", "function setEmail() {\n if (emailCheck.checked === true) {\n localStorage.setItem('emailCheck', 'true')\n } else {\n localStorage.setItem('emailCheck', 'false')\n }\n}", "function emailChecker (email){\n for (id in users) {\n if (email === users[id].email){\n return users[id]\n } \n }\n return false;\n}", "function inform_storage(){\n alert('Thank you for subscribing!');\n localStorage.setItem('subscribeEmail',document.getElementById('inputEmail').value)\n console.log(`SubscribeEmail: ${document.getElementById('inputEmail').value}`)\n \n}", "function isAuth(){\n let email = sessionStorage.getItem(\"user\");\n if (email == null){\n console.log(\"nu er vi nået til linje 6\")\n console.log(email)\n window.location.href = \"login.html\"\n }else{\n return \n }\n}", "function userEmailCheck(input) {\n for (user in users) {\n if (users[user].email === input) {\n return users[user].id;\n }\n }\n return false;\n}", "function storageUserEmail() {\n\n firebase.auth().onAuthStateChanged(function (user) { // Check the user that is logged in\n if (user) {\n db.collection('users')\n .doc(user.uid) // the user's UID\n .get() //READ\n .then(function (doc) {\n var email = doc.data().email; // point to the user's email in the document\n sessionStorage.setItem('email', email); // store the user's email in sessionStorage\n })\n }\n })\n}", "async function emailIsExist(email) {\r\n try {\r\n const user = await User.findOne({\r\n where: {\r\n email,\r\n },\r\n });\r\n if (user) {\r\n return user.toJSON();\r\n }\r\n return false;\r\n } catch (error) {\r\n console.error(error.message);\r\n return false;\r\n }\r\n}", "function addToLocalStorage(){\n var dataString = $(\"#BADefaultEmail\").val();\n localStorage.setItem(\"BADefaultEmail\", dataString );\n alert(\"Default reviewer email saved.\")\n}", "function checkEmail()\r\n{\r\n // sending xml request\r\n let xml = new XMLHttpRequest;\r\n\r\n // function that is called when reply received from server\r\n xml.onreadystatechange = () =>\r\n {\r\n if ((xml.readyState == 4) && (xml.status == 200))\r\n {\r\n let result = JSON.parse(xml.responseText);\r\n\r\n localStorage.clear();\r\n\r\n for (let i = 0; i < result.length; i++)\r\n {\r\n localStorage.setItem(i, JSON.stringify(result[i].email));\r\n } \r\n registerUser();\r\n }\r\n };\r\n\r\n //Send new user data to server\r\n xml.open(\"POST\", \"/allEmails\", true);\r\n xml.setRequestHeader(\"Content-type\", \"application/json\");\r\n xml.send(); \r\n}", "function persistUserToLS(email){\n \n let blogUser;\n \n if(localStorage.getItem('blogUser') !== null){\n blogUser = JSON.parse(localStorage.getItem('blogUser'))\n }else{\n blogUser = [];\n }\n \n if(blogUser.indexOf(email) === -1){\n blogUser.push(email);\n }\n \n localStorage.setItem('blogUser',JSON.stringify(blogUser));\n }", "function checkExistingEmail(email) {\n var flag = false;\n for (let item in databases.users) {\n if(databases.users[item].email === email){\n flag = true;\n userId = databases.users[item].id;\n }\n }\n return flag;\n}", "getLocalStorageUser() {\n return JSON.parse(localStorage.getItem('user'))\n }", "function userFromLocal() {\n let user = localStorage.getItem(\"user\");\n return user;\n}", "function lookUpEmail(email) {\n return new Promise(function (resolve, reject) {\n external_commonjs_vue_commonjs2_vue_root_Vue_default.a.axios.get(\"\".concat(baseURL, \"/users_public?email=\").concat(email)).then(function (data) {\n if (data.data.length) {\n resolve(data.data[0]);\n } else {\n resolve(null);\n }\n }).catch(function (e) {\n console.log('err: ', e);\n reject(e);\n });\n });\n}", "function BALoadFromLocalStorage() {\n $(\"#BAEmail\").val(localStorage.getItem(\"BADefaultEmail\"));\n}", "function checkEmailUniqueness(userData) {\n //Set a toggle w/ a default of TRUE\n var uniqueEmail = true;\n $.get(\"/email\", userData.email)\n .then(function(userList) {\n //Loop through the database emails\n for (var i = 0; i < userList.length; i++) {\n //If there's a match, trigger the validation error & exit the loop\n if (userData.email == userList[i].email) {\n //Show validation <h6> if not unique\n $(\".unique_email\").show();\n console.log(\"This email is already taken\");\n uniqueEmail = false;\n return uniqueEmail;\n break;\n }\n }\n })\n return uniqueEmail;\n }", "function getCurrentEmail(){\n return Session.getActiveUser().getEmail();\n}", "function findUserEmail (email) {\n let found = \"\";\n\n for (let key in users) {\n if (users[key].email === email) {\n found = key\n }\n }\n return found\n}", "function getUserEmail() {\n return firebase.auth().currentUser.email;\n}", "function userForExistingEmail(email) {\n for (let userKey in users) {\n if (users[userKey].email === email) {\n return users[userKey];\n }\n }\n}", "getEmail() {\n const linkedUri = this.getValueFromVcard('hasEmail');\n\n if (linkedUri) {\n return this.getValueFromVcard('value', linkedUri).split('mailto:')[1];\n }\n\n return '';\n }", "function existsEmail(user_input){\n for(let i in users){\n let user = users[i];\n if(user_input === user.email){\n return true;\n }\n }\n return false;\n}", "function ChangeEmail(old_email, new_email) {\n if (!new_email || new_email.length === 0) {\n ShowFormError(\"Email cannot be empty.\");\n return [false, old_email];\n } else if (new_email !== old_email) {\n if (localStorage.getItem(new_email) != null) {\n ShowFormError(\"Email is already taken by another user.\");\n return [false, old_email];\n } else {\n return [true, new_email];\n }\n } else {\n console.log(\n \"No change in user's email. \" + old_email + \" === \" + new_email\n );\n return [true, old_email];\n }\n}", "function getCurrentEmail(){\n\t\t\t\t\t\t\tvar text = document.getElementById(\"userEmail\").value;\n\t\t\t\t\t\t\tconsole.log(text)\n\t\t\t\t\t\t\tcurrentEmail = 'email: ' + text\n\n\t\t\t\t\t\t}", "function emailExist(email) {\n for (let userKey in users) {\n if (users[userKey].email === email) {\n return true;\n }\n }\n return false;\n}", "async function getUserWithMail(email) {\r\n\r\n try {\r\n const userDet = await getDataAsync(`${BASE_URL}/user/mail/${email}`);\r\n if (userDet != null) {\r\n // returns user details \r\n return userDet;\r\n } else {\r\n //returns false if no user found with email\r\n return false;\r\n }\r\n } // catch and log any errors\r\n catch (err) {\r\n console.log(err);\r\n }\r\n}", "function checkLocalStorageData() {\n let email = localStorage.getItem('email');\n let firstName = localStorage.getItem('firstName');\n let lastName = localStorage.getItem('lastName');\n let textarea = localStorage.getItem('textarea');\n if (\n email != null &&\n firstName != null &&\n lastName != null &&\n textarea != null\n ) {\n $('#email').val(email);\n $('#firstName').val(firstName);\n $('#lastName').val(lastName);\n $('#taMessage').val(textarea);\n }\n}", "login() {\n var map = new Map(JSON.parse(localStorage.getItem('userstorage')));\n var user = map.get(this.email);\n if (user == undefined) {\n return \"Invalid\";\n } else if (user.password == this.password) {\n sessionStorage.setItem('login', this.email);\n return true;\n }\n\n return false;\n }", "function checkName(data) {\n let result = userData.find((element) => {\n return (element.email === data.email && element.pass === data.pass)\n });\n if(result){\n localStorage.setItem(\"loggedInUserId\",result.id)\n props.loggedInUser(result)\n history.push('/homes');\n }else{\n alert(\"Incorrect Email or Password\")\n }\n }", "function emailChecker(storedEmail, reqEmail, callback){\n if (storedEmail === reqEmail){\n callback();\n };\n}", "function checkEmail() {}", "async function checkUser() {\n const user = await localStorage.getItem(Current_User);\n return user;\n}", "function isEmailExist() {\n for (var index = 0; index < signUpContainer.length; index++) {\n if ( signUpContainer[index].userEmail.toLowerCase() == signUpEmail.value.toLowerCase() ) {\n return false\n }\n }\n}", "function update_email(){\n\tvar username = localStorage.getItem('username');\n\tvar email = localStorage.getItem('email');\n\tvar newEmail = $(\"#updateemail\").val();\n\tif (email.trim()!==newEmail.trim()){\n\t\temail_check(newEmail).then(function(){\n\t\t\tlet inputs = {\n\t\t\t\t\t\t\temail: newEmail\n\t\t\t\t\t\t};\n\t\t\tlet params = {\n\t\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\t\turl: \"/api/user/edit_email/\"+username,\n\t\t\t\t\t\t\tdata: inputs\n\t\t\t\t\t\t};\n\t\t\t$.ajax(params).done(function(data) {\n\t\t\t\tlocalStorage.setItem('email', newEmail);\n\t\t\t\tdocument.getElementById(\"greetings\").innerHTML = \"Hope that's not a burner email...\";\n\t\t\t\tconsole.log(\"email changed\")\n\t\t\t})\n\t\t}).catch(function (err) {\n\t\t\tconsole.log(err);\n\t\t});\n\t} else {\n\t\tdocument.getElementById(\"greetings\").innerHTML = \"That's the same email tho :C\";\n\t}\n}", "function emailExists(email: string, callback: GenericCallback<boolean>) {\n email = email.toLowerCase();\n getUIDFromMail(email, function (error, username) {\n callback(error, username !== null);\n });\n}", "function dothis(){\r\n var mailformat=/^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/;\r\n if(document.getElementById(\"emailhere\").value==\"\"){\r\n document.getElementById(\"errormsg\").innerHTML=\"Enter a valid Email address\";\r\n document.getElementById(\"popup_container\").style.visibility=\"visible\";\r\n }\r\n else{\r\n if(document.getElementById(\"emailhere\").value.match(mailformat)){\r\n localStorage.setItem(\"email\",document.getElementById(\"emailhere\").value);\r\n window.open(\"loading.html\",\"_self\");\r\n localStorage.setItem(\"time\",\"1500\");\r\n localStorage.setItem(\"link\",\"E-kart_pass.html\");\r\n }\r\n else {\r\n document.getElementById(\"errormsg\").innerHTML=\"Enter a valid Email address\";\r\n document.getElementById(\"popup_container\").style.visibility=\"visible\";\r\n document.getElementById(\"emailhere\").value.focus();\r\n }\r\n }}", "function authEmail(){\r\n let emailvalue=document.querySelector('#email').value;\r\n let passwordvalue=document.querySelector('#password').value;\r\n \r\n //here i set values of email and pass to make user always sign in\r\nif(emailvalue != \"\" && passwordvalue !=\"\"){\r\n window.localStorage.setItem('x',emailvalue); \r\n window.localStorage.setItem('y',passwordvalue);\r\n} \r\n var email=window.localStorage.getItem('x');\r\n var password=window.localStorage.getItem('y');\r\n \r\n firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {\r\n // Handle Errors here.\r\n var errorCode = error.code;\r\n var errorMessage = error.message;\r\n messerr.textContent=errorMessage;\r\n\r\n // ...\r\n })\r\n messerr.textContent='waiting...'\r\n}", "checkLoggedIn() {\n AsyncStorage.getItem(\"userEmail\").then(userEmail => {\n this.setState({ userEmail });\n });\n }", "function checkForUserEmail(data) {\n let sql = \"SELECT id FROM users WHERE email = '\" + data.email + \"'\";\n return db.query(sql);\n}", "function emailLookup(userEmail, users) {\n for (user in users) {\n if (userEmail === users[user][\"email\"]) {\n return true;\n }\n }\n return false;\n}", "function getUsrName() {\n //if (!isUsrTokenValid()) {\n // return \"\";\n //}else\n return localStorage.getItem(\"usrName\");\n}", "function getUserLocal(){\n try\n {\n return LocalStorage.getObject(Constants.USER);\n \n }\n catch(err)\n {\n return {};\n }\n }", "isEmailInUse(email) {\n return __awaiter(this, void 0, void 0, function* () {\n if (email == null) {\n throw new nullargumenterror_1.NullArgumentError('email');\n }\n return this.users.find(u => u.email == email) != null;\n });\n }", "function emailChecker (email) {\n for (id in users){\n if (email === users[id].email){\n return true;\n }\n }\n return false;\n}", "async function getUserData(email) {\n const values = await AsyncStorage.getItem(`api/patient/${email}`);\n const userData = JSON.parse(values);\n\n if (userData.patientId) return userData;\n return {};\n}", "getUserIdByEmail(email) {\n this.email = email;\n let myId;\n const userData = this.app.readDataFile(userFilePath);\n\n userData.forEach((item) => {\n if (item.email === this.email) {\n myId = item.id;\n }\n });\n\n return myId;\n }", "function checkEmail () {\n var scriptProps = PropertiesService.getScriptProperties();\n var myEmail = scriptProps.getProperty('userEmail');\n if (myEmail == null) {\n return '✗ You still need to set up your email address. Go to 🔍 Career Hacking™ > 📧 Set Email Address.';\n } else {\n return 'Your follow-up reminders will be send to ' + myEmail + '. To have them sent to a different address, go to\\n🔍 Career Hacking™ > 📧 Set Email Address.'\n } \n}", "findMail()\n{\n let mail = '';\n let loginEmail = Cookie.load('email');\nlet uname = document.getElementById('users');\n// let uname = '';\n let userNames = this.state.userNames;\n // console.log(userNames.length);\n for(let i = 0; i < userNames.length; i = i + 1)\n {\n if(userNames[i].name === uname.value && userNames[i].email !== loginEmail)\n {\n mail = userNames[i].email;\n break;\n }\n }\n // console.log(mail);\n this.sendInvite(mail);\n}", "function checkUser(usersDB, email) {\n for (let user in usersDB) {\n if (usersDB[user].email === email) {\n return usersDB[user];\n }\n }\n return null;\n}", "getEmail() {}", "async isEmailExist(email, role) {\n let query = '';\n const data = [];\n this.email = email;\n this.role = role;\n data.push(this.email);\n\n switch (this.role) {\n case constants.USER:\n query = 'SELECT id_user FROM users WHERE email = $1';\n break;\n case constants.ADMIN:\n query = 'SELECT id_admin FROM admin WHERE email = $1';\n break;\n default:\n query = 'SELECT id_user FROM users WHERE email = $1';\n break;\n }\n\n const result = await execute(query, data);\n return result.rowCount > 0;\n }", "function altroUtente(offerta){\r\n return (offerta.ospitato === JSON.parse(localStorage.utente).username)?offerta.ospitante:offerta.ospitato;\r\n}", "function GetCustomerInfo(){\n if(ValidateEmail(document.querySelector('#userEmail').value)){\n localStorage.clear();\n let email = document.querySelector('#userEmail').value;\n let url = 'https://localhost:5001/MainMenu/get/' + email;\n fetch(url)\n .then(result=> result.json())\n .then(result=>\n {if(result.id == 0){\n alert(\"No Customer with the email\");\n } else{\n \n CustomerLocal(result);\n }\n });\n}}", "function getEmailToView() {\r\n //emailToView JSON set up by the viewEmail Function\r\n var key = JSON.parse(localStorage.getItem(\"emailToView\")).key;\r\n var index = JSON.parse(localStorage.getItem(\"emailToView\")).index;\r\n\r\n //Make email no longer bold\r\n var json = JSON.parse(localStorage.getItem(key));\r\n var emails = json.emails; \r\n emails[index].read = \"read\"; \r\n\r\n //Places the email back, NO LONGER BOLD\r\n localStorage.setItem(key, JSON.stringify(json));\r\n return emails[index]; //Returns the email JSON to be viewed.\r\n}", "getEmail(){\n \treturn this.email.getEmailFromHeader();\n \t//return this.state.value;\n }", "function isCorrect(){\n for (var index = 0; index < signUpContainer.length; index++) {\n if ( signUpContainer[index].userEmail == logInEmail.value && signUpContainer[index].userPass == logInPass.value ) {\n\n currentName = signUpContainer[index].userName ; //store name of user \n localStorage.setItem(\"name\" , JSON.stringify(currentName)) ; //store name of user in local storage\n \n return true;\n }\n }\n}", "async function checkEmail(email) {\n const accountUser = await db('users')\n .where({\n email\n })\n .first()\n .catch(console.log)\n\n const accountOrg = await db('organizations')\n .where({\n email\n })\n .first()\n .catch(console.log)\n\n if (!accountUser && !accountOrg) {\n return false\n }\n return (accountUser.email === email || accountOrg.email === email) ? true : false\n}", "function getUserWithEmail(email) {\n const matchingId = Object.keys(users).filter(userId => {\n return users[userId].email === email;\n })[0];\n return users[matchingId];\n}", "function isEmailTaken(){\n return new Promise(function(resolve, reject){\n mysql.pool.getConnection(function(err, connection){\n if(err){return reject(err)};\n\n connection.query({\n sql: 'SELECT email FROM deepmes_auth_login WHERE email=?',\n values: [fields.email+'@sunpowercorp.com']\n }, function(err, results){\n if(err){return reject(err)};\n\n if(typeof results[0] !== 'undefined' && results[0] !== null && results.length > 0){\n let emailTaken = 'Email is already taken.';\n reject(emailTaken);\n } else {\n resolve();\n }\n\n });\n\n connection.release();\n\n });\n });\n }", "function checkEmail(email) {\n for (let id in users) {\n if (email === users[id].email)\n return true;\n }\n return false;\n}", "function checkBorrowerExists() {\n console.log(\"Function called\");\n let data = {\n userEmail: document.getElementById('email').value,\n userPassword: document.getElementById('password').value\n }\n\n axios.post(baseUrlLocal+'/login',data, {headers: headers})\n .then(response => {\n \n console.log(response.data.info);\n console.log(response.data.info[0]);\n console.log(response.data.info[0].Email);\n if(response.data.success){ \n let user_info = {\n userData: response.data.info[0]\n \n }\n console.log(user_info)\n localStorage.setItem(USER_INFO, JSON.stringify(user_info)); \n if(data.userEmail == \"[email protected]\"){\n window.location.href = \"returned_books.html\";\n }\n else{\n window.location.href = \"user_dashboard.html\";\n }\n }else{\n $.notify(\"Invalid login credentials\",\"warn\");\n }\n })\n .catch(error => {\n $.notify(\"Invalid login credentials\",\"warn\");\n \n console.log(error);\n })\n}", "function welcome() {\n var welc = localStorage.getItem(\"email\");\n document.getElementById(\"welcomeUser\").innerHTML = welc;\n}", "function get_email(){\n\t$email_label_el = $(\"td.label\").filter(\":contains('Email:')\")\n\tconsole.assert($email_label_el && $email_label_el.length == 1, \"email label could not be found or length > 1\")\n\tconsole.log($email_label_el)\n\n\temail_data = $email_label_el.next().text()\n\tconsole.assert(email_data, \"Could not extract Email data\")\n\tconsole.log(\"Email is: \" + email_data)\n\n\treturn email_data\n}", "function saveSettings() {\n\tvar ttc_email = $('#txtEmail').val();\n\t\n\t//take the input value and store it\n localStorage.setItem(\"ttcemail\", ttc_email);\n\t\n\t//retrieve the storage, just to be sure!\n\tvar check_storage = localStorage.getItem(\"ttcemail\");\n\t////alert (\"The NEW storage is \"+check_storage);\n\t\n\t//Now run a check on it and display as appropriate\n\tcheck_credentials (check_storage);\n return false;\n}", "getUser(email) { \n return listUsers.find(item => item.email === email);\n }", "function emailToId(input) {\n for (let id in users) {\n if (users[id].email === input) {\n return id;\n };\n };\n return false;\n}", "function getLocalStorageUsername() {\n\n const username = JSON.parse(localStorage.getItem(\"username\"));\n // turn object into array to use foreach function and display tasks\n\n return username;\n}", "function getUserId (email) {\n for (let key in users) {\n if (users[key]['email'] === email) {\n return users[key].id\n }\n }\n return false\n}", "function checkEmail(email) {\n if (email === \"null\");\n return \"\";\n }", "function notify(){\n sendEmail().then(function(good){\n let itemName = document.getElementById(\"itemName\").value;\n let storeName = localStorage.getItem(\"locationName\");\n console.log(itemName);\n console.log(storeName);\n }).catch(function(error){\n console.log(error)\n });\n}", "function getLocalStorage() {\n return JSON.parse(localStorage.getItem(\"user\")) \n}", "getUser() {\n const user = localStorage.getItem(\"user\") || null\n return user ? JSON.parse(user) : null\n }", "function afficherEmail() {\n return isValidEmail(email.value);\n}", "getUserByEmail(email) {\n const stmt = this.db.prepare(\"SELECT * FROM users WHERE email = ?\");\n return stmt.get(email);\n }", "isUserDetailsExists(email) {\n return new Promise(function (resolve, reject) {\n let sql = \"SELECT email FROM personal_details WHERE email=?\";\n db.all(sql, [email], (err, rows) => {\n if (err) {\n reject(Error(\"Error:\" + err.message));\n }\n if (rows.length > 0) {\n resolve(true);\n } else {\n resolve(false);\n }\n });\n });\n }", "function emailSearch(emailIn) {\n for (id in users) {\n if (users[id].email == emailIn){\n return true;\n }\n }\n return false;\n}", "async function checkFirst(email) {\n try {\n email = decodeURIComponent(email);\n const results = await User.find({ email: email });\n if (results.length == 0) {\n return true;\n } else {\n return false;\n }\n } catch (err) {\n console.log(err.response);\n }\n}", "function getUserData(userName) {\n\t\tvar checkUser = localStorage.getItem(userName);\n\t\tif (checkUser) {\n\t\t\t//user exists get data and return \n\t\t\tvar retreivedUser = JSON.parse(checkUser);\n\t\t\treturn retreivedUser;\n\n\t\t} else {\n\t\t\t//user doesn't exist return false\n\t\t\treturn false;\n\t\t}\n\t}", "function getFacebookUserLocal(){\n try\n {\n return LocalStorage.getObject(Constants.USER_FACEBOOK);\n \n }\n catch(err)\n {\n return {};\n }\n }", "function findByEmail(email, callback) {\n var sql_search_by_email = 'select id, email, nickname, gender, text, imagepath, need, ' +\n 'position_id, genre_id, city_id, town_id, password ' +\n 'from user ' +\n 'where email = ?';\n\n var user = {};\n\n if (email === undefined) {\n return callback(null, null);\n }\n else {\n dbPool.getConnection(function (err, dbConn) {\n if (err) {\n return callback(err);\n } else {\n dbConn.query(sql_search_by_email, [email], function (err, result) {\n dbConn.release();\n if (err) {\n return callback(err);\n } else {\n if (result[0] === undefined) {\n // no such email\n callback(new Error('there is no user have such email'));\n } else {\n user.id = result[0].id;\n user.email = result[0].email;\n user.nickname = result[0].nickname;\n user.gender = result[0].gender;\n user.text = result[0].text;\n user.imagepath = result[0].imagepath;\n user.position_id = result[0].position_id;\n user.genre_id = result[0].genre_id;\n user.city_id = result[0].city_id;\n user.town_id = result[0].town_id;\n user.need = result[0].need;\n user.password = result[0].password;\n callback(null, user);\n }\n }\n });\n }\n });\n }\n}", "function retrieveUserByEmail(email, callback) {\n retrieveUserByQuery({\"email\": email}, callback);\n}", "function getSpecificUser(email, data)\n{\n\tvar user = null;\n\tfor (var i = 0; i < data.length; i++) \n\t{\n\t\tif (data[i].key == email) {\n\t\t\tuser = data[i].value;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn user;\n}", "get userName () {\n return window.localStorage['userName'] || null\n }", "function findUser(email) {\n const user = users.filter(user => user.email === email)\n return user[0]\n }", "getEmail() {\n \n return this.email;\n }", "function checkLogin() {\n if (\"ActiveUser\" in localStorage) {\n return true\n } else {\n return false\n }\n}", "function checkIfLogedin(){\n let logedIn = localStorage.getItem(\"logedIn\");\n if(logedIn !== undefined && logedIn !== null ){\n let input = document.getElementById(\"loginInput\");\n input.value = JSON.parse(localStorage.getItem(\"logedIn\")).personnr;\n loginOnClick();\n }\n}", "async validateEmailInput() {\n this.baseEl.find('.email-exists').removeClass('on');\n this.baseEl.find('.email-invalid').removeClass('on');\n\n let email = this.baseEl.find('.email-input').val();\n\n let result = await User.find(`.findOne({email: '${email}'})`);\n if (result) {\n this.baseEl.find('.email-exists').addClass('on');\n return false;\n }\n let regEx = /\\w\\w+@\\w\\w+\\.\\w\\w+/;\n if (!regEx.test(email)) {\n this.baseEl.find('.email-invalid').addClass('on');\n return false;\n }\n return true;\n }", "function loginReturn(loginEmail) {\n for (key in users) {\n if (users[key].email == loginEmail){\n return users[key].id;\n }\n }\n return null;\n}", "function getUserContactState(userEmail) {\n for(var i = 0; i < contactList.length; i++) {\n var oneUser = contactList[i];\n if(oneUser.email == userEmail) {\n return contactList[i].state;\n }\n }\n\n return \"NOT_EXIST\";\n}" ]
[ "0.7614653", "0.7370305", "0.7315754", "0.67491454", "0.6708699", "0.66201174", "0.6543067", "0.652607", "0.64364916", "0.64181274", "0.640039", "0.63077223", "0.6306384", "0.6305968", "0.6297027", "0.62538064", "0.62161314", "0.6205636", "0.61839736", "0.61826116", "0.6177238", "0.6172594", "0.6170813", "0.61616373", "0.61392194", "0.61281353", "0.61277986", "0.6111037", "0.6096957", "0.609558", "0.60955656", "0.60796815", "0.6069936", "0.60671926", "0.6067108", "0.60649365", "0.6052809", "0.6041847", "0.60393274", "0.6036649", "0.6012766", "0.6011121", "0.5995475", "0.59931993", "0.5974916", "0.5967843", "0.59612274", "0.594076", "0.5939762", "0.59367836", "0.59344864", "0.5932997", "0.59314615", "0.5922255", "0.5917451", "0.5907859", "0.59074205", "0.59002143", "0.5894501", "0.589338", "0.5892952", "0.58917856", "0.58863944", "0.58777", "0.5861623", "0.58606046", "0.58287567", "0.5826555", "0.5824989", "0.58202994", "0.581849", "0.5817968", "0.58091146", "0.58085716", "0.58072996", "0.58015484", "0.58007574", "0.5794317", "0.57880867", "0.5786227", "0.57800245", "0.57736146", "0.57702017", "0.576833", "0.574981", "0.5733975", "0.57329726", "0.5728555", "0.5724242", "0.57083565", "0.57078797", "0.5706603", "0.5699989", "0.56948775", "0.5694434", "0.56933755", "0.5685434", "0.56786966", "0.567554", "0.56746584" ]
0.88203657
0
getRecipesFromLocalStorage function gets the saved recipes from local storage, it returns false if value is not found in local storage. recipe is stored as recipe in local storage
function getRecipesFromLocalStorage() { if (localStorage.getItem("recipes")) { recipes = localStorage.getItem("recipes"); return JSON.parse(recipes); } else { return false; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "getData() {\n var data = [];\n if (typeof(Storage) !== \"undefined\") {\n data = localStorage.getItem(\"recipes\");\n if (data !== null) {\n data = JSON.parse(data);\n } else {\n data = mockData;\n }\n } else {\n console.log(\"WARNING: no local storage, cannot save recipes.\");\n }\n// DEBUG: dump the contents of localStorage\n//console.log(data);\n return data;\n }", "function setRecipeFromLocalStorage(recipe) {\n var recipes = localStorage.getItem(\"recipes\");\n recipes = JSON.parse(recipes);\n console.log(recipes);\n console.log(recipe + \" to be added\");\n if (recipes == null) {\n var recipes = [];\n recipes[0] = recipe;\n console.log(recipes);\n var index = 1;\n localStorage.setItem(\"length\", index);\n } else {\n var index = localStorage.getItem(\"length\");\n recipes[index++] = recipe;\n console.log(recipes);\n console.log(index);\n localStorage.setItem(\"length\", index);\n }\n localStorage.setItem(\"recipes\", JSON.stringify(recipes));\n}", "saveRecipe() {\n // read recipes is none -> create recipes\n let recipes = localStorage.getItem(\"recipes\")\n let info = {\n title: shortTxt(this.recipe.title),\n publisher: this.recipe.publisher,\n image_url: this.recipe.image_url,\n recipe_id: this.recipe.recipe_id,\n }\n if (!recipes) {\n localStorage.setItem(\"recipes\", JSON.stringify([info]))\n } else {\n let data = JSON.parse(recipes)\n if (data.map(info_ => info_.recipe_id).includes(info.recipe_id)){\n // delete rid\n data = data.filter(info_ => info_.recipe_id !== info.recipe_id)\n console.log(data)\n } else{\n // add rid\n data.push(info)\n }\n localStorage.setItem(\"recipes\", JSON.stringify(data))\n }\n }", "function initializeRecipes(){\n\t\t\t\t\t\t\t\n\n\n\tvar arrayofrecipes = [];\n\tObject.keys(localStorage).map((key,index)=>{\n\t\tarrayofrecipes.push({index:index,title:key,ingredient:localStorage[key]})\n\t})\n\treturn arrayofrecipes;\n}", "function fetchLocalStorage() {\n // FETCHING LOCAL STORAGE\n let fromLocalStorage = JSON.parse(localStorage.getItem(\"myBooks\"));\n // IF WE GOT SOMETHING FROM LOCAL STORAGE WE ADD IT TO myBooks ARRAY\n if (fromLocalStorage) {\n myBooks = fromLocalStorage;\n }\n}", "function pullLocalFoods() {\n var foodList = localStorage.getItem(\"foods\");\n if (localStorage.getItem(\"foods\") === null) {\n return;\n } else {\n foods = foodList.split(\",\");\n }\n for (var k = 0; k < foods.length; k++) {\n addContainer();\n }\n setFoods(foods);\n}", "static getFoods() {\n let items;\n // Check if storage has foods \n if (localStorage.getItem('foods') === null) {\n items = [];\n } else {\n items = JSON.parse(localStorage.getItem('foods'));\n }\n\n return items;\n }", "function restoreFromLocalStorage() {\r\n if(localStorage.getItem(`trip${tripId}`) && tripId) {\r\n const savedCheckboxesJSON = localStorage.getItem(`trip${tripId}`);\r\n const savedCheckboxes = JSON.parse(savedCheckboxesJSON);\r\n $('.items li').each(function() {\r\n if(savedCheckboxes.includes( $(this).find('label').text() )) {\r\n $(this).find($checkboxes).prop('checked', true);\r\n }\r\n });\r\n }\r\n}", "function returnallfromlocalstorage() {\n console.log(\"Step 5\");\n return JSON.parse(localStorage.getItem(\"allthings\"));\n}", "function ReceitasFavoritas() {\n // const favoriteRecipes = JSON.parse(localStorage.favoriteRecipes);\n const [favoriteRecipes, setFavoriteRecipes] = useState([]);\n const [isFavorite, setIsFavorite] = useState(true);\n const { recipeMeal } = useContext(MealsContext);\n const { id } = useParams();\n /* const timeoutTextCopy = 2000;\n const [isCopied, handleCopy] = useCopyToClipboard(timeoutTextCopy); */\n useEffect(() => {\n if (!localStorage.favoriteRecipes) {\n return <p>Você ainda não tem nenhuma receita pronta.</p>;\n }\n setFavoriteRecipes(JSON.parse(localStorage.favoriteRecipes));\n }, []);\n const filterRecipes = ({ innerText }) => {\n if (innerText === 'Food') {\n const newDone = favoriteRecipes.filter((done) => (\n done.type === 'comida'\n ));\n setFavoriteRecipes(newDone);\n } else if (innerText === 'Drinks') {\n const newDone = favoriteRecipes.filter((done) => (\n done.type === 'bebida'\n ));\n setFavoriteRecipes(newDone);\n } else {\n setFavoriteRecipes(JSON.parse(localStorage.favoriteRecipes));\n }\n };\n console.log('testRecipemelas', recipeMeal);\n function FavoriteRecipeClick() {\n // eslint-disable-next-line no-shadow\n const favoriteRecipesC = JSON.parse(localStorage.getItem('favoriteRecipes'));\n if (favoriteRecipesC !== null) {\n if (isFavorite) {\n console.log('ok', recipeMeal);\n const arrayFavoriteRecipe = favoriteRecipesC.filter((item) => item.id !== id);\n localStorage.setItem('favoriteRecipes', JSON.stringify(arrayFavoriteRecipe));\n setIsFavorite(false);\n } else {\n const newFavoriteRecipe = {\n id: recipeMeal.idMeal,\n type: 'comida',\n area: recipeMeal.strArea,\n category: recipeMeal.strCategory,\n alcoholicOrNot: '',\n name: recipeMeal.strMeal,\n image: recipeMeal.strMealThumb,\n };\n const arrayFavoriteRecipe = [...favoriteRecipes, newFavoriteRecipe];\n localStorage.setItem('favoriteRecipes', JSON.stringify(arrayFavoriteRecipe));\n setIsFavorite(true);\n }\n }\n }\n\n return (\n <>\n <Header />\n <button\n className=\"button-all\"\n type=\"button\"\n data-testid=\"filter-by-all-btn\"\n onClick={ ({ target }) => { filterRecipes(target); } }\n >\n All\n </button>\n <button\n type=\"button\"\n data-testid=\"filter-by-food-btn\"\n onClick={ ({ target }) => { filterRecipes(target); } }\n >\n Food\n </button>\n <button\n className=\"button-drink\"\n type=\"button\"\n data-testid=\"filter-by-drink-btn\"\n onClick={ ({ target }) => { filterRecipes(target); } }\n >\n Drinks\n </button>\n {favoriteRecipes.map((recipe, index) => (\n <div key={ index }>\n <Link\n to={ recipe.type === 'bebida' ? `/bebidas/${recipe.id}`\n : `/comidas/${recipe.id}` }\n >\n <p data-testid={ `${index}-horizontal-name` }>\n { recipe.name }\n </p>\n <img\n src={ recipe.image }\n alt={ recipe.name }\n data-testid={ `${index}-horizontal-image` }\n />\n </Link>\n <p data-testid={ `${index}-horizontal-top-text` }>\n { recipe.type === 'comida' ? `${recipe.area} - ${recipe.category}`\n : `${recipe.alcoholicOrNot} - ${recipe.category}` }\n </p>\n {console.log(recipe)}\n <button\n data-testid={ `${index}-horizontal-share-btn` }\n type=\"button\"\n src={ shareIcon }\n >\n <img\n src={ shareIcon }\n alt=\"Compatilhar Receita\"\n />\n </button>\n <button\n data-testid={ `${index}-horizontal-favorite-btn` }\n type=\"button\"\n onClick={ FavoriteRecipeClick }\n src={ isFavorite ? blackIcon : whiteIcon }\n >\n <img\n src={ isFavorite ? blackIcon : whiteIcon }\n alt=\"Desfavoritar Receita\"\n />\n </button>\n <p data-testid={ `${index}-horizontal-done-date` }>\n { recipe.category }\n </p>\n </div>\n ))}\n </>\n );\n}", "function revisarLocalStorage() {\n let productos;\n //Revisar Valores de local Storage\n if (localStorage.getItem('productos') === null) {\n productos = [];\n } else { \n productos = JSON.parse(localStorage.getItem('productos') );\n }\n return productos;\n}", "function foodRecipes() \n{\n var myFood = JSON.parse(localStorage.getItem(\"myFood\"))\n console.log(myFood);\n\n // Loop through the local storage array and create cards for the recipes\n for (let i = 0; i < myFood.length; i++) \n {\n // Create the divs and add the classes / attributes\n let foodCardDiv = $(\"<div>\").addClass(\"col s12 m6 xl4 recipe\");\n let imgCardDiv = $(\"<div>\").addClass(\"card large hoverable\");\n let imgDiv = $(\"<div>\").addClass(\"card-image waves-effect waves-block waves-light\");\n let recipeImg = $(\"<img>\").attr(\"src\", myFood[i][\"img\"]).addClass(\"activator\");\n let recipeTitleDiv = $(\"<div>\").addClass(\"card-content\");\n let titleDivSpan = $(\"<span>\").addClass(\"card-title grey-text text-darken-4\");\n let showRecipe = $(\"<i>more_vert</i>\").addClass(\"s1 material-icons right activator\");\n let recipeTitle = $(\"<h5>\" + myFood[i][\"label\"] + \"</h5>\").addClass(\"s9\");\n let recipeDiv = $(\"<div>\").addClass(\"card-reveal\");\n let recipeDivSpan = $(\"<span>\" + myFood[i][\"label\"] + \"</span>\").addClass(\"card-title grey-text text-darken-4\");\n let closeRecipe = $(\"<i>\" + \"close\" + \"</i>\").addClass(\"material-icons right\");\n let recipeHeader = $(\"<h6>Recipe:</h6>\");\n let recipeText = $(\"<p> Find out how to cook this dish: <a href=\" + myFood[i][\"url\"] + \" target='_blank'>\" + myFood[i][\"url\"] + \"</p>\");\n \n // Append the divs to the container\n\n titleDivSpan.append(showRecipe);\n recipeDiv.append(recipeDivSpan);\n recipeDivSpan.append(closeRecipe);\n recipeTitleDiv.append(titleDivSpan);\n recipeTitleDiv.append(recipeTitle);\n imgDiv.append(recipeImg);\n imgCardDiv.append(imgDiv);\n imgCardDiv.append(recipeTitleDiv);\n imgCardDiv.append(recipeDiv);\n foodCardDiv.append(imgCardDiv);\n recipeDiv.append(recipeHeader);\n recipeDiv.append(recipeText);\n \n $(\"#myRecipes\").append(foodCardDiv); \n }\n}", "function getLocalStorage() {\n if (localStorage.myLibrary !== \"[]\" && localStorage.myLibrary) {\n bookIdCount = JSON.parse(localStorage.bookIdCount);\n myLibrary = JSON.parse(localStorage.myLibrary)\n };\n}", "function obtenerProductosLocalStorage() {\r\n let productosLS;\r\n\r\n //comprobamos si hay algo en localStorage con if/else\r\n if (localStorage.getItem(\"productos\") === null) {\r\n productosLS = [];\r\n } else {\r\n productosLS = JSON.parse(localStorage.getItem(\"productos\"));\r\n }\r\n return productosLS;\r\n}", "function getRecipeData(e) {\n var getMealData = JSON.parse(localStorage.getItem(\"meal\"));\n var mealId = e.target.getAttribute(\"data-id\");\n var selected = getMealData.filter((meal) => meal.idMeal === mealId);\n\n if (selected.length > 0) {\n selected = selected[0];\n }\n hideRecipe.classList.remove(\"hidden\");\n foodPoster.src = selected.strMealThumb;\n foodTitle.innerText = selected.strMeal;\n methodText.innerText = selected.strInstructions;\n\n const ingredients = [];\n for (let i = 1; i <= 20; i++) {\n if (selected[`strIngredient${i}`]) {\n ingredients.push(\n `${selected[`strMeasure${i}`]} - ${selected[`strIngredient${i}`]}`\n );\n } else {\n break;\n }\n }\n ingredientEl.innerHTML = `${ingredients\n .map((ingredients) => `<li>${ingredients}</li>`)\n .join(\"\")}`;\n}", "function searchRecipe(searchCriterias) {\n let ingredients = searchCriterias.ingredients.toString();\n let cuisines = searchCriterias.cuisines.toString();\n let diet = searchCriterias.diet.toString();\n let allergies = searchCriterias.allergies.toString();\n\n fetch(url + \"recipes/complexSearch?apiKey=\" + apikey + \"&cuisine=\" + cuisines + \"&diet=\" + diet + \"&intolerances=\" + allergies + \"&includeIngreients=\" + ingredients + \"&includeIngreients=10&sort=popularity&sortDirection=asc&minFat=0&minProtein=0&minCalories=0&instructionsRequired=true\")\n .then(function (response) {\n return response.json();\n })\n .then(function (data) {\n console.log(data);\n $(data.results).each(function (index) {\n let recipe = {\n id: \"\",\n title: \"\",\n image: \"\",\n fat: \"\",\n protein: \"\",\n calories: \"\"\n };\n recipe.id = data.results[index].id;\n recipe.title = data.results[index].title;\n recipe.image = data.results[index].image;\n recipe.calories = data.results[index].nutrition.nutrients[0].amount +\n data.results[index].nutrition.nutrients[0].unit;\n recipe.protein = data.results[index].nutrition.nutrients[1].amount +\n data.results[index].nutrition.nutrients[1].unit;\n recipe.fat = data.results[index].nutrition.nutrients[2].amount +\n data.results[index].nutrition.nutrients[2].unit;\n localSearchedRecipes.push(recipe);\n });\n localStorage.setItem(\"searchedRecipies\", JSON.stringify(localSearchedRecipes));\n window.location = './recipe_list.html';\n })\n}", "function checkLocal(){\n if(localStorage.getItem('todos') === null){\n return todos = [];\n }else{\n return todos= JSON.parse(localStorage.getItem('todos'));\n }\n}", "function getSavedRecipes() {\n $.get(\"/api/recipes/saved\", function (data) {\n if (!data) {\n return;\n }\n renderSavedRecipes(data);\n });\n}", "function checkLocalStorage(string) {\n\t\tif (localStorage.getItem(string + '_list') === 'true') {\n\t\t\treturn true;\n\t\t} else {\n\t\t\tvar alternatives = [];\n\t\t\tfor (var i = 0; i < localStorage.length; i++) {\n\t\t\t\tvar key = localStorage.key(i);\n\n\t\t\t\t//we check for any key that returns true... since that was our check initially.\n\t\t\t\tif (localStorage.getItem(key) === 'true') {\n\t\t\t\t\tvar string = key.replace('_list', '');\n\t\t\t\t\talternatives.push(string);\n\t\t\t\t\tdelete string;\n\t\t\t\t}\n\t\t\t\t// key = NULL;\n\t\t\t\tdelete key;\n\t\t\t}\n\t\t\talert('did you mean something else? maybe the following: \\n' + alternatives.toString());\n\t\t\treturn false;\n\t\t}\n\t}", "function checkLocalStorage() {\n if (localStorage.length > 0) {\n let arr = localStorage.getItem('savedLibrary');\n let retrievedLibrary = JSON.parse(arr);\n for (let i = 0; i < retrievedLibrary.length; i++) {\n let newBookObject = new Book(retrievedLibrary[i].title, retrievedLibrary[i].author, retrievedLibrary[i].numOfPages, retrievedLibrary[i].readStatus);\n addBookToLibrary(newBookObject);\n } return displayBook(myLibrary);\n }\n}", "function loadFavoritesFromLocalStorage() {\n favorites = getFromLocalStorage(\"favorites\");\n}", "function ifExistsTodos(){\r\n let todos;\r\n if(localStorage.getItem('todos') === null){\r\n todos = []\r\n }else{\r\n todos = JSON.parse(localStorage.getItem('todos'));\r\n }\r\n return todos;\r\n}", "saveNewRecipe() {\n if (this.state.newestRecipe.recipeName && this.state.newestRecipe.ingredients) {\n let recipes = this\n .state\n .recipes\n .slice();\n recipes.push({recipeName: this.state.newestRecipe.recipeName, ingredients: this.state.newestRecipe.ingredients});\n localStorage.setItem(\"recipes\", JSON.stringify(recipes));\n this.setState({recipes});\n this.setState({\n newestRecipe: {\n recipeName: \"\",\n ingredients: []\n }\n })\n }\n this.close();\n }", "deleteRecipe(rid) {\n // read recipes delete rid\n let data = JSON.parse(localStorage.getItem(\"recipes\"))\n data = data.filter(info => info.recipe_id !== rid)\n localStorage.setItem(\"recipes\", JSON.stringify(data))\n }", "function getLS() {\n // console.log(JSON.stringify(localStorage));\n if (localStorage.getItem(\"searchedCities\") === null ||\n localStorage.getItem(\"searchedCities\") === \"\"){\n searchedCities = [];\n } else {\n searchedCities = JSON.parse(localStorage.getItem(\"searchedCities\"));\n }\n console.log(searchedCities)\n}", "function getDataFromLocalStorage(){\n let data = JSON.parse(localStorage.getItem('restaurant'))\n selectedRestaurant(data)\n }", "async function searchLocal() {\n if (localStorage.getItem(\"tasks\") != null && localStorage.getItem(\"tasks\") != undefined) {\n tasks = JSON.parse(await localStorage.getItem(\"tasks\"));\n createList();\n }\n}", "function getFavoritesLocalStorage() {\n // el array de favoritos tendrá lo que tenga el localStorage\n let favorites = JSON.parse(localStorage.getItem('favs'));\n // si me devuelve un array de favoritos distinto a nulo, entonces duélveme array favorites, sino devuélveme aunque sea el array vacío\n if (favorites !== null) {\n return favorites;\n } else {\n return (favorites = []);\n }\n}", "obtenerProductosLocalStorage(){\n let productoLS;\n\n if(localStorage.getItem('productos') === null){\n productoLS = [];\n }\n else {\n productoLS = JSON.parse(localStorage.getItem('productos'));\n }\n return productoLS;\n }", "obtenerProductosLocalStorage(){\n let productoLS;\n\n //Comprobar si hay algo en LS\n if(localStorage.getItem('productos') === null){\n productoLS = [];\n }\n else{\n productoLS = JSON.parse(localStorage.getItem('productos'));\n }\n return productoLS; \n }", "function getLocalStorage() {\n return localStorage.getItem('list')\n ? JSON.parse(localStorage.getItem('list'))\n : [];\n}", "function obtenerProductoLocalStorage() {\n let productos;\n if (localStorage.getItem(\"productos\") === null) {\n // si el LocalStorage no tiene elementos, retorna un array vacio.\n // if LocalStorage hasn't elements, return a empty array. \n productos = [];\n }else {\n // retorna un array con los productos.\n // return an array with the articles.\n productos = JSON.parse( localStorage.getItem(\"productos\") );\n }\n\n // retorna productos (array), vacíos o no.\n // return productos (array), empty or not.\n return productos;\n}", "function checkCityList() {\n cityList = localStorage.getItem(\"cityList\");\n\n if (cityList === null) {\n // There is no list of cities in local storage, so set variable to empty\n cityList = [];\n } else {\n // City List already existed in local storage, so read in and display\n cityList = JSON.parse(cityList);\n displayCityList();\n }\n\n}", "function getAllFromLocalStorage() {\n const val = JSON.parse(localStorage.getItem(LOCALSTORAGE_KEY))\n return val || []\n}", "function getSavedRecipes() {\n $.get(\"/api/recipes/saved\", function (data) {\n // console.log(data);\n if (!data) {\n return;\n }\n renderSavedRecipes(data);\n });\n}", "function getItemLocalStorage(){\n let todos\n\n if(localStorage.getItem(\"todos\") == null){\n todos = []\n } else {\n todos = JSON.parse(localStorage.getItem(\"todos\"))\n }\n\n return todos\n}", "function loadFromStorage() {\n var favs = storage.getItem(\"favs\");\n if (favs) {\n favs = JSON.parse(favs);\n } else {\n favs = [];\n }\n return favs;\n }", "function getRecipes () {\n setRecipes(recipesData)\n }", "function checkAndRestore() {\n if (localStorage.length > 0) {\n itemsArray = JSON.parse(localStorage.getItem('itemsData'));\n }\n}", "function fetchLocalStorage() {\n // CONVERTING LOCAL STORAGE STRING THAT STORE OUR LEADS AND PUSH IT IN myLeads ARRAY\n const leadsFromLocalStorage = JSON.parse(localStorage.getItem(\"myLeads\"));\n // CHECKING IF WE GOT SOMETHING FROM LOCAL STORAGE\n if (leadsFromLocalStorage)\n {\n myLeads = leadsFromLocalStorage;\n render(myLeads);\n }\n}", "function getDataFromLocalStorage(){\n var students = JSON.parse(localStorage.getItem(\"students\"));\n return students;\n \n }", "function localStorageCategorySearch(category) {\n let search = [],\n keys = Object.keys(localStorage),\n i = 0, key;\n\n for (; key = keys[i]; i++) {\n let item = JSON.parse(localStorage.getItem(key));\n if(item.category == category) {\n search.push(key);\n }\n }\n\n // If items are found return their key array, else return false\n if(search.length > 0) {\n return search;\n } else {\n return false;\n }\n}", "function getFromLocalStorage() {\n const reference = localStorage.getItem('todos');\n // if reference exist\n if (reference) {\n // converts back to arr and store it in todos arr\n todos = JSON.parse(reference);\n renderTodos(todos);\n }\n}", "function checkTweetsLocalStorage() {\n let tweets;\n if (localStorage.getItem('tweets') === null) {\n tweets = [];\n } else {\n tweets = JSON.parse(localStorage.getItem('tweets'));\n }\n return tweets;\n}", "function getLocalStorage() {\n var storage = JSON.parse(localStorage.getItem(\"cities\"));\n if (storage !== null) {\n citiesArray = storage;\n }\n }", "function getLocalStorage() {\n const localStorageFavorites = localStorage.getItem(\"favorites\");\n if (localStorageFavorites !== null) {\n favoritesList = JSON.parse(localStorageFavorites);\n }\n paintFavorites();\n}", "async checkSavedRecipe(){\n const apiResponse = await fetch(`${process.env.REACT_APP_URL}/myrecipes/id-only`, {\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n })\n const { response, savedRecipeIds } = await apiResponse.json()\n\n if (response === 'success') this.setState({ isCurrentlySaved: savedRecipeIds.includes(this.state.recipeId)})\n else if (response !== 'unauthorized') this.props.history.push('/error')\n }", "function saveMeal() {\n var chosenMeal = getMeal.meals[0];\n var savedMeal = localStorage.getItem(\"meal\");\n if (!savedMeal || savedMeal === null || savedMeal === \"null\") {\n savedMeal = [];\n } else {\n savedMeal = JSON.parse(savedMeal);\n }\n var selected = savedMeal.filter(\n (meal) => meal.idMeal === getMeal.meals[0].mealId\n );\n\n if (selected.length > 0) {\n return;\n }\n // Add new favourite recipe into local storage and create button\n savedMeal.push(chosenMeal);\n localStorage.setItem(\"meal\", JSON.stringify(savedMeal));\n var newMeal = document.createElement(\"button\");\n newMeal.classList.add(\"favouritesBtn\");\n newMeal.textContent = getMeal.meals[0].strMeal;\n newMeal.setAttribute(\"data-id\", getMeal.meals[0].idMeal);\n favRecipes.appendChild(newMeal);\n}", "function getLocalstorage() {\n dark = JSON.parse(localStorage.getItem(\"dark\")) || false;\n\n setDark(dark);\n\n var secretStored = JSON.parse(localStorage.getItem(\"secret\"));\n var binStored = JSON.parse(localStorage.getItem(\"bin\"));\n\n if (secretStored == null || binStored == null || secretStored == \"\" || binStored == \"\") {\n jsonbin = false;\n return false;\n }\n\n jsonbin = true;\n secret = secretStored;\n bin = binStored;\n\n return true;\n}", "function getLocalStorage() {\n const favLocal = JSON.parse(localStorage.getItem(\"favorite\"));\n return favLocal;\n}", "function getLocalStorageTasks() {\n\n const store = JSON.parse(localStorage.getItem(\"tasks\"));\n // turn object into array to use foreach function and display tasks\n Array.from(store).forEach(elem => renderTask(elem));\n\n return store;\n}", "function obtenerLocalStorage(){\n let dataCarritos;\n \n if(localStorage.getItem('Orden') === null){\n dataCarritos = []\n }else{\n dataCarritos = JSON.parse(localStorage.getItem('Orden'))\n }\n\n return dataCarritos;\n}", "function deleteRecipeFromLocalStorage (recip) {\n\n if (localStorage.getItem(\"data\") !=null) {\n allRecipies = JSON.parse(localStorage.getItem(\"data\")); // jeśli są to konwertujemy je i zapisujemy do zmiennej\n console.log(recip)\n // zwroc nowa tablice bez skasowanego elementu\n allRecipies = allRecipies.filter(function(element, index, array) {\n return element.title != recip;\n });\n //reindeksuj\n for (let i=0; i < allRecipies.length; i++) {\n allRecipies[i].id = i+1;\n }\n localStorage.setItem(\"data\", JSON.stringify(allRecipies)); //Zapisujemy do localStorage nowe dane\n }\n }", "function getFromLocalStorage() {\n const localSto = localStorage.getItem('listTask')\n\n if(localSto) {\n listTask = JSON.parse(localSto);\n renderTask(listTask)\n }\n}", "function store() {\n let list = JSON.parse(localStorage.getItem('taskList'));\n if (list !== null) {\n taskList = list;\n } else {\n return list;\n }\n}", "function checkLocalStorage() {\n if (localStorage.getItem('products') === null) {\n //if empty run new products to create object instances\n newProducts();\n } else {\n //get the products from storage\n var getProducts = localStorage.getItem('products');\n //parse back to js from JSON\n var parsedProductsArray = JSON.parse(getProducts);\n //make product array = stored data to keep running total.\n productArray = parsedProductsArray;\n } \n}", "function delSavedRecipe(img, name, calories, cautions, dietLabels, healthLabels, ingredients, url){\r\n let index = savedRecipesArray.findIndex(x => x.img === img && x.name === name && x.calories === calories && x.cautions === cautions && x.dietLabels === dietLabels && x.url === url);\r\n savedRecipesArray.splice(index, 1);\r\n localStorage.setItem('recipes', JSON.stringify(savedRecipesArray));\r\n location.reload();\r\n}", "function loadStorage() {\n const keys = Object.keys(localStorage);\n let i = keys.length;\n console.log(\"i: \", i);\n\n while ( i-- ) {\n coffees.push( JSON.parse( localStorage.getItem(keys[i]) ) );\n }\n}", "function getBooks(){\n let books;\n\n if (localStorage.getItem(\"books\") === null){\n books = [];\n } else {\n books = JSON.parse(localStorage.getItem(\"books\"));\n }\n\n return books\n}", "function checkStorageItem() {\n return localStorage.getItem(localBook) !== null;\n}", "function publish_recipe(){\r\n const recipeName = document.getElementById(\"name\");\r\n const description = document.getElementById(\"description\");\r\n const ingredients = document.getElementById(\"ingredients\");\r\n const instructions = document.getElementById(\"instructions\");\r\n if(recipeName.value != '' && description.value != '' && ingredients.value != '' && instructions.value != ''){\r\n var recipe_info = {\r\n 'img' : uploadedImage,\r\n 'name' : recipeName.value,\r\n 'description' : description.value,\r\n 'ingredients' : ingredients.value,\r\n 'instructions' : instructions.value\r\n }\r\n myRecipesArray.push(recipe_info);\r\n localStorage.setItem('myRecipes', JSON.stringify(myRecipesArray));\r\n document.querySelector('#myFileInput').value = '';\r\n recipeName.value = '';\r\n description.value = '';\r\n ingredients.value = '';\r\n instructions.value = '';\r\n }\r\n else{\r\n alert(\"Please complete the fields\");\r\n }\r\n}", "function getProductsFromStorage(){\n let products=localStorage.getItem(\"products\");\n\n return products? JSON.parse(products):[];\n}", "function readFromLocalStorage() {\n let stringViews = localStorage.getItem('views');\n let stringVotes = localStorage.getItem('votes');\n\n let normalViews = JSON.parse(stringViews);\n let normalVotes = JSON.parse(stringVotes);\n\n if (normalViews) \n {\n viewsArrTemp = normalViews;\n }\n if (normalVotes) \n {\n votesArrTemp = normalVotes;\n }\n // localStorage.clear();\n console.log('votes', votesArrTemp);\n console.log('views', viewsArrTemp);\n}", "async function checkLocalStorage() {\n if (!localStorage.getItem('repertoire')) {\n // If local storage does not exist, add the initial JSON\n addJSONToLocalStorage(\"repertoire\");\n } else {\n // If local storage does exist, fill the container with tracks from local storage\n fillWithLocalStorage(\"repertoire\");\n }\n}", "function checkResults(){\n let checkData = localStorage.getItem('results');\n if (checkData){\n let storedResults = JSON.parse(checkData);\n //renderResults(storedResults);\n return storedResults;\n }\n}", "function getCitiesFromLocalStorage() {\n if (localStorage.getItem(\"cities\")) {\n citySearches = JSON.parse(localStorage.getItem(\"cities\"));\n }\n}", "function getSavedTodos() {\r\n // Get TODOs from the local storage\r\n let todos = localStorage.getItem('todos')\r\n\r\n if (todos == null || todos == 'undefined') {\r\n todos = []\r\n } else { \r\n // Convert it to an array\r\n todos = JSON.parse(todos)\r\n }\r\n\r\n // Return it\r\n return todos\r\n}", "function recipeData(recipeSearch) {\n $.ajax({\n url:\n \"https://api.edamam.com/search?app_id=40897fdb&app_key=e7085ffc3bbf333e4fcc1dfd79fa54fd&q=\" +\n recipeSearch,\n method: \"GET\",\n }).then(function (response) {\n // randomised selection of recipe\n var randomRecipe =\n response.hits[Math.floor(Math.random() * response.hits.length)].recipe;\n console.log(\"I am the random recipe\", randomRecipe);\n $(\".recipe-card\").empty();\n\n //add to local storage\n if (!recipePreviouslySearched.includes(recipeSearch)) {\n recipePreviouslySearched.push(recipeSearch);\n localStorage.setItem(\n \"recipe\",\n JSON.stringify(recipePreviouslySearched)\n );\n }\n $(\".recipe-history\").empty();\n createRecipeList(recipePreviouslySearched);\n\n //appending recipe data to card\n\n var image = $(\"<p>\").addClass(\"card-image\");\n var imageUrl = randomRecipe.image;\n var iconHtml = $(\"<img>\").attr(\"src\", imageUrl);\n var recipeLink = $(\"<a>\")\n .attr(\"href\", randomRecipe.shareAs)\n .attr(\"target\", \"_blank\")\n .text(\"Read your recipe at \" + randomRecipe.source);\n var label = $(\"<p>\").addClass(\"card-text\").text(randomRecipe.label);\n var source = $(\"<p>\").addClass(\"card-text\").text(randomRecipe.source);\n\n image.append(iconHtml);\n $(\".recipe-card\").append(image, recipeLink, label, source);\n });\n\n createRecipeList(recipePreviouslySearched);\n }", "function checkLocalStorage(){ \nif (localStorage.getItem('adjektiv') && localStorage.getItem('nomen')) \n { \n localStorArrayAdj = [];\n let localStorAdj = localStorage.getItem('adjektiv');\n localStorArrayAdj.push(...localStorAdj.split(','));\n\n localStorArrayNomen = []\n let localStorNom = localStorage.getItem('nomen');\n localStorArrayNomen.push(...localStorNom.split(','));\n\n init(localStorArrayAdj, localStorArrayNomen);\n}\nelse \n { setDefaultToLocaleStorage();\n init(adjektivArray, nomenArray); } \n}", "function obtenerDelLocalStorage(){\n\tlet productos;\n\tif (localStorage.getItem(\"Productos\") === null) {\n\t\tproductos = []\n\t}\n\telse{\n\t\tproductos = JSON.parse(localStorage.getItem(\"Productos\"));\n\t}\n\treturn productos;\n}", "function retrive(){\n if (localStorage.getItem('movies')){\n nominationList = JSON.parse(localStorage.getItem('movies'))\n }\n \n}", "function getDiaryFromLocalStorage() {\n\tif (localStorage.getItem('diary') == null) {\n\t\treturn [];\n\t} else {\n\t\treturn JSON.parse(localStorage.getItem('diary'));\n\t}\n}", "function getLocalStorage() {\n let storageArray = [];\n for(let i = 0; i < localStorage.length; i++) {\n let item = JSON.parse(localStorage.getItem(localStorage.key(i)));\n storageArray.push(item);\n }\n console.log('Found local items:', storageArray);\n return storageArray;\n}", "function checkLS() {\n // check local storage\n let dataLS;\n if (localStorage.getItem(\"dataLS\") === null) {\n dataLS = [];\n } else {\n dataLS = JSON.parse(localStorage.getItem(\"dataLS\"));\n }\n return dataLS;\n}", "function getFromLocalStorage() {\n const reference = localStorage.getItem('lists');\n // if reference exists\n if (reference) {\n // converts back to array and store it in lists array\n lists = JSON.parse(reference);\n renderLists(lists);\n }\n}", "function saveAll() {\n totalCount = 0;\n foodInput = document.querySelectorAll(\".input-field\");\n localStorage.removeItem(\"foods\");\n foods= [];\n\n for(var i = 0; i < foodInput.length; i++) {\n if(foodInput[i].value.length > 0) {\n var savedFood = foodInput[i].value;\n foods.push(savedFood);\n }\n }\n localStorage.setItem(\"foods\", foods);\n setFoods(foods)\n}", "function loadFavourites() {\n favouritesArray = JSON.parse(localStorage[\"favouritesArray\"]);\n}", "retrieveFromLocalStorage(difficulty, rank) {\n return JSON.parse(localStorage.getItem(`${difficulty}_${rank}`));\n }", "function getShoesFromStorage() {\r\n let shoes;\r\n\r\n //get the value if present in the storage, else return an empty array\r\n if (localStorage.getItem('shoes') === null) {\r\n shoes = [];\r\n } else {\r\n shoes = JSON.parse(localStorage.getItem('shoes'));\r\n }\r\n return shoes;\r\n}", "function getFavoritos() {\n\tvar datos = localStorage.getItem('peliculasFavoritos');\n\n\tif (datos !== null) {\n\t\tfavoritos = JSON.parse(datos);\n\t\t// console.log('favoritos cargados');\n \n\t}\n}", "function readAll() {\r\n const stringLivro = localStorage.getItem('livros-app:livros');\r\n return JSON.parse(stringLivro);\r\n}", "function add_favourite(submit_value){\n //parse html table\n var parse_status=parse_htmltable(submit_value);\n let redundantFavourite = false;\n if(parse_status){\n let localstorage_key = 'FoodTour_'+ ( Math.random() * 100);\n //check for redundancy addition of content to favourites\n for (l=0 ; l < localStorage.length ;l++){\n key=localStorage.key(l);\n if (key.match('FoodTour') && redundantFavourite==false){\n if ( favourite_json == localStorage.getItem(key)){\n redundantFavourite=true;\n alert(\"Favourite already exists\");\n }\n }\n }\n if(redundantFavourite==false){\n console.log(\"favouritejson\",favourite_json);\n localStorage.setItem(localstorage_key,favourite_json);\n //fetch table id and add new rows and display each favourite item added\n var favourite_table=document.getElementById(favourite_tour_table);\n //call to display favourites\n display_favourtie(favourite_table,localstorage_key);\n }\n\n }\n}", "function favorite(e) {\n e.stopPropagation();\n let favoriteRecipes = []\n if (localStorage && localStorage.getItem('faved')) {\n favoriteRecipes = JSON.parse(localStorage.getItem('faved'))\n }\n let existing=favoriteRecipes.filter(x=>x.url===props.recipe.url)\n if (existing.length <= 0) {\n favoriteRecipes.push(props.recipe)\n setIsFaved(true);\n } else {\n let index = favoriteRecipes.findIndex(x=>x.url===props.recipe.url)\n favoriteRecipes.splice(index, 1)\n setIsFaved(false);\n }\n localStorage.setItem('faved', JSON.stringify(favoriteRecipes))\n }", "function checkStorage() {\n var storedCity = localStorage.getItem(\"city\");\n if(storedCity) {\n sTerm = storedCity;\n getForecasts();\n };\n var storedCities = localStorage.getItem(\"cities\")\n if (storedCities){\n cities = JSON.parse(storedCities)\n for (i=0; i < cities.length; i++){\n name = cities[i];\n btnMk(name);\n };\n btnClear();\n };\n}", "function displayCities() {\n if (localStorage.getItem(\"citySearchedArray\") !== null) {\n var citySearchedArray = JSON.parse(localStorage.getItem(\"citySearchedArray\"));\n console.log(citySearchedArray);\n }\n}", "function getTodos () {\n // If there are items in the storage : \n if ( localStorage.getItem('todos') ){\n // There are items in the storage\n console.log('there is stuff in the local storage')\n // Save the items into the todoList array\n todoList = JSON.parse( localStorage.getItem('todos') )\n\n // create the HTML for the items in the todoList array\n popList ()\n return\n } else {\n // There are no items in the storage\n return 'You do not have any todos \\nclick the \"+\" button to add more'\n }\n}", "getLocalStorage() {\r\n return JSON.parse(localStorage.getItem('todos')) || [];\r\n }", "_commit(recipes) {\n this.onRecipesChanged(recipes);\n localStorage.setItem('recipes', JSON.stringify(recipes));\n }", "function getChosenCityLS() {\n var chosenCityLS = JSON.parse(localStorage.getItem(\"chosenCity\"));\n return chosenCityLS;\n}", "function getArray(){\r\n return JSON.parse(localStorage.getItem('list')) || [];\r\n}", "function getCart() {\n if (localStorage.getItem(\"cart\") === null) {\n $(\"#cartList\").prepend(\n '<h2 style=\"text-align:center\"><B>Cart is empty</b></h2>'\n );\n removeForm();\n } else {\n tempCart = JSON.parse(localStorage.getItem(\"cart\")); // cart = localstorage cart\n console.log(\"tempCart\");\n console.log(tempCart);\n for (let i = 0; i < tempCart.length; i++) {\n if (\n tempCart[i].amount == false ||\n tempCart[i].amount == undefined ||\n tempCart[i].amount == NaN\n ) {\n getAmount();\n }\n }\n combineDuplicates();\n console.log(\"newTempCart\");\n console.log(tempCart);\n cart = tempCart;\n setCart();\n }\n}", "function LocalStorage(){\r\n if(localStorage.getItem(\"todos\")===null){\r\n return [];\r\n }\r\n return JSON.parse(localStorage.getItem(\"todos\"));\r\n}", "function prodExiste(prodNuevo){\n \n let salida=true;\n let prodLista=JSON.parse(localStorage.getItem(\"productos\"));\n if(prodLista!=null&&prodLista.find(item=>item.id==prodNuevo.id)){\n salida=false;\n }\n return salida;\n}", "function checkForStorage() {\n\n if (!localStorage.myStorage) {\n console.log('no local');\n createArray();\n showThreePics();\n } else {\n console.log(' yes local');\n var tempDataHolder = localStorage.getItem('myStorage');\n var parseData = JSON.parse(tempDataHolder);\n allProducts = parseData;\n showThreePics();\n }\n}", "function getTaskLocalStorage() {\n var tasks;\n // Revisamos los valoes de local storage\n if (localStorage.getItem('tasks') === null) {\n tasks = [];\n } else {\n tasks = JSON.parse(localStorage.getItem('tasks'));\n }\n return tasks;\n}", "function loadList(){\n let list = [];\n // Load the item from localStorage.\n let newList = localStorage.getItem(\"list\");\n\n // Check to see if the item returned null\n if (newList == null || newList == undefined){\n // If it did, save a new list.\n saveList();\n return list;\n } else {\n // If it didn't, parse the JSON string and save it to list.\n list = JSON.parse(newList);\n return list;\n }\n}", "function getLocalStorage(){\n let toLibrary = JSON.parse(localStorage.getItem('myLibrary'));\n if(toLibrary===undefined) return;\n toLibrary.forEach((object)=>{\n // book.prototype=toggleRead;\n let bookObject = new Book(object.title,object.author,object.pages,object.read);\n myLibrary.push(bookObject)\n })\n}", "function loadKittens() {\n console.log(\"enter loadKittens()\");\n let storedKittens = JSON.parse(window.localStorage.getItem(\"kittens\"));\n if (storedKittens) {\n kittens = storedKittens;\n }\n console.log(\"loadKittens() success\");\n}", "function getSoundFromLocalStorage() {\n// if localStorage exists\n if (localStorage.length > 0) {\n // retrieve, parse, assign to array of objects\n soundChoice = JSON.parse(localStorage.getItem('soundPref'));\n } else {\n }\n return soundChoice;\n}", "function carregarLocalStorage(){\n\n // Limpar a lista\n listaTarefa.innerHTML = ''\n\n if(localStorage.getItem(\"tarefas\")){\n \n let listaTarefa = JSON.parse(localStorage.getItem('tarefas'))\n \n listaTarefa.forEach((tarefas, id) => {\n addListaTarefa(tarefas, id)\n })\n console.log('Carregando do local storage TAREFAS')\n \n }\n}" ]
[ "0.7369242", "0.70015085", "0.685982", "0.6499887", "0.6338447", "0.6327309", "0.62800825", "0.6271402", "0.62226397", "0.6222276", "0.62205327", "0.6188178", "0.61537135", "0.61517423", "0.61320984", "0.6112645", "0.6092996", "0.6090652", "0.60802317", "0.60758847", "0.602762", "0.5995473", "0.5993113", "0.59898895", "0.59742004", "0.5968466", "0.59655136", "0.5955076", "0.5937084", "0.59161586", "0.5906853", "0.5902723", "0.5901223", "0.5864886", "0.58625764", "0.5842204", "0.5837093", "0.58164173", "0.5809452", "0.57906055", "0.5788792", "0.5785444", "0.5767263", "0.57649666", "0.576154", "0.57422864", "0.5740588", "0.57365227", "0.57259065", "0.57163537", "0.57133967", "0.57102174", "0.570466", "0.5702457", "0.56982476", "0.5697798", "0.56922936", "0.56910646", "0.56895524", "0.5685834", "0.56850326", "0.5679821", "0.5673761", "0.5658172", "0.5655283", "0.5655212", "0.5654807", "0.5654701", "0.5641096", "0.56375027", "0.5635248", "0.56348324", "0.563365", "0.5629592", "0.56160575", "0.56100124", "0.5609131", "0.5607399", "0.5606551", "0.5599072", "0.55933994", "0.55925006", "0.55862945", "0.55807287", "0.55683833", "0.5565811", "0.5561919", "0.5549536", "0.55472594", "0.5545155", "0.55397624", "0.553428", "0.55330443", "0.5532311", "0.5524398", "0.55172694", "0.5513044", "0.55081874", "0.5507779", "0.55037695" ]
0.88765395
0
setUserLocalStorage function sets the username, email values to local storage
function setUserLocalStorage(username, email) { localStorage.setItem("username", username); localStorage.setItem("email", email); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function syncCurrentUserToLocalStorage() {\n if (currentUser) {\n localStorage.setItem(\"token\", currentUser.loginToken);\n localStorage.setItem(\"username\", currentUser.username);\n }\n }", "function syncCurrentUserToLocalStorage() {\n if (currentUser) {\n localStorage.setItem(\"token\", currentUser.loginToken);\n localStorage.setItem(\"username\", currentUser.username);\n }\n }", "function syncCurrentUserToLocalStorage() {\n if (currentUser) {\n localStorage.setItem(\"token\", currentUser.loginToken);\n localStorage.setItem(\"username\", currentUser.username);\n }\n }", "function syncCurrentUserToLocalStorage() {\n if (currentUser) {\n localStorage.setItem(\"token\", currentUser.loginToken);\n localStorage.setItem(\"username\", currentUser.username);\n }\n }", "function syncCurrentUserToLocalStorage() {\n if (currentUser) {\n localStorage.setItem(\"token\", currentUser.loginToken);\n localStorage.setItem(\"username\", currentUser.username);\n }\n }", "function syncCurrentUserToLocalStorage() {\n if (currentUser) {\n localStorage.setItem(\"token\", currentUser.loginToken);\n localStorage.setItem(\"username\", currentUser.username);\n }\n }", "function saveUserCredentialsInLocalStorage() {\n console.debug('saveUserCredentialsInLocalStorage');\n if (currentUser) {\n localStorage.setItem('token', currentUser.loginToken);\n localStorage.setItem('username', currentUser.username);\n }\n}", "function saveUserCredentialsInLocalStorage() {\n console.debug(\"saveUserCredentialsInLocalStorage\");\n if (currentUser) {\n localStorage.setItem(\"token\", currentUser.loginToken);\n localStorage.setItem(\"username\", currentUser.username);\n }\n}", "function setUserInLocalStorage(userData) {\n var localUser = localStorageService.get('currentUser');\n localStorageService.set('currentUser', {\n username: Methods.isNullOrEmpty(userData.username) ? localUser.username : userData.username,\n token : Methods.isNullOrEmpty(userData.token) ? localUser.token : userData.token\n });\n }", "function storeLocal() {\n const jsonUserData = JSON.stringify(userData);\n localStorage.setItem('fullname', jsonUserData);\n}", "function setData() {\n localStorage.setItem('name', username.value);\n localStorage.setItem('email', email.value);\n localStorage.setItem('city', city.value);\n localStorage.setItem('organisation', organisation.value);\n localStorage.setItem('contact', contact.value);\n localStorage.setItem('message', message.value);\n // Reset all the fields.\n username.value = '';\n email.value = '';\n city.value = 'city';\n organisation.value = '';\n contact.value = '';\n message.value = '';\n\n}", "function setLogin(email,name) {\n\tlocalStorage.setItem(\"email\", email);\n\tlocalStorage.setItem(\"name\", name);\n}", "function setupLocalStroageAfterLogin() {\n Object(_comms_js__WEBPACK_IMPORTED_MODULE_0__[\"fetchJson\"])(\"/user/profile\").then(function (user) {\n localStorage.setItem(\"auth\", true);\n localStorage.setItem(\"navbar_title\", user.firstName);\n });\n} // Function to reset the localStorage", "setUserLS(userName) {\n localStorage.setItem('logedUser', userName);\n }", "function saveToLocalStorage() { \n\t\n\t\t\t\t\tvar lscount = localStorage.length; \n\t\t\t\t\tvar Userstring=User.toJSONString();\n\t\t\t\t\t\t\tlocalStorage.setItem(\"User_\" + lscount, Userstring); \n\t\t\n}", "function saveUserData(userData) {\n localStorage.setItem('username', userData.username);\n localStorage.setItem('accessToken', userData.accessToken);\n localStorage.setItem('id', userData.id);\n username = userData.username;\n accessToken = userData.accessToken;\n }", "function saveInfoLocal(email) {\n localStorage.setItem('email', email);\n}", "function store() {\n localStorage.setItem('name_1', name_1.value);\n localStorage.setItem('pw', pw.value);\n localStorage.setItem('email',email.value )\n}", "setUsername() {\n var username = document.getElementById(\"username\");\n localStorage.setItem('username', username.value);\n localStorage.setItem('balance', 100);\n localStorage.setItem('round', 0);\n localStorage.setItem('pool', 0);\n }", "function storedata(username, jwt) {\r\n if(typeof(Storage) !== \"undefined\") {\r\n if (localStorage.jwt && localStorage.username) {\r\n localStorage.username =username;\r\n localStorage.jwt =jwt;\r\n // alert('done')\r\n } else {\r\n localStorage.username =username;\r\n localStorage.jwt =jwt;\r\n // alert('done add')\r\n }\r\n } else {\r\n alert(\"Sorry, your browser does not support web storage...\");\r\n }\r\n }", "static saveUserInfo(userData) {\n localStorage.setItem('uid', userData.uid);\n localStorage.setItem('name', userData.name);\n }", "function setsaveInfoLocalStorage(userInfo){\n localStorage.setItem('userInfo',JSON.stringify(userInfo));\n}", "static storeUser(user) {\n localStorage.setItem('userInfo', user);\n }", "function saveUserData() {\n localStorage.setItem('locallyStored', JSON.stringify(userData))\n}", "function setStorage() \r\n\t{\r\n if (typeof(Storage) !== \"undefined\")\r\n\t\t{\r\n if (remember)\r\n\t\t\t{\r\n localStorage.setItem(\"member\", 'true');\r\n if (publicAddr)\r\n localStorage.setItem(\"address\", publicAddr);\r\n } else\r\n\t\t\t{\r\n localStorage.removeItem('member');\r\n localStorage.removeItem('address');\r\n }\r\n } \r\n }", "function setUserDetailsInLocalStorage(user) {\n localStorage.setItem(\"userDetails\", JSON.stringify(user));\n}", "pushToLocal() {\r\n\r\n let userData = {};\r\n\r\n userData = {\r\n userName: this.name.val(),\r\n userEmail: this.email.val(),\r\n userPhone: this.phone.val(),\r\n userAge: this.age.val(),\r\n userPassword: this.password.val(),\r\n userRepassword: this.rePassword.val(),\r\n }\r\n\r\n this.localData.push(userData);\r\n localStorage.setItem(\"userData\", JSON.stringify(this.localData));\r\n\r\n }", "function localAddTestUsersToStorage(){\n let choice = prompt(\"Clear Storage before adding users? Y/N\");\n \n if(choice.toLocaleLowerCase() == \"y\"){\n localStorage.clear();\n }\n \n for(let i = 0; i < localTestUsers.users.length; i++){\n localStorage.setItem(localTestUsers.users[i].email, JSON.stringify(localTestUsers.users[i])); \n }\n}", "async function saveUserCredentialsInLocalStorage() {\n if (currentUser) {\n let teamsList = await Team.getTeams();\n\n favName = teamsList.find(function (obj) {\n if (obj[\"id\"] == favTeam) return obj;\n });\n\n localStorage.setItem(\"username\", currentUser.username);\n localStorage.setItem(\"userId\", currentUser.userId);\n localStorage.setItem(\"favTeamId\", favTeam);\n\n //catches error when function is called prior to user setting a favorite team\n try {\n localStorage.setItem(\"favTeamName\", favName.name);\n } catch (err) {\n console.log(\"no favorite team selected\");\n }\n }\n}", "function settingFunction() {\n\n let allUsersString = JSON.stringify(allUsers);\n localStorage.setItem('allUsers', allUsersString);\n\n}", "function saveUserDetails() {\n var user = {\n 'first': $('#user_event_first_name').val(),\n 'last': $('#user_event_last_name').val(),\n 'email': $('#user_event_user_email').val()\n };\n localStorage.setItem('wceUser', JSON.stringify(user));\n}", "function GetDataFromLocalStorage(){\n /*if (storageObject.getItem(\"username\") != null) {\n $(\".usernameval\").val(storageObject.username);\n }\n if (storageObject.getItem(\"password\") != null) {\n $(\".passwordval\").val(storageObject.password);\n }*/\n}", "function setUser(id, username) {\n\tuserid = id;\n\tusername = username;\n\tlocalStorage.setItem('userid', userid);\n\tlocalStorage.setItem('username', username);\n}", "function storeUsers() {\n localStorage.setItem(\"users\", JSON.stringify(users));\n}", "function storeUsers() {\n localStorage.setItem(\"users\", JSON.stringify(users));\n}", "function setTemp() {\n if (localStorage.getItem(\"userId\") === null) {\n // Create temp user\n var tempUser = {\n name: \"temp\",\n password: \"\"\n };\n localUser.name = tempUser.name;\n console.log(tempUser);\n // User post\n API.createUser(tempUser);\n } else {\n localUser.id = localStorage.getItem(\"userId\");\n API.getFridge(localUser.id);\n }\n}", "function checkLocalStorageData() {\n let email = localStorage.getItem('email');\n let firstName = localStorage.getItem('firstName');\n let lastName = localStorage.getItem('lastName');\n let textarea = localStorage.getItem('textarea');\n if (\n email != null &&\n firstName != null &&\n lastName != null &&\n textarea != null\n ) {\n $('#email').val(email);\n $('#firstName').val(firstName);\n $('#lastName').val(lastName);\n $('#taMessage').val(textarea);\n }\n}", "function rememberUser() {\r\n\tif(localStorage.remember) {\r\n\t\tgetId('name').value = localStorage.name;\r\n\t\tgetId('email').value = localStorage.email;\r\n\t\tgetId('phone').value = localStorage.phone;\r\n\t\tgetId('address').value = localStorage.address;\r\n\t\tgetId('remember').checked = localStorage.remember;\r\n\t}\r\n}", "function setUserData(name, value) {\n if (window.localStorage) { // eslint-disable-line\n window.localStorage.setItem(name, value) // eslint-disable-line\n } else {\n Cookies.set(name, value, { expires: 7 })\n }\n}", "function setUser(user) {\n\t\t\tlocalStorage.addLocal('user', user);\n\t\t}", "function setDataFromLocalStorage() { \t\n \tCORE.LOG.addInfo(\"PROFILE_PAGE:setDataFromLocalStorage\");\n \t$(\"#name\").val(gameData.data.player.profile.name);\n \t$(\"#surname\").val(gameData.data.player.profile.surname);\n \t$(\"#age\").val(gameData.data.player.profile.age);\n \t$(\"#sex\").val(gameData.data.player.profile.sex);\n \t$(\"#mobile\").val(gameData.data.player.profile.mobile); \n \t \t \t\n }", "async setCredentials() {\n\t\tif (this.state.save) {\n\t\t\tawait AsyncStorage.setItem('username', this.state.username);\n\t\t\tawait AsyncStorage.setItem('password', this.state.password);\n\t\t}\n\t\telse {\n\t\t\tawait AsyncStorage.setItem('username', '');\n\t\t\tawait AsyncStorage.setItem('password', '');\n\t\t}\n\t}", "function set_name_storage(){\r\n\tvar name_local_storage = document.querySelector('#userName').value;\r\n\tlocalStorage.setItem(\"name_storage\", name_local_storage);\r\n\t//alert(localStorage.getItem(\"name_storage\"));\r\n\r\n\tlocalStorage.setItem(\"countSD_storage\", countSD);\r\n\tlocalStorage.setItem(\"countSE_storage\", countSE);\r\n\tlocalStorage.setItem(\"countID_storage\", countID);\r\n\tlocalStorage.setItem(\"countIE_storage\", countIE);\r\n\t\r\n}", "function storeLocalInfo(){\n // IE7 uses cookies\n // Check for IE7 first\n if(ieSeven){\n // Use cookies\n SetCookie('firstName', $(\"fName\").value);\n SetCookie('lastName', $('lName').value);\n SetCookie('email', $('email').value);\n }\n else if (window.localStorage){ // all other browsers\n localStorage.setItem(\"firstName\", $(\"fName\").value);\n localStorage.setItem(\"lastName\", $(\"lName\").value);\n localStorage.setItem(\"email\", $(\"email\").value);\n }\n}", "persist() {\n localStorage.setItem(\n STORAGE_KEY + \"/\" + this.user.getId(),\n JSON.stringify(this.data)\n );\n }", "function saveUsers(){\n $(\"#create-account\").css(\"display\",\"none\");\n var str = JSON.stringify(users);\n console.log(str);\n localStorage.setItem(\"users\", str);\n}", "function saveUsers(){\n $(\"#create-account\").css(\"display\",\"none\");\n var str = JSON.stringify(users);\n console.log(str);\n localStorage.setItem(\"users\", str);\n}", "async writeToStorage() {\r\n const fetchedInfo = {\r\n fetchedUsername: this.state.fetchedUsername,\r\n fetchedPassword: this.state.fetchedPassword,\r\n };\r\n\r\n //Save the user info\r\n localStorage.setItem(\"fetchedInfo\", JSON.stringify(fetchedInfo));\r\n }", "function store() {\n\t// Stores inputs from the register-form in variables\n\tvar name = document.getElementById('regUser').value;\n\tvar pw = document.getElementById('regPw').value;\t\n\t// Stores input from register-form\n localStorage.setItem('name', regUser.value);\n localStorage.setItem('pw', regPw.value);\n\tconsole.log('Username:' + name + ' ' + 'Password:' + pw + ' are stored in local storage');\n\t//resets form on button click//\n\tdocument.getElementById('register-form').reset();\n \t\n}", "function saveName() {\n\n localStorage.setItem('receivedName', userName);\n}", "async function storageUser(data){\n await AsyncStorage.setItem('Auth_user', JSON.stringify(data));\n }", "function display_name()\n{\n // localStorage.clear();\n let username=document.getElementById(\"username\").value;\n // alert(username)\n localStorage.setItem('username', username);\n}", "function addTestUsersToStorage(){\n let choice = prompt(\"Clear Storage before adding users? Y/N\");\n let testUsers;\n \n if(choice.toLocaleLowerCase() == \"y\"){\n localStorage.clear();\n }\n \n let xml = new XMLHttpRequest();\n xml.open(\"GET\", \"testUsers.dat\");\n xml.onreadystatechange = () => {\n if(xml.readyState == 4){\n testUsers = JSON.parse(xml.responseText);\n for(let i = 0; i < testUsers.users.length; i++){\n localStorage.setItem(testUsers.users[i].email, JSON.stringify(testUsers.users[i])); \n }\n }\n };\n xml.send();\n}", "function store() {\n localStorage.setItem('name1', name1.value);\n localStorage.setItem('pw', pw.value);\n}", "guardarStorage() {\n localStorage.setItem('usuario', JSON.stringify(this.usuario));\n }", "function saveCredentials() {\n\tvar username = document.getElementById(\"username\").value;\n\tvar password = document.getElementById(\"password\").value;\n\tvar creds = {\n\t\t\tuser: username,\n\t\t\tpass: password\n\t};\n\tvar store = JSON.stringify(creds);\n\tlocalStorage.setItem(\"AtmosphereLogin\", store);\n}", "function storeCredentials () {\n var storage = window.localStorage;\n\n //Get Info\n username = document.getElementById(\"username\").value;\n password = document.getElementById(\"password\").value;\n\n //Store Info\n storage.setItem(\"username\", username);\n storage.setItem(\"password\", password);\n\n //Hide Login\n hideLogin();\n}", "function saveAuthData() {\n // Skip if the local storage is not available.\n if (!utils.storageAvailable('localStorage')) {\n return;\n }\n\n // Create the data object.\n var data = {\n authUserID: authUserID\n };\n\n // Save to the local storage.\n localStorage.setItem(authDataID, JSON.stringify(data));\n }", "function storeUser(fname, lname, gender, phone, add,username, email, password) {\n\n\t// Create an array of object\n var userAccount = {};\n\n\t// Stores user properties\n userAccount.firstName = fname;\n userAccount.lastName = lname;\n userAccount.gender = gender;\n userAccount.phoneNumber = phone;\n\tuserAccount.address=add;\n userAccount.emailAddress = email;\n userAccount.password = password;\n userAccount.username = username;\n userAccount.high_score=0;\n\n\t// Convert array obj into stringify\n\t// Stores into localStorage\n\t// Use username as key\n localStorage[userAccount.username] = JSON.stringify(userAccount);\n\n\n\n\n\n\n}", "function usuarioPredeterminado(){\r\n localStorage.setItem('Clave1', 'lider123');\r\n localStorage.setItem('Usuario1', 'lider123');\r\n localStorage.setItem('Genero1', 'Masculino');\r\n localStorage.setItem('Tipo Usuario1', 'Administrador');\r\n localStorage.setItem('Apellido1', 'lider123');\r\n localStorage.setItem('Nombre1', 'lider123');\r\n\r\n localStorage.setItem('Clave2', 'usuario123');\r\n localStorage.setItem('Usuario2', 'usuario123');\r\n localStorage.setItem('Genero2', 'Femenino');\r\n localStorage.setItem('Tipo Usuario2', 'Usuario');\r\n localStorage.setItem('Apellido2', 'usuario123');\r\n localStorage.setItem('Nombre2', 'usuario123');\r\n}", "function syncUser (newval) {\n storage.set('user', newval);\n}", "function saveNickName() {\n localStorage.setItem('receivedNickName', userNickName); //1st argument is a keyword to get the info, 2nd argument - info that has to be rememeber \n userNickName = localStorage.getItem('receivedNickName');\n}", "function clearUserData()\n {\n userData = userDataDefault;\n window.localStorage.setItem(localStorageName, JSON.stringify(userData));\n }", "setUser() {\n var target = ('http://backend-edu.azurewebsites.net/user/' + localStorage.getItem('email'))\n fetch(target).then((results) => {\n return results.json();\n\n }).then((json) => {\n\n this.setState({\n NutzerId: json[0].userid\n }, function () {\n localStorage.setItem('userid', this.state.NutzerId);\n });\n })\n }", "function persistUserToLS(email){\n \n let blogUser;\n \n if(localStorage.getItem('blogUser') !== null){\n blogUser = JSON.parse(localStorage.getItem('blogUser'))\n }else{\n blogUser = [];\n }\n \n if(blogUser.indexOf(email) === -1){\n blogUser.push(email);\n }\n \n localStorage.setItem('blogUser',JSON.stringify(blogUser));\n }", "setLocalStorage() {\r\n\tlocalStorage.setItem('userPantry', JSON.stringify(this.state.userIngredients))\r\n }", "function storeUserLocal(user){\n try\n {\n LocalStorage.setObject(Constants.USER,user);\n return true;\n }\n catch(err)\n {\n return false;\n }\n }", "function saveUsers(detailsStr) {\n var usersJSON = JSON.stringify(detailsStr);\n localStorage.setItem(LS_MEME_USER, usersJSON);\n}", "function addToLocalStorage(){\n var dataString = $(\"#BADefaultEmail\").val();\n localStorage.setItem(\"BADefaultEmail\", dataString );\n alert(\"Default reviewer email saved.\")\n}", "function fetchStorage() {\n txtFName.value = localStorage.getItem(\"input-name\");\n txtLName.value = localStorage.getItem(\"input-lastname\");\n txtPhone.value = localStorage.getItem(\"input-phone\");\n txtEmail.value = localStorage.getItem(\"input-email\");\n }", "function saveCurrentUserinLocalStorage() {\n localStorage.setItem(\"curUserId\", firebase.auth().currentUser.uid);\n localStorage.setItem(\"curUserImgSource\", firebase.auth().currentUser.photoURL);\n}", "function store() {\r\n localStorage.setItem('regName', regName.value);\r\n localStorage.setItem('regPw', regPw.value);\r\n auth.innerHTML = 'Registered Successfull'\r\n regName.value='';\r\n regPw.value='';\r\n}", "function initLoginLocalStorage(response) {\n // const { resultData, token } = response;\n // set('token', token);\n // set('__USER__ID__', resultData.userId);\n // if (resultData.permission) {\n // userPermissionUtil.setPermission(resultData.permission);\n // userProfileUtil.setUerProfile(resultData.profile);\n // userInfoUtil.setUerInfo(resultData.user_info);\n // }\n\n // localStorage.setItem('token', result.token);\n // localStorage.setItem('userInfo', JSON.stringify(_.get(result, 'resultData.userInfo', {})));\n // localStorage.setItem('userId', _.get(result, 'resultData.userInfo.id'));\n}", "login(state, { username, token }) {\n state.currentUser = {\n username: username,\n token: token,\n };\n\n localStorage.trckrCurrentUser = JSON.stringify(state.currentUser);\n }", "init () {\n if (localStorage.users === undefined || !localStorage.encrypted) {\n // Set default user\n let defaultUser = 'DeekshithShetty'\n let defaultUserSalt = genSalt(defaultUser)\n let defaultUserPass = hashSync('Hydra@12345', defaultUserSalt)\n\n users = {\n [defaultUser]: hashSync(defaultUserPass, salt)\n }\n\n localStorage.users = JSON.stringify(users)\n localStorage.encrypted = true\n } else {\n users = JSON.parse(localStorage.users)\n }\n }", "function setUserData(userInputData){\n console.log(userInputData)\n var user = userRef.push()\n localStorage.setItem(\"userID \", user.key)\n user.set({\n name: userInputData.userName, //key: value\n birthday: userInputData.userBDay, //prop = field will need to reset\n email: userInputData.userEmail,\n recentSearches: null,\n });\n }", "function setStorage(username, token, msgType) {\r\n sessionStorage.setItem('authToken', token);\r\n sessionStorage.setItem('username', username);\r\n\r\n sayGreeting();\r\n showPage('viewBooks');\r\n\r\n let message;\r\n if (msgType == 'login') {\r\n message = 'You have successfully logged in!';\r\n }\r\n else {\r\n message = 'You have registered successfully!';\r\n }\r\n\r\n infoBox.show().text(message);\r\n setTimeout(() => infoBox.fadeOut(), 2500);\r\n }", "createUser(username) {\n var createUser = {\n 'username': username,\n 'password': this.password\n };\n var userdata = [];\n userdata.push(createUser);\n var map = new Map(JSON.parse(localStorage.getItem('userstorage')));\n if (!map.has(this.email)) {\n map.set(this.email, createUser);\n localStorage.setItem('userstorage', JSON.stringify(Array.from(map.entries())));\n return true;\n }\n return false;\n }", "onLocalLogin() {\n let accessToken = localStorage.getItem('access_token');\n let refreshToken = localStorage.getItem('refresh_token');\n let user = JSON.parse(localStorage.getItem('user'));\n\n if (accessToken && refreshToken && user) {\n this.saveTokens({access_token: accessToken, refresh_token: refreshToken});\n this.loginSuccess(user, true);\n }\n }", "function store() {\n if (email.value.length == 0 && password.value.length == 0) {\n\n } else {\n localStorage.setItem('firstName', firstName.value);\n localStorage.setItem('lastName', lastName.value);\n localStorage.setItem('age', age.value);\n localStorage.setItem('occupation', occupation.value);\n localStorage.setItem('email', email.value);\n localStorage.setItem('password', password.value);\n location.href = 'https://rowanhorn1412.github.io/frontend2/';\n }\n}", "function saveName(text) {\n localStorage.setItem('currentUser', text);\n}", "function fbLogin(username, password) {\n if(typeof(Storage) !== \"undefined\") {\n if (localStorage.username) {\n localStorage.username = username;\n } else {\n localStorage.setItem(\"username\", username);\n localStorage.setItem(\"password\", password);\n }\n }\n}", "function setLocalStorage(){\r\n var playerSetter = JSON.stringify(allPlayers);\r\n localStorage.setItem('players', playerSetter);\r\n}", "rememberLS(e){\n\t\tif (this.DOMElems.remember.checked){\n\t\t\tconst loginValue = this.DOMElems.email.value;\n\t\t\tconst passValue = this.DOMElems.password.value;\n\t\t\tlet temp = [];\n\t\t\ttemp.push(loginValue,passValue); \n\t\t\tlocalStorage.setItem('temp', JSON.stringify(temp));\n\t\t} else {\n\t\t\tlocalStorage.removeItem('temp');\n\t\t}\n\t}", "getLocalStorageUser() {\n return JSON.parse(localStorage.getItem('user'))\n }", "function setSessionStorage(email, accessToken, idToken, displayName, profilePicture, userUid)\n{\n sessionStorage.setItem('display_name_firebase', displayName);\n sessionStorage.setItem('profile_picture_firebase', profilePicture);\n sessionStorage.setItem('email_firebase', email);\n sessionStorage.setItem('access_token_firebase', accessToken);\n sessionStorage.setItem('id_token_firebase', idToken);\n sessionStorage.setItem('uid_firebase', userUid);\n}", "function setProfileFromLS() {\n if (\n localStorage.getItem('customer') != null &&\n localStorage.getItem('customer') != 'undefined'\n ) {\n let localST = JSON.parse(localStorage.getItem('customer'))\n $('#validationCustom01').val(localST.firstName)\n $('#validationCustom02').val(localST.lastName)\n $('#validationCustom03').val(localST.email)\n $('#validationCustom04').val('*************')\n $('#validationCustom05').val(localST.number)\n $('#validationCustom06').val(localST.address.street)\n $('#validationCustom07').val(localST.address.city)\n $('#validationCustom08').val(localST.address.zipcode)\n $('#welcomeText').text('Hej ' + localST.firstName + ' ' + localST.lastName)\n $('#welcomeEmail').text(localST.email)\n }\n}", "function initializeUsers() {\n username = localStorage.getItem('staySignedInAs')\n if (username !== null) {\n useDefaults = localStorage.getItem('Defaults Used?' + username + 'Kixley@65810')\n useDefaults = parseBool(useDefaults)\n if (useDefaults === false) {\n useDefaultDiff = localStorage.getItem('Default Diff Used?' + username + 'Kixley@65810')\n useDefaultDiff = parseBool(useDefaultDiff)\n useDefaultClass = localStorage.getItem('Default Class Used?' + username + 'Kixley@65810')\n useDefaultClass = parseBool(useDefaultClass)\n }\n }\n}", "function save() {\r\n //recupero il valore (.value) inserito dall'utente nel campo che ha id 'username'\r\n let inseredUsername = document.getElementById(\"username\").value;\r\n\r\n //recupero il valore (.value) inserito dall'utente nel campo che ha id 'password'\r\n let inseredPassword = document.getElementById(\"password\").value;\r\n\r\n //salvo questi valori nel local storage:\r\n localStorage.setItem('username', inseredUsername) //key = username, value = inseredUsername (ovvero ciò che ha scritto l'utente)\r\n localStorage.setItem('password', inseredPassword)\r\n}", "function asignarUsuario(){\n usuarioActual = localStorage.getItem('nombre');\n document.getElementById(\"nombreUsuario\").value = usuarioActual;\n}", "function persistLocalStorage() {\n _localStorage.setItem(_name, this.toJSON());\n }", "function addStorage(employeeDetails) {\n localStorage.setItem(\"userDetails\", JSON.stringify(employeeDetails));\n}", "UPDATE_USER_INFO(state, payload) {\n\t\t// Get Data localStorage\n\t\tlet userInfo = JSON.parse(localStorage.getItem('userInfo')) || state.AppActiveUser;\n\n\t\tfor (const property of Object.keys(payload)) {\n\t\t\tif (payload[property] != null) {\n\t\t\t\t// If some of user property is null - user default property defined in state.AppActiveUser\n\t\t\t\tstate.AppActiveUser[property] = payload[property];\n\n\t\t\t\t// Update key in localStorage\n\t\t\t\tuserInfo[property] = payload[property];\n\t\t\t}\n\t\t}\n\t\t// Store data in localStorage\n\t\tlocalStorage.setItem('userInfo', JSON.stringify(userInfo));\n\t}", "function setLocalStorageData() {\n if ($.isEmptyObject(localStorage.inUse)) {\n //Set defaults\n localStorage.inUse = 'true';\n localStorage.sounds = 'true';\n localStorage.tracking = 'true';\n localStorage.logggedWorkouts = '[]';\n }\n if ($.isEmptyObject(localStorage.logggedWorkouts)) {\n localStorage.logggedWorkouts = '[]';\n $('#previousworkout-btn').hide();\n } else if (localStorage.logggedWorkouts === '[]') {\n $('#previousworkout-btn').hide();\n }\n if (localStorage.sounds === 'true') {\n $('#flip-alert').val('on');\n } else {\n $('#flip-alert').val('off');\n }\n if (localStorage.tracking === 'true') {\n $('#flip-track').val('on');\n } else {\n $('#flip-track').val('off');\n }\n }", "function setLocalStorage(fieldName, value) {\n\twindow.localStorage.setItem(fieldName, JSON.stringify(value));\t\n}", "function saveSettingsLocalStorage(){\n settingsObject = {email: emailSwitch.checked, profile: profileSwitch.checked, timezone: timezoneSelect.selectedIndex}; \n localStorage.setItem('settings', JSON.stringify(settingsObject));\n \n}", "function save() {\r\n const uname = context.user && context.user.username;\r\n const time = new Date().toLocaleTimeString();\r\n const searchValue = value.length > 0 ? value : \"\";\r\n const newData = { uname, searchValue, time };\r\n if (localStorage.getItem(\"data\") === null) {\r\n localStorage.setItem(\"data\", \"[]\");\r\n }\r\n\r\n var oldData = JSON.parse(localStorage.getItem(\"data\"));\r\n oldData.push(newData);\r\n\r\n localStorage.setItem(\"data\", JSON.stringify(oldData));\r\n }", "function fillStorage() {\n var local = {\n uid : uid,\n Time : timeLocal,\n Todos : todos\n }\n localStorage.clear();\n window.localStorage.setItem(`local`,JSON.stringify(local));\n mapping();\n}", "saveLocalStorage() {\n localStorage.setItem(\"usuario\", JSON.stringify(this.lista_usuario));\n }", "function setEmail() {\n if (emailCheck.checked === true) {\n localStorage.setItem('emailCheck', 'true')\n } else {\n localStorage.setItem('emailCheck', 'false')\n }\n}" ]
[ "0.7715453", "0.7715453", "0.7715453", "0.7715453", "0.7715453", "0.7715453", "0.7651826", "0.76277274", "0.76040643", "0.75565594", "0.75184935", "0.7391666", "0.73473936", "0.73104584", "0.7219108", "0.72054136", "0.71536237", "0.70849776", "0.7067868", "0.7016784", "0.70104706", "0.6996272", "0.6977069", "0.69717276", "0.69536275", "0.69508266", "0.6946427", "0.69305027", "0.68988323", "0.6892524", "0.68916076", "0.6878576", "0.6847472", "0.6827371", "0.6827371", "0.6812298", "0.68108875", "0.6800694", "0.67835337", "0.6730116", "0.6720124", "0.6714658", "0.66925365", "0.66896665", "0.6665712", "0.66340315", "0.66340315", "0.66249", "0.66199875", "0.6614496", "0.6602654", "0.6589365", "0.65818954", "0.6579352", "0.656954", "0.6547998", "0.65478224", "0.65470666", "0.6546584", "0.65450597", "0.6541667", "0.6538161", "0.6537058", "0.6534339", "0.65325373", "0.65318", "0.65255666", "0.65227497", "0.65034556", "0.6501", "0.64934754", "0.6493355", "0.6486591", "0.6479245", "0.6478972", "0.6478407", "0.64760554", "0.64694667", "0.6459425", "0.6457526", "0.64560884", "0.64516556", "0.6440668", "0.6430521", "0.64274377", "0.6424607", "0.6408535", "0.6408025", "0.6400371", "0.6398888", "0.63940936", "0.63934964", "0.63853335", "0.63847435", "0.6373392", "0.63725686", "0.6366853", "0.63614947", "0.6353725", "0.6346994" ]
0.89102155
0
Stores recipes and length in the local storage
function setRecipeFromLocalStorage(recipe) { var recipes = localStorage.getItem("recipes"); recipes = JSON.parse(recipes); console.log(recipes); console.log(recipe + " to be added"); if (recipes == null) { var recipes = []; recipes[0] = recipe; console.log(recipes); var index = 1; localStorage.setItem("length", index); } else { var index = localStorage.getItem("length"); recipes[index++] = recipe; console.log(recipes); console.log(index); localStorage.setItem("length", index); } localStorage.setItem("recipes", JSON.stringify(recipes)); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "saveNewRecipe() {\n if (this.state.newestRecipe.recipeName && this.state.newestRecipe.ingredients) {\n let recipes = this\n .state\n .recipes\n .slice();\n recipes.push({recipeName: this.state.newestRecipe.recipeName, ingredients: this.state.newestRecipe.ingredients});\n localStorage.setItem(\"recipes\", JSON.stringify(recipes));\n this.setState({recipes});\n this.setState({\n newestRecipe: {\n recipeName: \"\",\n ingredients: []\n }\n })\n }\n this.close();\n }", "saveRecipe() {\n // read recipes is none -> create recipes\n let recipes = localStorage.getItem(\"recipes\")\n let info = {\n title: shortTxt(this.recipe.title),\n publisher: this.recipe.publisher,\n image_url: this.recipe.image_url,\n recipe_id: this.recipe.recipe_id,\n }\n if (!recipes) {\n localStorage.setItem(\"recipes\", JSON.stringify([info]))\n } else {\n let data = JSON.parse(recipes)\n if (data.map(info_ => info_.recipe_id).includes(info.recipe_id)){\n // delete rid\n data = data.filter(info_ => info_.recipe_id !== info.recipe_id)\n console.log(data)\n } else{\n // add rid\n data.push(info)\n }\n localStorage.setItem(\"recipes\", JSON.stringify(data))\n }\n }", "_commit(recipes) {\n this.onRecipesChanged(recipes);\n localStorage.setItem('recipes', JSON.stringify(recipes));\n }", "function saveData() {\n let recipe = getValues();\n let encodedUrl = encodeURI(url);\n let dataToStore = {};\n dataToStore[encodedUrl] = recipe;\n chrome.storage.local.set(dataToStore, () => { });\n}", "function initializeRecipes(){\n\t\t\t\t\t\t\t\n\n\n\tvar arrayofrecipes = [];\n\tObject.keys(localStorage).map((key,index)=>{\n\t\tarrayofrecipes.push({index:index,title:key,ingredient:localStorage[key]})\n\t})\n\treturn arrayofrecipes;\n}", "function foodRecipes() \n{\n var myFood = JSON.parse(localStorage.getItem(\"myFood\"))\n console.log(myFood);\n\n // Loop through the local storage array and create cards for the recipes\n for (let i = 0; i < myFood.length; i++) \n {\n // Create the divs and add the classes / attributes\n let foodCardDiv = $(\"<div>\").addClass(\"col s12 m6 xl4 recipe\");\n let imgCardDiv = $(\"<div>\").addClass(\"card large hoverable\");\n let imgDiv = $(\"<div>\").addClass(\"card-image waves-effect waves-block waves-light\");\n let recipeImg = $(\"<img>\").attr(\"src\", myFood[i][\"img\"]).addClass(\"activator\");\n let recipeTitleDiv = $(\"<div>\").addClass(\"card-content\");\n let titleDivSpan = $(\"<span>\").addClass(\"card-title grey-text text-darken-4\");\n let showRecipe = $(\"<i>more_vert</i>\").addClass(\"s1 material-icons right activator\");\n let recipeTitle = $(\"<h5>\" + myFood[i][\"label\"] + \"</h5>\").addClass(\"s9\");\n let recipeDiv = $(\"<div>\").addClass(\"card-reveal\");\n let recipeDivSpan = $(\"<span>\" + myFood[i][\"label\"] + \"</span>\").addClass(\"card-title grey-text text-darken-4\");\n let closeRecipe = $(\"<i>\" + \"close\" + \"</i>\").addClass(\"material-icons right\");\n let recipeHeader = $(\"<h6>Recipe:</h6>\");\n let recipeText = $(\"<p> Find out how to cook this dish: <a href=\" + myFood[i][\"url\"] + \" target='_blank'>\" + myFood[i][\"url\"] + \"</p>\");\n \n // Append the divs to the container\n\n titleDivSpan.append(showRecipe);\n recipeDiv.append(recipeDivSpan);\n recipeDivSpan.append(closeRecipe);\n recipeTitleDiv.append(titleDivSpan);\n recipeTitleDiv.append(recipeTitle);\n imgDiv.append(recipeImg);\n imgCardDiv.append(imgDiv);\n imgCardDiv.append(recipeTitleDiv);\n imgCardDiv.append(recipeDiv);\n foodCardDiv.append(imgCardDiv);\n recipeDiv.append(recipeHeader);\n recipeDiv.append(recipeText);\n \n $(\"#myRecipes\").append(foodCardDiv); \n }\n}", "function publish_recipe(){\r\n const recipeName = document.getElementById(\"name\");\r\n const description = document.getElementById(\"description\");\r\n const ingredients = document.getElementById(\"ingredients\");\r\n const instructions = document.getElementById(\"instructions\");\r\n if(recipeName.value != '' && description.value != '' && ingredients.value != '' && instructions.value != ''){\r\n var recipe_info = {\r\n 'img' : uploadedImage,\r\n 'name' : recipeName.value,\r\n 'description' : description.value,\r\n 'ingredients' : ingredients.value,\r\n 'instructions' : instructions.value\r\n }\r\n myRecipesArray.push(recipe_info);\r\n localStorage.setItem('myRecipes', JSON.stringify(myRecipesArray));\r\n document.querySelector('#myFileInput').value = '';\r\n recipeName.value = '';\r\n description.value = '';\r\n ingredients.value = '';\r\n instructions.value = '';\r\n }\r\n else{\r\n alert(\"Please complete the fields\");\r\n }\r\n}", "function save() {\n localStorage.productData = JSON.stringify(Product.allProducts);\n localStorage.totalCounter = totalCounter;\n}", "function saveAll() {\n totalCount = 0;\n foodInput = document.querySelectorAll(\".input-field\");\n localStorage.removeItem(\"foods\");\n foods= [];\n\n for(var i = 0; i < foodInput.length; i++) {\n if(foodInput[i].value.length > 0) {\n var savedFood = foodInput[i].value;\n foods.push(savedFood);\n }\n }\n localStorage.setItem(\"foods\", foods);\n setFoods(foods)\n}", "function saveFoods() {\n localStorage.setItem(\"breakfast\", JSON.stringify(breakfast));\n localStorage.setItem(\"lunch\", JSON.stringify(lunch));\n localStorage.setItem(\"dinner\", JSON.stringify(dinner));\n}", "updateRecipeName(recipeName, currentIndex) {\n let recipes = this\n .state\n .recipes\n .slice();\n recipes[currentIndex] = {\n recipeName: recipeName,\n ingredients: recipes[currentIndex].ingredients\n };\n localStorage.setItem(\"recipes\", JSON.stringify(recipes));\n this.setState({recipes});\n }", "updateIngredients(ingredients, currentIndex) {\n let recipes = this\n .state\n .recipes\n .slice();\n recipes[currentIndex] = {\n recipeName: recipes[currentIndex].recipeName,\n ingredients: ingredients\n };\n localStorage.setItem(\"recipes\", JSON.stringify(recipes));\n this.setState({recipes});\n }", "function writeRecipesToDatabase(recipes){\n db.serialize(function() {\n\n //Here we will drop the current files in the database and work with the new ones that we are creating now\n var serverStringNeeded = \"DROP TABLE IF EXISTS recipes\";\n db.run(serverStringNeeded);\n\n\t //this will create a new table within the database\n serverStringNeeded = \"CREATE TABLE IF NOT EXISTS recipes (id INTEGER PRIMARY KEY, recipe_name TEXT, contributor TEXT, category TEXT, description TEXT, spices TEXT, source TEXT, rating TEXT, ingredients TEXT, directions TEXT)\";\n\n db.run(serverStringNeeded);\n\n var stmt = db.prepare(\"INSERT INTO recipes (recipe_name,contributor,category,description,spices,source,rating,ingredients,directions) VALUES (?,?,?,?,?,?,?,?,?)\");\n for (var i = 0; i < recipes.length; i++) {\n \t recipe = recipes[i];\n stmt.run(recipe.recipe_name, recipe.contributor, recipe.category, recipe.description, recipe.spices, recipe.source, recipe.rating, recipe.ingredients, recipe.directions);\n }\n stmt.finalize();\n });\n}", "getData() {\n var data = [];\n if (typeof(Storage) !== \"undefined\") {\n data = localStorage.getItem(\"recipes\");\n if (data !== null) {\n data = JSON.parse(data);\n } else {\n data = mockData;\n }\n } else {\n console.log(\"WARNING: no local storage, cannot save recipes.\");\n }\n// DEBUG: dump the contents of localStorage\n//console.log(data);\n return data;\n }", "static storeFood(item) {\n const items = Storage.getFoods();\n\n items.push(item);\n localStorage.setItem('foods', JSON.stringify(items));\n }", "function getRecipesFromLocalStorage() {\n if (localStorage.getItem(\"recipes\")) {\n recipes = localStorage.getItem(\"recipes\");\n return JSON.parse(recipes);\n } else {\n return false;\n }\n}", "function storeData(){\r\n localStorage.setItem(\"selections\", JSON.stringify(selections));\r\n}", "function saveKittens() {\r\n window.localStorage.setItem(\"kittens\", JSON.stringify(kittens))\r\n window.localStorage.setItem(\"Names\", JSON.stringify(namesArray))\r\n drawKittens()\r\n}", "handleNewRecipe(ingredientsArray, recipeName) {\n localStorage.recipe = recipeName;\n localStorage.ingredients = ingredientsArray; \n this.state.listArray.push({recipe: recipeName, ingredients: ingredientsArray});\n this.setState({recipe: recipeName, ingredients: ingredientsArray});\n }", "function saveKittens() {\r\n\r\n\r\n //save kittens to local storage\r\n window.localStorage.setItem(\"kittens\", JSON.stringify(kittens));\r\n\r\n}", "function saveKittens() {\n window.localStorage.setItem(\"kittens\", JSON.stringify(kittens))\n window.localStorage.setItem(\"kittenNameTracker\", JSON.stringify(kittenNameTracker))\n}", "function saveLocally(date, mealType, calories, foodName) {\n\n\n //console.log('storing in ' + number)\n //window.localStorage.setItem(number + '', post)\n\n window.localStorage.setItem(date + '', mealType + \"/\" + calories + \"/\" + foodName)\n \n //can we change items? I think we can\n\n //we need to add multiple food mealtimes per day. how can we make it efficient?\n\n //clearScreen()\n //populate()\n}", "function saveNotes() {\n localStorage.setItem(\"notes\", JSON.stringify(notes));\n localStorage.setItem(\"notesLength\", c);\n}", "function saveData() {\n if (localStorage != null && JSON != null) {\n localStorage[\"size\"] = JSON.stringify(size);\n localStorage[\"cartData\"] = JSON.stringify(cartData);\n }\n }", "deleteRecipe(rid) {\n // read recipes delete rid\n let data = JSON.parse(localStorage.getItem(\"recipes\"))\n data = data.filter(info => info.recipe_id !== rid)\n localStorage.setItem(\"recipes\", JSON.stringify(data))\n }", "function localStoreMaker(){\n var productsInStorage=localStorage.getItem('countedVotesStore');\n if (!productsInStorage){\n initializeProducts();\n console.log('initialized', localStorage.length);\n localStorage.setItem('countedVotesStore', JSON.stringify(allProducts));\n }\n else{\n allProducts= JSON.parse(localStorage.getItem('countedVotesStore'));\n }\n}", "function populateStorage() {\n const bookOne = ['Budapeste', 'Chico Buarque de Holanda', 174, true];\n const bookTwo = [\n 'Will my cat eat my eyeballs?',\n 'Caitlin Doughty',\n 222,\n true,\n ];\n const bookThree = ['The Time Machine', 'H.G. Wells', 118, true];\n localStorage.setItem('book1', JSON.stringify(bookOne));\n localStorage.setItem('book2', JSON.stringify(bookTwo));\n localStorage.setItem('book3', JSON.stringify(bookThree));\n}", "function getRecipeData(e) {\n var getMealData = JSON.parse(localStorage.getItem(\"meal\"));\n var mealId = e.target.getAttribute(\"data-id\");\n var selected = getMealData.filter((meal) => meal.idMeal === mealId);\n\n if (selected.length > 0) {\n selected = selected[0];\n }\n hideRecipe.classList.remove(\"hidden\");\n foodPoster.src = selected.strMealThumb;\n foodTitle.innerText = selected.strMeal;\n methodText.innerText = selected.strInstructions;\n\n const ingredients = [];\n for (let i = 1; i <= 20; i++) {\n if (selected[`strIngredient${i}`]) {\n ingredients.push(\n `${selected[`strMeasure${i}`]} - ${selected[`strIngredient${i}`]}`\n );\n } else {\n break;\n }\n }\n ingredientEl.innerHTML = `${ingredients\n .map((ingredients) => `<li>${ingredients}</li>`)\n .join(\"\")}`;\n}", "function save() {\n localStorage.setItem(\"toys\", toys);\n localStorage.setItem(\"click\", mClickUpgrade.amount);\n localStorage.setItem(\"autoClicker\", mAutoClicker.amount);\n localStorage.setItem(\"multiplier\", mMultiplier.amount);\n localStorage.setItem(\"toyShop\", mToyShop.amount);\n localStorage.setItem(\"toyFactory\", mToyFactory.amount);\n localStorage.setItem(\"hiddenToyLayer\", mHiddenToyLayer.amount);\n}", "function postData() {\n\n //let size = window.localStorage.getItem(0 + '')\n\n date = document.getElementById(\"dateInput\").value\n mealType = document.getElementById(\"mealType\").value\n calories = document.getElementById(\"calories\").value\n foodName = document.getElementById(\"foodName\").value\n\n //convert date to usable string\n //we can do so by making the key just\n //6302023\n //take out all the slashes and all\n\n saveLocally(date, mealType, calories, foodName)\n //document.getElementById(\"postIt\").value = \"\"\n //console.log(post)\n //let clone = document.getElementById(\"post\").cloneNode(true);\n //clone.innerHTML = post\n //clone.style.backgroundColor = \"lightgreen\"\n //document.getElementById(\"post\").appendChild(clone)\n\n //added new item, need to change the size\n //let size = window.localStorage.getItem(0 + '')\n //if (size == '0') {\n // console.log('in postIt method and size is 0')\n // size = 1\n //}\n //else {\n // size = Math.floor(size)\n // size += 1\n //}\n\n //window.localStorage.setItem(0 + '', size)\n\n saveLocally(size, post)\n}", "function saveLocalStorage() {\n const userInput9 = localStorage.getItem('9');\n $('#9')\n .children('.description')\n .text(userInput9);\n\n const userInput10 = localStorage.getItem('10');\n $('#10')\n .children('.description')\n .text(userInput10);\n\n const userInput11 = localStorage.getItem('11');\n $('#11')\n .children('.description')\n .text(userInput11);\n\n const userInput12 = localStorage.getItem('12');\n $('#12')\n .children('.description')\n .text(userInput12);\n\n const userInput1 = localStorage.getItem('13');\n $('#13')\n .children('.description')\n .text(userInput1);\n\n const userInput2 = localStorage.getItem('14');\n $('#14')\n .children('.description')\n .text(userInput2);\n\n const userInput3 = localStorage.getItem('15');\n $('#15')\n .children('.description')\n .text(userInput3);\n\n const userInput4 = localStorage.getItem('16');\n $('#16')\n .children('.description')\n .text(userInput4);\n\n const userInput5 = localStorage.getItem('17');\n $('#17')\n .children('.description')\n .text(userInput5);\n }", "function view_recipe(img, name, description, ingredients, instructions){\r\n var recipe_info = {\r\n 'img' : img,\r\n 'name' : name,\r\n 'description' : description,\r\n 'ingredients' : ingredients,\r\n 'instructions' : instructions\r\n }\r\n viewRecipeArray = [];\r\n sessionStorage.setItem('viewRecipe', JSON.stringify(viewRecipeArray))\r\n viewRecipeArray.push(recipe_info);\r\n sessionStorage.setItem('viewRecipe', JSON.stringify(viewRecipeArray))\r\n}", "function saveKittens() {\n console.log(\"enter saveKittens()\");\n window.localStorage.setItem(\"kittens\", JSON.stringify(kittens));\n console.log(\"saveKittens() Success\");\n drawKittens();\n}", "store() {\n\t\tlet storeData = this.data.map(wfItem => wfItem.storeVersion());\n\t\tlocalStorage.setItem('data', JSON.stringify(storeData));\n\t}", "function saveBopsAndHops() {\n localStorage.setItem(\"currentAlcohol\", JSON.stringify(alcohol));\n localStorage.setItem(\"currentArtist\", JSON.stringify(artist));\n}", "function saveMeal() {\n var chosenMeal = getMeal.meals[0];\n var savedMeal = localStorage.getItem(\"meal\");\n if (!savedMeal || savedMeal === null || savedMeal === \"null\") {\n savedMeal = [];\n } else {\n savedMeal = JSON.parse(savedMeal);\n }\n var selected = savedMeal.filter(\n (meal) => meal.idMeal === getMeal.meals[0].mealId\n );\n\n if (selected.length > 0) {\n return;\n }\n // Add new favourite recipe into local storage and create button\n savedMeal.push(chosenMeal);\n localStorage.setItem(\"meal\", JSON.stringify(savedMeal));\n var newMeal = document.createElement(\"button\");\n newMeal.classList.add(\"favouritesBtn\");\n newMeal.textContent = getMeal.meals[0].strMeal;\n newMeal.setAttribute(\"data-id\", getMeal.meals[0].idMeal);\n favRecipes.appendChild(newMeal);\n}", "function addItem() {\n\tvar num = Math.floor(Math.random() * 10000);\n\tvar item = {}\n\tconsole.log(document.getElementById(\"servingsize\").value);\n\tvar curmeal = JSON.parse(localStorage.getItem(\"curMeal\"));\n\titem.name = document.getElementById(\"foodname\").value;\n\titem.servingType = document.getElementById(\"servingtype\").value;\n\titem.servingSize = document.getElementById(\"servingsize\").value;\n\titem.carbCount = 10;\n\titem.id = num;\n\tcurmeal.push(item);\n\t\n\tlocalStorage.setItem(\"curMeal\", JSON.stringify(curmeal));\n\t\n\n}", "function saveValues() {\n\tstorage.hiscore2 = hiscore;\n\tstorage.longest2 = longest;\n\tstorage.speed2 = speed;\n}", "function bringNotes() {\n if (localStorage.getItem(\"notes\") != null) {\n notes = JSON.parse(localStorage.getItem(\"notes\"));\n } else {\n notes = [];\n }\n console.log(notes.length);\n if (localStorage.getItem(\"notesLength\") != null)\n c = parseInt(localStorage.getItem(\"notesLength\"));\n console.log(c);\n console.log(notes);\n}", "function storeEntryInLocalStorage(text, amount) {\n let entries;\n if (localStorage.getItem('entries') === null) {\n entries = [];\n } else {\n entries = JSON.parse(localStorage.getItem('entries'));\n }\n entries.push({ inputTxt: text, InputAmnt: amount });\n localStorage.setItem('entries', JSON.stringify(entries));\n}", "function housekeeping() {\n ingredients = \"\";\n spoonlength = \"\";\n}", "async function save() {\n await localStorage.setItem(\n KEY,\n JSON.stringify({\n path,\n text,\n revision,\n lineCount,\n store: store.getState()\n })\n );\n }", "function saveGolds() {\n localStorage.setItem(\"golds\", golds);\n}", "function sendRecipeData(data)\r\n\t{\r\n\t\tvar video;\r\n\t\tvideo = data.meals[0].strYoutube;\r\n\t\tvideo = video.substr(32, 43);\r\n\t\tlocalStorage.setItem(\"foodTitle\", data.meals[0].strMeal);\r\n\t\tlocalStorage.setItem(\"foodImage\", data.meals[0].strMealThumb);\r\n\t\tlocalStorage.setItem(\"i1\", data.meals[0].strMeasure1 + \" \" + data.meals[0].strIngredient1);\r\n\t\tlocalStorage.setItem(\"i2\", data.meals[0].strMeasure2 + \" \" + data.meals[0].strIngredient2);\r\n\t\tlocalStorage.setItem(\"i3\", data.meals[0].strMeasure3 + \" \" + data.meals[0].strIngredient3);\r\n\t\tlocalStorage.setItem(\"i4\", data.meals[0].strMeasure4 + \" \" + data.meals[0].strIngredient4);\r\n\t\tlocalStorage.setItem(\"i5\", data.meals[0].strMeasure5 + \" \" + data.meals[0].strIngredient5);\r\n\t\tlocalStorage.setItem(\"i6\", data.meals[0].strMeasure6 + \" \" + data.meals[0].strIngredient6);\r\n\t\tlocalStorage.setItem(\"i7\", data.meals[0].strMeasure7 + \" \" + data.meals[0].strIngredient7);\r\n\t\tlocalStorage.setItem(\"i9\", data.meals[0].strMeasure8 + \" \" + data.meals[0].strIngredient8);\r\n\t\tlocalStorage.setItem(\"i10\", data.meals[0].strMeasure10 + \" \" + data.meals[0].strIngredient10);\r\n\t\tlocalStorage.setItem(\"i11\", data.meals[0].strMeasure11 + \" \" + data.meals[0].strIngredient11);\r\n\t\tlocalStorage.setItem(\"i12\", data.meals[0].strMeasure12 + \" \" + data.meals[0].strIngredient12);\r\n\t\tlocalStorage.setItem(\"i13\", data.meals[0].strMeasure13 + \" \" + data.meals[0].strIngredient13);\r\n\t\tlocalStorage.setItem(\"i14\", data.meals[0].strMeasure14 + \" \" + data.meals[0].strIngredient14);\r\n\t\tlocalStorage.setItem(\"i15\", data.meals[0].strMeasure15 + \" \" + data.meals[0].strIngredient15);\r\n\t\tlocalStorage.setItem(\"i16\", data.meals[0].strMeasure16 + \" \" + data.meals[0].strIngredient16);\r\n\t\tlocalStorage.setItem(\"i17\", data.meals[0].strMeasure17 + \" \" + data.meals[0].strIngredient17);\r\n\t\tlocalStorage.setItem(\"i18\", data.meals[0].strMeasure18 + \" \" + data.meals[0].strIngredient18);\r\n\t\tlocalStorage.setItem(\"i19\", data.meals[0].strMeasure19 + \" \" + data.meals[0].strIngredient19);\r\n\t\tlocalStorage.setItem(\"i20\", data.meals[0].strMeasure20 + \" \" + data.meals[0].strIngredient20);\r\n\t\t\r\n\t\tlocalStorage.setItem(\"Instructions\", data.meals[0].strInstructions);\r\n\t\tlocalStorage.setItem(\"cookVid\", video);\r\n\r\n\t\t\r\n\t}", "function storeData() {\n var foodObject = { //store data as an object that Results Page can use\n name: foodName,\n allergy: userAllergy,\n category: categoryInput,\n item: upcInput,\n searchResult: safeToEat,\n image: foodImg,\n }\n localStorage.setItem(foodName, JSON.stringify(foodObject));\n localStorage.setItem(\"lastKey\", foodName);\n resultsScreen(); //call function to redirect to the Results Screen after data is stored\n}", "function storingBottlesaAndState(){\n\n\t\tvar purchaseDetails = {\n\t\t\t\n\t\t\tbottleTotal: quantitySelected(),\n\t\t\tstateChosen: document.getElementById(\"selectStateOption\").value\n\t\t};\n\t\t\n\t\tvar json = JSON.stringify(purchaseDetails);\n\t\tlocalStorage.setItem(\"purchaseDetails\", json);\n\t} // End localStorage ", "function saveData(key){\n\t\t//If there is no key, this is a new item and we need to create an id, otherwise we set id to\n\t\t//existing key to it will save over the original data\n\t\tif(!key){\n\t\t//create unique identifier key\n\t\t\tvar id = Math.floor(Math.random()*100000001);\n\t\t}else{\n\t\t\tid = key;\n\t\t}\t\n\t\t\t\n\t\t\t\n\t\t//get values of Checkboxes and Radios first\n\t\t\t\t\n\t\tcheckRadio();\n\t\tcheckCheckboxes();\t\t\n\t\t\t\n\t\t// Can setItems individually\t\t\n\t\t// localStorage.setItem(\"drug\",$('drug').value); //local storage can ONLY store strings\n\t\t// \tlocalStorage.setItem(\"dosage\",$('dosage').value + \" \" + $('drugUnits').value);\n\t\t// \tlocalStorage.setItem(\"frequency\",$('freqAmnt').value + \" \" +$('freqTime').value);\n\t\t// \tlocalStorage.setItem(\"drugType\", radioChecked);\n\t\t// \tlocalStorage.setItem(\"refill needed\", refill);\n\t\t// \tlocalStorage.setItem(\"doctor\", $('doctor').value);\n\t\t// \tlocalStorage.setItem(\"doctor's phone\", $('docPhone').value);\n\t\t// \tlocalStorage.setItem(\"instructions\", $('instructions').value);\n\t\t// \tlocalStorage.setItem(\"notes\", $('notes').value);\n\t\t\n\t\t\n\t\tvar prescription = {};\n\t\t\tprescription.drug \t= [\"Drug name:\", $('drug').value];\n\t\t\tprescription.dosage = [\"Dosage:\", $('dosage').value + \" \"];\n\t\t\tprescription.units = [\"Units:\", $('drugUnits').value];\n\t\t\tprescription.frequencyAmnt = [\"Frequency Amount:\", $('freqAmnt').value + \" \"];\n\t\t\tprescription.frequencyTime = [\"Frequency Time:\",$('freqTime').value];\n\t\t\tprescription.drugType = [\"Type of Prescription:\", radioChecked];\n\t\t\tprescription.refillNeeded = [\"Refill Needed:\", refill];\n\t\t\tprescription.doctor = [\"Prescribing Doctor's name:\", $('doctor').value];\n\t\t\tprescription.docPhone =[\"Doctor's phone:\", $('docPhone').value];\n\t\t\tprescription.instructions = [\"Instructions:\", $('instructions').value];\n\t\t\tprescription.notes = [\"Notes:\", $('notes').value];\n\t\t\n\t\t//Save data into Local Storage: Use Stringify to convert object to a string\n\t\t\n\t\tlocalStorage.setItem(id, JSON.stringify(prescription));\n\t\n\t\n\t\tconsole.log(\"data stored\");\n\t\t\n\t\t//e.preventDefault(); //Don't need this here anymore because validation fn prevents the refresh\n\t\t//return false;\n\t\t\n\t}", "function getRecipe() {\n // same as before, gets ID\n var mainContainer = document.getElementById(\"myRecipe\");\n // gets stored URI\n let getURI = localStorage.getItem(\"uri\");\n console.log(getURI);\n fetch(getURI, {\n method: \"GET\",\n })\n .then((response) => response.json())\n .then(function (data) {\n console.log(data.recipe);\n var div = document.createElement(\"div\");\n \n // get all needed objects within object\n // will use map method to output data within template literal\n \n var obj = data.recipe.ingredientLines;\n var nutritional = data.recipe.totalNutrients;\n var daily = data.recipe.totalDaily;\n console.log(nutritional);\n div.classList.add(\"columns\");\n div.innerHTML = `\n <div class=\"column is-4 recipe-photo\">\n <img src=\"${data.recipe.image}\" style=\"width:100%;\"> \n </div>\n <div class=\"column is-8\">\n <h3>${data.recipe.label}</h3> \n <strong>Yield:</strong> ${data.recipe.yield}<br />\n <strong>Prep Time:</strong> ${data.recipe.totalTime} minutes\n <hr />\n <p><strong>Ingredients:</strong></p>\n <ul>\n ${Object.keys(obj)\n .map(function (key) {\n return \"<li>\" + obj[key] + \"</li>\";\n })\n .join(\"\")}\n </ul>\n <hr />\n <p><strong>Nutritional Data:</strong></p>\n <ul>\n ${Object.keys(daily)\n .map(function (key) {\n return (\n \"<li>\" +\n daily[key].label +\n \": \" +\n daily[key].quantity.toFixed(2) +\n daily[key].unit +\n \"</li>\"\n );\n })\n .join(\"\")}\n </ul>\n <hr />\n <strong>Daily Amounts:</strong>\n <ul>\n ${Object.keys(nutritional)\n .map(function (key) {\n return (\n \"<li>\" +\n nutritional[key].label +\n \": \" +\n nutritional[key].quantity.toFixed(2) +\n nutritional[key].unit +\n \"</li>\"\n );\n })\n .join(\"\")}\n </ul>\n </div>\n `;\n mainContainer.appendChild(div);\n })\n .catch((error) => {\n console.error(\"Error:\", error);\n });\n}", "function addFoodToLocalDatabase(food) {\r\n\r\n function addFood_findMicronutrientValue(attribute_ID){\r\n for(let i = 0; i < food[\"full_nutrients\"].length; i++) {\r\n if(attribute_ID == food[\"full_nutrients\"][i][\"attr_id\"]){\r\n return food[\"full_nutrients\"][i][\"value\"];\r\n }\t\r\n }\r\n return \"0\"; // not found probably means zero amount\r\n }\r\n\r\n \r\n let serving = food[\"serving_weight_grams\"];\r\n function helperNormalize(item){\r\n return Math.round((item * 100 / serving) * 100) / 100;\r\n }\r\n //create the food's nutrition dictionary object\r\n\r\n //first, normalize to 100g serving sizes\r\n var food_localData = {\r\n \"name\": food[\"food_name\"],\r\n \"serving\": 100,\r\n \"calories\": helperNormalize(food[\"nf_calories\"]),\r\n \"carbohydrates\": helperNormalize(food[\"nf_total_carbohydrate\"]),\r\n \"proteins\": helperNormalize(food[\"nf_protein\"]),\r\n \"fats\": helperNormalize(food[\"nf_total_fat\"]),\r\n \"iron\": helperNormalize(addFood_findMicronutrientValue(303)),\r\n \"vitaminD\": helperNormalize(addFood_findMicronutrientValue(324)),\r\n \"vitaminB12\": helperNormalize(addFood_findMicronutrientValue(418)),\r\n \"calcium\": helperNormalize(addFood_findMicronutrientValue(301)),\r\n \"magnesium\": helperNormalize(addFood_findMicronutrientValue(304)),\r\n };\r\n \r\n var food_localData_original = {\r\n \"name\": food[\"food_name\"],\r\n \"serving\": food[\"serving_weight_grams\"],\r\n \"calories\": food[\"nf_calories\"],\r\n \"carbohydrates\": food[\"nf_total_carbohydrate\"],\r\n \"proteins\": food[\"nf_protein\"],\r\n \"fats\": food[\"nf_total_fat\"],\r\n \"iron\": addFood_findMicronutrientValue(303),\r\n \"vitaminD\": addFood_findMicronutrientValue(324),\r\n \"vitaminB12\": addFood_findMicronutrientValue(418),\r\n \"calcium\": addFood_findMicronutrientValue(301),\r\n \"magnesium\": addFood_findMicronutrientValue(304),\r\n };\r\n\r\n\r\n //next, try to determine tags\r\n let tags = [];\r\n\r\n if( ((food_localData[\"proteins\"] * 4) > (0.4 * food_localData[\"calories\"])) || (food_localData[\"proteins\"] > 20)){\r\n tags.push(\"High Proteins\");\r\n }\r\n else if( (food_localData[\"proteins\"] * 4) < (0.2 * food_localData[\"calories\"]) || (food_localData[\"proteins\"] < 5)){\r\n tags.push(\"Low Proteins\");\r\n }\r\n\r\n if( (food_localData[\"carbohydrates\"] * 4) > (0.4 * food_localData[\"calories\"]) || (food_localData[\"carbohydrates\"] > 30)){\r\n tags.push(\"High Carbohydrates\");\r\n }\r\n else if( (food_localData[\"carbohydrates\"] * 4) < (0.2 * food_localData[\"calories\"]) || (food_localData[\"proteins\"] < 5)){\r\n tags.push(\"Low Carbohydrates\");\r\n }\r\n\r\n if( (food_localData[\"fats\"] * 9) > (0.4 * food_localData[\"calories\"]) || (food_localData[\"fats\"] > 20)){\r\n tags.push(\"High Fats\");\r\n }\r\n else if( (food_localData[\"fats\"] * 9) < (0.2 * food_localData[\"calories\"]) || (food_localData[\"proteins\"] < 5)){\r\n tags.push(\"Low Fats\");\r\n }\r\n\r\n food_localData_original[\"tags\"] = JSON.stringify(tags);\r\n generatedTags[food[\"food_name\"]] = JSON.stringify(tags);\r\n return food_localData_original;\r\n //$.post('/food-database', food_localData, null, \"json\");\r\n}", "function savealltolocalstorage() {\n console.log(\"Step 3\");\n localStorage.setItem(\"allthings\", JSON.stringify(allthings));\n}", "function localSaveVotes(){\n var savedProducts = JSON.stringify(products);\n localStorage.setItem('votes', savedProducts);\n}", "updateStore() {\n const dataToStore = {\n formulas: this.formulas,\n lastObjectId: this.lastObjectId,\n };\n localStorage.setItem(LS_FORMULAS_KEY, JSON.stringify(dataToStore));\n }", "function storeEntry() {\n localStorage.setItem(\"event1\", entry1.text());\n localStorage.setItem(\"event2\", entry2.text());\n localStorage.setItem(\"event3\", entry3.text());\n localStorage.setItem(\"event4\", entry4.text());\n localStorage.setItem(\"event5\", entry5.text());\n }", "afegirCistella(id, quant, preu, decimalsPreu, decimalsPreuSenseIva, descripcio, desc, codi,imatge, ivaId, preuCataleg, preuSenseIvaCataleg, preuSenseIva ) {\n\n\n if (localStorage.getItem(\"productesCart\") === null) {\n const productes = [{\"codi\" : id, \"unitats\" : quant, \"preu\" : preu, \"decimalsPreuCataleg\" : decimalsPreu, \"decimalsPreuSenseIva\" : decimalsPreuSenseIva , \"descripcio\": descripcio,\"descripcioCurta\" : desc , \"id\" : codi , \"imatge\" : imatge , \"ivaId\" : ivaId, \"preuCataleg\" : preuCataleg , \"preuSenseIvaCataleg\" : preuSenseIvaCataleg, \"preuSenseIva\" : preuSenseIva}];\n localStorage.setItem(\"productesCart\", JSON.stringify(productes));\n } else {\n\n const productesCart = JSON.parse(localStorage.getItem(\"productesCart\"));\n const trobat = this.trobarArticleCart(productesCart, id);\n\n if (trobat >= 0) {\n productesCart[trobat][\"unitats\"] += quant;\n\n } else {\n productesCart.push({\"codi\" : id, \"unitats\" : quant, \"preu\" : preu, \"decimalsPreuCataleg\" : decimalsPreu, \"decimalsPreuSenseIva\" : decimalsPreuSenseIva , \"descripcio\": descripcio,\"descripcioCurta\" : desc , \"id\" : codi , \"imatge\" : imatge , \"ivaId\" : ivaId, \"preuCataleg\" : preuCataleg , \"preuSenseIvaCataleg\" : preuSenseIvaCataleg, \"preuSenseIva\" : preuSenseIva});\n\n }\n\n localStorage.setItem(\"productesCart\", JSON.stringify(productesCart));\n \n }\n\n const contador = this.contarArticles();\n this.setState({ carritoCount: contador })\n localStorage.setItem(\"count\", contador);\n this.calcularTotal();\n\n\n }", "storeLessonsInStorage() {\n Storage.storeLessons(this.lessons);\n }", "function storeData() {\n let storeDate = new Date();\n let month = storeDate.getMonth() + 1;\n let day = storeDate.getDate();\n let year = storeDate.getFullYear();\n\n let fullDate1 = month + \"/\" + day + \"/\" + year + \"/\" + 1;\n let fullDate2 = month + \"/\" + day + \"/\" + year + \"/\" + 2;\n let fullDate3 = month + \"/\" + day + \"/\" + year + \"/\" + 3;\n\n let moodObject = {\n mood: getMoodLevel,\n anxiety: getMotLevel,\n stress: getStrLevel,\n };\n\n if (localStorage.getItem(fullDate1) === null) {\n window.localStorage.setItem(fullDate1, JSON.stringify(moodObject));\n } else if (\n localStorage.getItem(fullDate1) !== null &&\n localStorage.getItem(fullDate2) === null\n ) {\n window.localStorage.setItem(fullDate2, JSON.stringify(moodObject));\n } else if (\n localStorage.getItem(fullDate1) !== null &&\n localStorage.getItem(fullDate2) !== null &&\n localStorage.getItem(fullDate3) === null\n ) {\n window.localStorage.setItem(fullDate3, JSON.stringify(moodObject));\n }\n else{\n showCapped = document.getElementById('moodCap');\n showCapped.textContent = \"Daily limit Reached. You have already checked in 3 times today.\";\n showCapped.style.display = 'block'; \n }\n}", "function getRecipes () {\n setRecipes(recipesData)\n }", "function storeData(key){\n\t\t//if there is no key, this is a brand new item & we need a new key\n\t\tif(!(key)){\n\t\t\tvar id\t\t\t\t= Math.floor(Math.random()*1000000001);\n\t\t}else{\n\t\t\t//set the id to the existing key that we're editing in order to rewrite local storage\n\t\t\tid = key;\n\t\t}\n\t\t\n\t\t//Gather up all our form field values and store them in an object\n\t\t//Object properties contain array with form label and input values\n\n\t\tgetSelectedRadio();\n\t\tvar item\t\t\t= {};\n\t\t\titem.date\t\t= [\"Date: \", $('date').value];\n\t\t\titem.type\t\t= [\"Meal Type: \", $('type').value];\n\t\t\titem.group\t\t= [\"Food Group: \", groupValue];\n\t\t\titem.name\t\t= [\"Food Name: \", $('name').value];\n\t\t\titem.calories\t= [\"Calories: \", $('calories').value];\n\t\t\titem.notes\t\t= [\"Additional Notes: \", $('notes').value];\n\t\t//Save data to local storage\n\t\t\tlocalStorage.setItem(id, JSON.stringify(item));\n\t\t\talert(\"Meal Saved!\");\n\t\t\t\n\t}", "save () {\n localStorage.setItem(STORAGE_KEY, JSON.stringify(this.allMyTrips))\n }", "static addBookToStorage(whatToAdd) {\n \n //initialise new variable for storage data\n let newStoredBooks;\n\n //set variale values based on data gotten from ls\n if (storage.getStorageData() === null) {\n newStoredBooks = [];\n } else {\n newStoredBooks = storage.getStorageData();\n };\n\n newStoredBooks.push(whatToAdd);\n \n localStorage.setItem('storedBooks', JSON.stringify(newStoredBooks))\n\n }", "function getInventory() {\r\n\t// Check if values of inventory are in storage. If not, assign 0 to each\r\n\t// amount of items in the inventory\r\n\tif (localStorage.getItem(\"inventory\") === null) {\r\n\r\n\t\tvar newInventory = {\r\n\t\t\tpotions : 0,\r\n\t\t\tarrows : 0\r\n\t\t};\r\n\r\n\t\tdocument.getElementById(\"potionCount\").innerHTML = newInventory.potions;\r\n\t\tdocument.getElementById(\"arrowCount\").innerHTML = newInventory.potions;\r\n\r\n\t\t// stringify before storage because localStorage supports strings only\r\n\t\tlocalStorage.setItem(\"inventory\", JSON.stringify(newInventory));\r\n\t} else {\r\n\t\tvar inventory = JSON.parse(localStorage.getItem(\"inventory\"))\r\n\r\n\t\tdocument.getElementById(\"potionCount\").innerHTML = inventory.potions;\r\n\t\tdocument.getElementById(\"arrowCount\").innerHTML = inventory.arrows;\r\n\t}\r\n\r\n}", "function ReceitasFavoritas() {\n // const favoriteRecipes = JSON.parse(localStorage.favoriteRecipes);\n const [favoriteRecipes, setFavoriteRecipes] = useState([]);\n const [isFavorite, setIsFavorite] = useState(true);\n const { recipeMeal } = useContext(MealsContext);\n const { id } = useParams();\n /* const timeoutTextCopy = 2000;\n const [isCopied, handleCopy] = useCopyToClipboard(timeoutTextCopy); */\n useEffect(() => {\n if (!localStorage.favoriteRecipes) {\n return <p>Você ainda não tem nenhuma receita pronta.</p>;\n }\n setFavoriteRecipes(JSON.parse(localStorage.favoriteRecipes));\n }, []);\n const filterRecipes = ({ innerText }) => {\n if (innerText === 'Food') {\n const newDone = favoriteRecipes.filter((done) => (\n done.type === 'comida'\n ));\n setFavoriteRecipes(newDone);\n } else if (innerText === 'Drinks') {\n const newDone = favoriteRecipes.filter((done) => (\n done.type === 'bebida'\n ));\n setFavoriteRecipes(newDone);\n } else {\n setFavoriteRecipes(JSON.parse(localStorage.favoriteRecipes));\n }\n };\n console.log('testRecipemelas', recipeMeal);\n function FavoriteRecipeClick() {\n // eslint-disable-next-line no-shadow\n const favoriteRecipesC = JSON.parse(localStorage.getItem('favoriteRecipes'));\n if (favoriteRecipesC !== null) {\n if (isFavorite) {\n console.log('ok', recipeMeal);\n const arrayFavoriteRecipe = favoriteRecipesC.filter((item) => item.id !== id);\n localStorage.setItem('favoriteRecipes', JSON.stringify(arrayFavoriteRecipe));\n setIsFavorite(false);\n } else {\n const newFavoriteRecipe = {\n id: recipeMeal.idMeal,\n type: 'comida',\n area: recipeMeal.strArea,\n category: recipeMeal.strCategory,\n alcoholicOrNot: '',\n name: recipeMeal.strMeal,\n image: recipeMeal.strMealThumb,\n };\n const arrayFavoriteRecipe = [...favoriteRecipes, newFavoriteRecipe];\n localStorage.setItem('favoriteRecipes', JSON.stringify(arrayFavoriteRecipe));\n setIsFavorite(true);\n }\n }\n }\n\n return (\n <>\n <Header />\n <button\n className=\"button-all\"\n type=\"button\"\n data-testid=\"filter-by-all-btn\"\n onClick={ ({ target }) => { filterRecipes(target); } }\n >\n All\n </button>\n <button\n type=\"button\"\n data-testid=\"filter-by-food-btn\"\n onClick={ ({ target }) => { filterRecipes(target); } }\n >\n Food\n </button>\n <button\n className=\"button-drink\"\n type=\"button\"\n data-testid=\"filter-by-drink-btn\"\n onClick={ ({ target }) => { filterRecipes(target); } }\n >\n Drinks\n </button>\n {favoriteRecipes.map((recipe, index) => (\n <div key={ index }>\n <Link\n to={ recipe.type === 'bebida' ? `/bebidas/${recipe.id}`\n : `/comidas/${recipe.id}` }\n >\n <p data-testid={ `${index}-horizontal-name` }>\n { recipe.name }\n </p>\n <img\n src={ recipe.image }\n alt={ recipe.name }\n data-testid={ `${index}-horizontal-image` }\n />\n </Link>\n <p data-testid={ `${index}-horizontal-top-text` }>\n { recipe.type === 'comida' ? `${recipe.area} - ${recipe.category}`\n : `${recipe.alcoholicOrNot} - ${recipe.category}` }\n </p>\n {console.log(recipe)}\n <button\n data-testid={ `${index}-horizontal-share-btn` }\n type=\"button\"\n src={ shareIcon }\n >\n <img\n src={ shareIcon }\n alt=\"Compatilhar Receita\"\n />\n </button>\n <button\n data-testid={ `${index}-horizontal-favorite-btn` }\n type=\"button\"\n onClick={ FavoriteRecipeClick }\n src={ isFavorite ? blackIcon : whiteIcon }\n >\n <img\n src={ isFavorite ? blackIcon : whiteIcon }\n alt=\"Desfavoritar Receita\"\n />\n </button>\n <p data-testid={ `${index}-horizontal-done-date` }>\n { recipe.category }\n </p>\n </div>\n ))}\n </>\n );\n}", "function storeSavedInitials() {\n localStorage.setItem(\"savedInitials\", JSON.stringify(savedInitials));\n}", "function store() {\n\n \n localStorage.setItem('mem', JSON.stringify(myLibrary));\n \n}", "function guardarProductosLocalStorage() {\n localStorage.setItem(\"Carrito\", JSON.stringify(carrito));\n}", "function storeProducts() {\n let stringProduct = JSON.stringify(Product.possibleProducts);\n localStorage.setItem(\"resultingProducts\", stringProduct);\n}", "function delSavedRecipe(img, name, calories, cautions, dietLabels, healthLabels, ingredients, url){\r\n let index = savedRecipesArray.findIndex(x => x.img === img && x.name === name && x.calories === calories && x.cautions === cautions && x.dietLabels === dietLabels && x.url === url);\r\n savedRecipesArray.splice(index, 1);\r\n localStorage.setItem('recipes', JSON.stringify(savedRecipesArray));\r\n location.reload();\r\n}", "function saveAllAnswerDataToLocalStorage() {\n localStorage.setItem(\"listOfItemQA\", JSON.stringify(currentData.listOfItemQA));\n}", "function storeQuestions(questions) {\n localStorage.questions = JSON.stringify(questions);\n }", "function storeQuestions(questions) {\n localStorage.questions = JSON.stringify(questions);\n }", "function storeQuestions(questions) {\n localStorage.questions = JSON.stringify(questions);\n }", "function saveGrade() {\n\n\tvar ModuleName = ModuleNameGlobal;\n\tvar idcounter = 1;\n\n\tfor(i = 0; i < LengthofForms; i++) {\n\t\tvar grade = document.getElementById(\"grade\"+idcounter+\"\").value;\n\t\tvar weight = document.getElementById(\"weight\"+idcounter+\"\").value;\n\t\tlocalStorage.setItem(ModuleName+\"grade\"+idcounter+\"\", grade);\n\t\tlocalStorage.setItem(ModuleName+\"weight\"+idcounter+\"\", weight);\n\t\tidcounter++;\n\t\tconsole.log(\"Saving \"+ModuleName +\"\\n Grade \"+grade+\"\\n Weight \" +weight);\n\t}\n\n\tlocalStorage.setItem(ModuleName+\"numberofItems\", LengthofForms);\n\n}", "function saveData()\n{\n /***********\n * SET INT *\n ***********/\n function setInt(name, data)\n {\n // if a boolean or other, convert to an int\n if (data === true)\n data = 1;\n else if (data === false)\n data = 0;\n\n // otherwise set it normally\n if (data !== null && data !== undefined && !isNaN(data))\n localStorage.setItem(name, data);\n }\n\n // set data\n setInt('data', true);\n setInt('ax', ax);\n setInt('ay', ay);\n setInt('dx', dx);\n setInt('dy', dy);\n setInt('score', score);\n setInt('recent', recent);\n setInt('hScore', hScore);\n setInt('paused', paused);\n setInt('doWrap', doWrap);\n \n // set snake data\n setInt('length', snake.length);\n for (var i = 0; i < snake.length; i++)\n {\n setInt('snake' + i + 'x', snake[i].x);\n setInt('snake' + i + 'y', snake[i].y);\n }\n}", "function saveLocalStorage() {\n localStorage.setItem('array', JSON.stringify(glassesArray));\n localStorage.setItem('date', lastGlassAt);\n}", "function update() {\n localStorage.setItem('recipeBook', JSON.stringify(recipes));\n const rows = [];\n for (let i = 0; i < recipes.length; i++) {\n rows.push(\n <Panel header={recipes[i].title} eventKey={i} bsStyle=\"success\">\n <Recipe title={recipes[i].title} ingredients={recipes[i].ingredients} index={i} />\n </Panel>,\n );\n }\n ReactDOM.render(<RecipeBook data={rows} />, document.getElementById('container'));\n}", "function savePurchase() {\n var purchaseCounter = localStorage.getItem(\"purchase\");\n if (purchaseCounter == null) {\n purchaseCounter = 1;\n } else {\n purchaseCounter++;\n }\n\n localStorage.setItem(\"purchase\", purchaseCounter);\n\n var purchaseData = [];\n purchaseData.push(\"Película: \" + $(\"#titleFilm .emphasis\").text());\n purchaseData.push(\"Nombre: \" + $(\"#first-name\").val());\n purchaseData.push(\"Apellidos: \" + $(\"#last-name\").val());\n purchaseData.push(\"Email: \" + $(\"#address\").val());\n purchaseData.push($(\"#totalPrice .subtotal\").text());\n purchaseData.push(\"Asientos: \" + seatIDs);\n\n localStorage.setItem(\"purchase_\" + purchaseCounter, JSON.stringify(purchaseData));\n}", "function pullLocalFoods() {\n var foodList = localStorage.getItem(\"foods\");\n if (localStorage.getItem(\"foods\") === null) {\n return;\n } else {\n foods = foodList.split(\",\");\n }\n for (var k = 0; k < foods.length; k++) {\n addContainer();\n }\n setFoods(foods);\n}", "function loadStorage() {\n const keys = Object.keys(localStorage);\n let i = keys.length;\n console.log(\"i: \", i);\n\n while ( i-- ) {\n coffees.push( JSON.parse( localStorage.getItem(keys[i]) ) );\n }\n}", "function Save(){\n localStorage.setItem(\"monsterrawrs\",monstercount)\n}", "function saveData() {\n localStorage.setItem('allBooks', JSON.stringify(librayLogModal.books));\n}", "function sendIngredients() {\n window.localStorage.removeItem(\"ingredients\");\n // If ingredients are empty\n if (userIngredients !== \"\") {\n var ingredients =\n JSON.parse(window.localStorage.getItem(\"ingredients\")) || [];\n\n\n var newIngredients = {\n ingredients: userIngredients\n };\n\n // Save to Local Storage\n ingredients.push(newIngredients);\n window.localStorage.setItem(\"ingredients\", JSON.stringify(ingredients));\n }\n}", "function saveCarrito(){\n localStorage.setItem(`carrito`, JSON.stringify(carrito))\n}", "function recentFoodStorage(value) {\n if (foodStorage.length === 5) {\n foodStorage.pop();\n }\n foodStorage.unshift(value);\n localStorage.setItem(\"food\", JSON.stringify(foodStorage));\n populateRecentFood(foodStorage);\n}", "function storeData(){\n\n\t// Clean arrays\n\thiddens = [];\n\timages = [];\n\ttitles = [];\n\telements = [];\n\tresources = [];\n\tmaxLevels = [];\n\tlockReqs = [];\n\trequirements = [];\n\tinfos = [];\n\ttexts = [];\n\tlevels = [];\n\tlockeds = [];\n\t\n\t// Class_skills are the .js stuff\n\tlet skills = Class_skills;\n\t\n\t// Amount of skills (includes hidden) 6 skills per column, 4 columns.\n\tlet skillAmount = 24;\n\t\n\t// Loop that pushes the .js info into the arrays\n\tfor(let j=0; j < skillAmount; j++){\n\t\tfor(let i=0; i < skills.length; i++){\n\t\t\tif(skills[j] && skills[j][i]){\n\t\t\t\thiddens.push(skills[j][i].hidden);\n\t\t\t\timages.push(skills[j][i].image);\n\t\t\t\ttitles.push(skills[j][i].title);\n\t\t\t\tresources.push(skills[j][i].resource);\n\t\t\t\tlevels.push(skills[j][i].level);\n\t\t\t\telements.push(skills[j][i].element);\n\t\t\t\tlockeds.push(skills[j][i].locked);\n\t\t\t\tlockReqs.push(skills[j][i].lockReq);\n\t\t\t\tmaxLevels.push(skills[j][i].maxLevel);\n\t\t\t\trequirements.push(skills[j][i].requirement);\n\t\t\t\tinfos.push(skills[j][i].info);\n\t\t\t\ttexts.push(skills[j][i].texts);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t// Check for default unlocked abilities.\n\tfor(let l=0; l < lockeds.length; l++){\n\t\tif( lockeds[l] == 0 ){\n\t\t\tlockedsURL[l] = 0;\n\t\t}\n\t}\n\t\n\t// If URL have info, Use it instead\n\tif( levelsURL.length > 0 && lockedsURL.length > 0 ){\n\t\tlevels = levelsURL;\n\t\tlockeds = lockedsURL;\n\t\tlevelsURL = [];\n\t\tlockedsURL = [];\n\t}\n\n}", "function RecipeList({ recipes, onRecipeCompleted }) {\n const [points, updatePoints] = useState(0);\n\n //changing the users points in the database, possibly the level too 🙀\n function CompletedRecipe(recipeId, recipe_api_id) {\n let currentPoints = parseInt(localStorage.getItem(\"points\"));\n let currentLevel = localStorage.getItem(\"cookingLevel\")\n const data = {\n points: currentPoints,\n userId: localStorage.getItem(\"userId\"),\n recipeId: parseInt(recipeId),\n recipeApiId: recipe_api_id,\n cookingLevel: currentLevel\n };\n\n const options = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n };\n\n fetch(\"http://localhost:9000\", options)\n // turn api response into json\n .then((res) => res.json())\n .then((result) => {\n if (result.errors) {\n // do something about errors\n // setErrors(result.errors);\n // return;\n console.log(result.errors);\n }\n console.log(result);\n // store their cooking level & points back in local storage\n //localStorage.setItem(\"cookinglevel\", result.data.cooking_level)\n localStorage.setItem(\"points\", result.points);\n\n onRecipeCompleted({\n recipes: {\n ...recipes,\n completed: result.completed_recipes_array,\n },\n points: result.points,\n cooking_level: result.cooking_level\n });\n })\n .catch((err) => {\n console.log(err);\n });\n }\n return (\n \n <div>\n <br></br>\n <div> \n <br/><br/>\n <h1> Welcome to Cookwars </h1>\n </div>\n \n\n\n <table class=\"table mt-5\">\n <thead class=\"mx-auto\">\n <tr class=\"bg-red mx-auto\">\n <th className=\"train\"></th>\n <th className=\"train\">Recipes</th>\n <th className=\"train\">Train</th>\n </tr>\n </thead>\n <tbody>\n {recipes &&\n recipes.recipes &&\n recipes.recipes.map((recipe) => (\n <tr key={recipe.id.toString()}>\n <td>{recipe.id}</td>\n <td>{recipe.recipe_name}</td>\n <td>\n <Link to={`/recipe/${recipe.recipe_id}`} className=\"btn btn-primary href\"> <FontAwesomeIcon icon={faEye} size='1x'/></Link>\n {recipes.completed.includes(recipe.recipe_id) ? (\n <span>&#10003;</span>\n ) : (\n \n <Link\n value={recipe.recipe_id}\n onClick={() =>\n CompletedRecipe(recipe.id, recipe.recipe_id)\n } className=\"btn btn-primary href\"><FontAwesomeIcon icon={faCheckSquare} size='1x'/>\n </Link>\n \n )}\n </td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n );\n}", "function populateStorage(){\n \t\tconsole.log('-- Populate local storage');\n\n \t\tfor (var level in GameJam.levels) {\n \t\t\tlocalStorage.setItem(level, GameJam.levels[level].time);\n \t\t}\n \t}", "function updateSnakeStorage() {\n\tSNAKE_STORAGE = {\n\t\thigh_score_records: HIGH_SCORE_RECORDS,\n\t\tgame_speed: GAME_SPEED,\n\t\tnum_rows: NUM_ROWS,\n\t\tnum_cols: NUM_COLS,\n\t\tavailable_fruit: AVAILABLE_FRUIT,\n\t\tfruit_effect: FRUIT_EFFECT,\n\t\tcolor_snake: COLOR_SNAKE,\n\t\tcolor_fruit: COLOR_FRUIT,\n\t\tcolor_board: COLOR_BOARD,\n\t\tzoom_level: ZOOM_LEVEL,\n\t\ttop_skill_scores: TOP_SKILL_SCORES\n\t}\n}", "function WriteToStorage(item){\n var currentStorage = ReadFromStorage();\n currentStorage.push(item);\n localStorage.setItem('indexBun', JSON.stringify(currentStorage));\n indexBun++;\n //renderCartPrice();\n}", "function saveData(){ \n // Transform the products array into a JSON string \n var productJSON = JSON.stringify(products); \n console.log(productJSON); \n\n\n // Save that JSON string to a local storage (aka local memory of the browser)\n localStorage.setItem(\"price-list\", productJSON); \n\n\n}", "SET_RECIPES(state, recipes) {\n state.recipes = recipes;\n }", "save(storage) {\n storage.store({ name: this.name, price: this.price });\n return storage.length;\n }", "function saveNominations(){\n localStorage.clear();\n // if there's no nominations, don't bother saving\n if(nominationState.nominations.length === 0){\n return;\n }\n var storage = JSON.stringify(nominationState.nominations);\n localStorage.setItem(\"Shoppies\", storage);\n }", "function storeScores() {\n localStorage.setItem('names', JSON.stringify(names));\n localStorage.setItem('scores', JSON.stringify(scores));\n localStorage.setItem('times', JSON.stringify(times));\n}", "function saveUpdate() {\n\t\tlocalStorage.setItem('cart', JSON.stringify(storedCart));\n\t\tupdateCartCounter();\n\t}", "function saveScores() {\n\n localStorage.setItem('scores', JSON.stringify(sectionScores));\n\n}", "function storeData(){\r\n\t\tvar id \t\t\t\t= Math.floor(Math.random()*100000000001);\r\n\t\t//Gather up all our form field values and store in an object\r\n\t\t//Object properties contain an array with the form label and input value\r\n\t\tgetSelectedRadio();\r\n\t\tvar item \t\t\t\t= {};\r\n\t\t\titem.comicTitle\t\t= [\"Title of Comic:\", e('comicTitle').value];\r\n\t\t\titem.seriesTitle\t= [\"Title of Series:\", e('seriesTitle').value];\r\n\t\t\titem.issueNum\t\t= [\"Issue Number:\", e('issueNum').value];\r\n\t\t\titem.dateReleased\t= [\"Date Released:\", e('dateReleased').value];\r\n\t\t\titem.publisher\t\t= [\"Publisher:\", e('publisher').value];\r\n\t\t\titem.rateIssue\t\t= [\"Rate of Issue:\", e('rateIssue').value];\r\n\t\t\titem.genre \t\t\t= [\"Genre:\", e('genre').value];\r\n\t\t\titem.illStyle\t\t= [\"Illustration Style:\", styleValue];\r\n\t\t\titem.comments\t\t= [\"Comments:\", e('comments').value];\r\n\t\t//Save data into Local Storage: Use Stringify to convert our object to a string\r\n\t\tlocalStorage.setItem(id, JSON.stringify(item));\r\n\t\talert(\"Comic saved to index!\");\r\n\t}", "persistData() {\n // Convert the likes array in string before save\n localStorage.setItem('likes', JSON.stringify(this.likes));\n }", "function saveLocalStore(){\n for(i = 0; i < generalInfo.length; i++){\n var displayNow = ($(\"#inputEvent\"+generalInfo[i].display).val());\n var notesNow = generalInfo[i].notes;\n generalInfo[i].notes = displayNow;\n console.log(\"grabo vacio\");\n\n }\n localStorage.setItem(\"generalInfo\", JSON.stringify(generalInfo));\n }", "function newDish()\n{\n //Get the name of the dish and its description\n var dishName = document.getElementById(\"dish_name\").value;\n var dishDesc = document.getElementById(\"dish_desc\").value;\n var dishPrice = document.getElementById(\"dish_price\").value;\n\n //get the name of the current chef\n currUser = window.sessionStorage.getItem(\"currentUser\");\n\n //Check for valid input (dish name and description are not blank\n if (dishName == \"\" || dishDesc == \"\")\n {\n window.alert(\"Please make sure all fields are not blank\");\n return;\n }\n\n //Grab the list of all dishes from local storage\n var localStorage = window.localStorage;\n var dishes = JSON.parse(localStorage.getItem(\"dishes\"));\n //If not instantiated, do so\n if (dishes == null || dishes.length == 0)\n {\n dishes = [];\n }\n\n //Add the current dish to this chef's dish list and store it in local storage\n dishes.push({\"chef_name\":currUser, \"dish_name\": dishName, \"dish_price\": dishPrice, \"dish_desc\": dishDesc});\n localStorage.setItem(\"dishes\",JSON.stringify(dishes));\n\n //Re load the list of dishes\n loadDishes(); \n}", "function deleteRecipeFromLocalStorage (recip) {\n\n if (localStorage.getItem(\"data\") !=null) {\n allRecipies = JSON.parse(localStorage.getItem(\"data\")); // jeśli są to konwertujemy je i zapisujemy do zmiennej\n console.log(recip)\n // zwroc nowa tablice bez skasowanego elementu\n allRecipies = allRecipies.filter(function(element, index, array) {\n return element.title != recip;\n });\n //reindeksuj\n for (let i=0; i < allRecipies.length; i++) {\n allRecipies[i].id = i+1;\n }\n localStorage.setItem(\"data\", JSON.stringify(allRecipies)); //Zapisujemy do localStorage nowe dane\n }\n }" ]
[ "0.681646", "0.6704981", "0.6697677", "0.63790077", "0.6320328", "0.63082176", "0.6302978", "0.6230274", "0.6208092", "0.61903894", "0.6142571", "0.612609", "0.6118722", "0.6106649", "0.6089457", "0.60274816", "0.6006594", "0.5909437", "0.5909046", "0.5908755", "0.5895762", "0.58850276", "0.5877405", "0.58747685", "0.5847386", "0.5837606", "0.58201355", "0.5798192", "0.5768764", "0.57614535", "0.57358867", "0.57104355", "0.5700597", "0.5671492", "0.5665736", "0.5647303", "0.5643894", "0.56074893", "0.5598808", "0.5596879", "0.5590516", "0.5576684", "0.55766547", "0.5576224", "0.5570184", "0.5563171", "0.55595696", "0.55565387", "0.5546212", "0.5545424", "0.5540488", "0.55319506", "0.55304456", "0.5524999", "0.5523866", "0.5520831", "0.55137736", "0.550773", "0.54980725", "0.54960287", "0.5495396", "0.5481894", "0.54753613", "0.54699695", "0.54689044", "0.54676604", "0.54621243", "0.5454262", "0.5450225", "0.5450225", "0.5450225", "0.544036", "0.54402727", "0.5434029", "0.5427176", "0.5424742", "0.54141265", "0.541255", "0.5404773", "0.54020756", "0.54017234", "0.5401432", "0.53943527", "0.5392025", "0.5383316", "0.5382139", "0.53794885", "0.53752875", "0.5371711", "0.5369828", "0.53633493", "0.5356732", "0.53550875", "0.5353023", "0.53494537", "0.53458273", "0.5339244", "0.53363115", "0.53315026", "0.53307694" ]
0.72961426
0
FIXME This is a workaround for If we exit immediately winston does not get a chance to write the last log message. So we wait a short time before exiting.
function exitWithStatus(exitStatus) { logger.info( "Exiting with status " + exitStatus ); setTimeout( function() { process.exit(exitStatus); }, 500 ); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function gracefulShutdown() {\n winston.log('info','Received kill signal, shutting down gracefully.');\n server.close(function() {\n winston.log('Closed out remaining connections.');\n process.exit();\n });\n\n // if after\n setTimeout(function() {\n winston.log('error','Could not close connections in time, forcefully shutting down');\n process.exit();\n }, 10*1000);\n}", "function shutdown() {\n\tlogger.info('shutdown started')\n\tsetTimeout(() => process.exit(0), 500);\n}", "async function log3lines() {\n try {\n await ensureDir();\n\n await logger(\"Ligne 1\");\n await logger(\"Ligne 2\");\n await logger(\"Ligne 3\");\n } catch (err) {\n console.log(err);\n }\n}", "_final(callback) {\n this._logger\n .close()\n .then(() => callback())\n .catch((err) => callback(err));\n }", "async function waitForLogger(logger) {\n const loggerDone = new Promise(resolve => logger.on(\"finish\", resolve));\n logger.end();\n return await loggerDone;\n}", "async handler () {\n this.getHost().clearLogOutput()\n }", "async terminate() {\n // chance for any last minute shutdown stuff\n logger.info('Null API Terminate');\n }", "async stop() {\n this.watcher.close();\n // finish sending all logs then send final all done logger log\n }", "function finish (err) {\n if (!calledDone) {\n calledDone = true;\n if (err) {\n finalize(err, resolve, reject, done);\n return;\n }\n if (logFinished) {\n finalize(null, resolve, reject, done);\n return;\n }\n const intervalId = setInterval(() => {\n if (logFinished) {\n clearInterval(intervalId);\n finalize(null, resolve, reject, done);\n }\n }, 1000);\n }\n }", "logHealthcheck() {\n (async () => {\n await module.exports.checkPg();\n module.exports.calcUptime();\n lumServer.logger.info('healthcheck', lumServer.healthcheck);\n })();\n }", "break() {\n this.write('log', '', null, false);\n }", "function logErrorAndExit(e) {\n console.error(e);\n process.exit(1);\n}", "function gracefulShutdown() {\n console.log('Received kill signal, shutting down gracefully.');\n server.close(() => {\n console.log('Closed out remaining connections.');\n process.exit();\n });\n // if after\n setTimeout(() => {\n console.error('Could not close connections in time, forcefully shutting down');\n process.exit();\n }, 10 * 1000);\n}", "function cleanUpandExit(arg) {\n\tconsole.log(arg);\n}", "function gracefulExit() {\n mongoose.connection.close(() => {\n console.log(`Mongoose default connection with DB : ${config.testing.db} is disconnected through app termination`);\n process.exit(0);\n });\n}", "function gracefulShutdown() {\n logger.warn('Configs have changed. Closing server and handling remaining connections.');\n server.close((err) => {\n if (err) {\n logger.error(err);\n }\n logger.warn('All server connections closed. Committing suicide to reload new configs.');\n process.exit(1);\n });\n }", "_eventNoWikis() {\n console.warn('No wikis configured! Exiting program...');\n process.exit();\n }", "log() {\n return winston.createLogger({\n defaultMeta: {\n requestId: this.requestId,\n // eslint-disable-next-line no-undef\n application: process.env.APP_NAME,\n },\n format: winston.format.combine(\n winston.format.timestamp({\n format: 'DD-MM-YYYY HH:mm:ss',\n }),\n winston.format.prettyPrint(),\n winston.format.json(),\n this.customFormatter(),\n winston.format.printf((info) => {\n const timestamp = info.timestamp.trim();\n const requestId = info.requestId;\n const level = info.level;\n const message = (info.message || '').trim();\n\n const saveFunction = new logsDb({\n timestamp : timestamp,\n level : level,\n message : message,\n //meta : meta,\n //hostname : foundedData.hostname\n });\n\n saveFunction.save((err) => {\n if (err) {\n console.log(\"failed to logs save operation\"); \n }\n\n })\n \n if (_.isNull(requestId) || _.isUndefined(requestId)) {\n return `${timestamp} ${level}: ${message}`;\n } else {\n return `${timestamp} ${level}: processing with requestId [${requestId}]: ${message}`;\n }\n }),\n ),\n transports: [\n new winston.transports.Console({\n level: 'debug',\n handleExceptions: true,\n }), \n // File transport\n new winston.transports.File({\n filename: 'logs/server.log',\n format: winston.format.combine(\n winston.format.colorize(),\n winston.format.timestamp({format: 'MMM-DD-YYYY HH:mm:ss'}),\n winston.format.align(),\n winston.format.json()\n )\n }), \n\n // MongoDB transport\n // new winston.transports.MongoDB({\n // level: 'info',\n // //mongo database connection link\n // db : 'mongodb://localhost:27017/mysale',\n // options: {\n // useUnifiedTopology: true\n // },\n // // A collection to save json formatted logs\n // collection: 'serverlogs',\n // format: winston.format.combine(\n // winston.format.timestamp(),\n // // Convert logs to a json format\n // winston.format.json()),\n // storeHost: true,\n // capped: false,\n // decolorize: false,\n // metaKey: 'meta',\n // }),\n\n ],\n });\n }", "function finish(err) {\n\t if (callback) {\n\t if (err) return callback(err);\n\t callback(null, level, msg, meta);\n\t }\n\n\t callback = null;\n\t if (!err) {\n\t self.emit('logged', level, msg, meta);\n\t }\n\t }", "async function waitForOracleCallback() {\n await promisifyLogWatch(cryptoRun.LogChallengeStatusRefreshed({ fromBlock: 'latest' }))\n }", "function quit() {\n log.info('Exiting now.');\n process.nextTick(process.exit);\n }", "function endOnError(err) {\n console.log(err);\n process.exit(1);\n}", "shutdown() {\n // this.log.debug(\"shutdown\");\n }", "function onFatal(root){root.finishedWork=null;}", "function onFatal(root){root.finishedWork=null;}", "function onFatal(root){root.finishedWork=null;}", "log() {\n return; // no output for initial application build\n }", "function finish (err, result) {\n if (!calledDone) {\n calledDone = true;\n var intervalId = setInterval(function () {\n if (logFinished) {\n clearInterval(intervalId);\n cb(err, result);\n }\n }, 1000);\n }\n }", "function exitHandler(options, err) {\n if (options.cleanup) console.log('clean');\n if (err) console.log(err.stack);\n if (options.exit) process.exit();\n }", "function _exit(inst)\n{\n if (inst.server != null) {\n logger.info(\"ROV Module: _exit(\" + inst.id + \") pid = \"\n + inst.server.pid);\n\n /* in case, the target monitor hangs, we kill rather than\n * inst.server.stdin.write(\"exit\" + os.EOL);\n */\n inst.server.kill('SIGTERM');\n inst.server = null;\n }\n else {\n logger.info(\"ROV Module: _exit(\" + inst.id + \") server == null\");\n }\n}", "function handleTimeout() {\n console.log(\"Timeout\");\n }", "function final() { console.log('Done and Final'); process.exit() ; }", "async 'after sunbath' () {\n console.log( 'see? I appear here because of the first custom above' )\n }", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function onFatal(root) {\n root.finishedWork = null;\n}", "function endProcess() {\n clearInterval(interval);\n process.stdout.write(chalk.blue('\\n\\nSetup complete!!\\n\\n'));\n process.exit(0);\n}", "async onEnd() {\n\t\tawait this.say('Exiting...');\n\t}", "function exit(message) {\n console.log(message);\n }", "function onFatal(root) {\n root.finishedWork = null;\n }", "function onFatal(root) {\n root.finishedWork = null;\n }", "function onFatal(root) {\n root.finishedWork = null;\n }", "function exitHandler(options, err) {\n let exitMessage = `Server shutting down`;\n\n if (err && options.uncaughtException) {\n console.log(`\\n${err.stack}`);\n log(`FATAL ERROR, PRINT SERVER SHUT DOWN ${err.stack}`, __filename, process.exit);\n } else {\n console.log(`\\n${exitMessage}`);\n log(exitMessage, __filename, process.exit);\n }\n }", "function handle_timeout() {\n\tif(!heating) {\n\t\tif(happenen) {\n\t\t\tconsole.log(\"on :\"+Date());\n\t\t}else {\n\t\t\tconsole.log(\"off:\"+Date());\n\t\t}\n\t}\n\tif(brew_last != 0.0) {\n\t\tconsole.log(\"last brew was \"+ (Date.now() - brew_last)/60000 + \" Minutes Ago\");\n\t}\n\tstartTimeout(handle_timeout, warming_interval);\n}", "function writeLog() {\n const interval = randomInt(900, 200);\n setTimeout(() => {\n const log = buildLog();\n stream.write(log)\n writeLog();\n }, interval)\n}", "static onExit(code) {\n this.logger.info('[midway:bootstrap] exit with code:%s', code);\n }", "function callLogs() {\n console.log('HAI SAYA ADALAH CALLBACK');\n}", "function terminator(sig) {\n if (typeof sig === \"string\") {\n winston.info('%s: Received %s - terminating Node server ...',Date(Date.now()), sig); \n process.exit(1);\n\t app.close();\n }\n winston.info('%s: Node server stopped.'.red, Date(Date.now()) );\n}", "stopAndLog() {\n\t\tthis.stop();\n\t\tthis.log();\n\t}", "function printTailoringStatusAndExit() {\n\tlet msg;\n\tif (persistedTailoringState === cStateNotTailored) {\n\t\tmsg = \"The npm module has not been tailored for a specific runtime environment.\";\n\t} else {\n\t\tmsg = `The npm module has been tailored for runtime environment: ${persistedTailoringState}`;\n\t}\n\tconsole.log(`TAILORING STATE: ${msg}`);\n\tprocess.exit(0);\n}", "exit() {\n const { server } = this;\n server.close().then(\n () => {\n server.log.info(Strings.SHUTDOWN_MESSAGE);\n },\n (error) => {\n server.log.error(Errors.DEFAULT_ERROR, error);\n }\n )\n }", "function gracefulShutdown(e) {\n\tconsole.log(\"Shutting Down\", e)\n\tclient.close()\n\tprocess.exit()\n}", "cleanUp() {\n logger.info('server shutting down');\n this.server.close(() => process.exit(0));\n }", "debounceInitialLogging() {\n if (!window[Const.GLOBAL].initialized) {\n clearTimeout(this.timeout);\n this.timeout = setTimeout(() => {\n var data = window[Const.GLOBAL];\n data.initialized = true;\n Util.log({\n [Const.COUNT.BUTTON]: data[Const.COUNT.BUTTON],\n [Const.COUNT.FOLLOW]: data[Const.COUNT.FOLLOW],\n [Const.COUNT.PIN_SMALL]: data[Const.COUNT.PIN_SMALL],\n [Const.COUNT.PIN_MEDIUM]: data[Const.COUNT.PIN_MEDIUM],\n [Const.COUNT.PIN_LARGE]: data[Const.COUNT.PIN_LARGE],\n [Const.COUNT.PROFILE]: data[Const.COUNT.PROFILE],\n [Const.COUNT.BOARD]: data[Const.COUNT.BOARD]\n });\n }, 1000);\n }\n }", "function exitHandler(options, err) {\n if (options.cleanup) console.log('clean');\n if (err) console.log(err.stack);\n if (options.exit) process.exit();\n}", "async shutdown() {\n process.exit(0)\n }", "function chillOut() {\n Reporter_1.Reporter.debug(`wait for ${CHILL_OUT_TIME}ms`);\n browser.pause(CHILL_OUT_TIME);\n }", "function chillOut() {\n Reporter_1.Reporter.debug(`wait for ${CHILL_OUT_TIME}ms`);\n browser.pause(CHILL_OUT_TIME);\n }", "function intervalCallback() {\n var delta = (new Date().getTime() - time_last_peer) / 1000;\n winston.debug(util.format(\"delta is %s\", delta));\n if (delta > argv.timeoutNoPeers) {\n\n if (ip_hashmap.keys().length > 0) {\n winston.info(\"Got no new peers in time. Terminating\");\n if (!terminating) { //this should prevent timeoutCallback from being called in parallel. Not sure if it works though...\n timeoutCallback();\n }\n } else {\n winston.info(\"Didn't terminate yet because no peers at all have been found\");\n }\n }\n time_last_peer = new Date().getTime();\n }", "async function signalTestHandlersReady() {\n const EXPECTED_ERROR =\n /No handler registered for message type 'test-handlers-ready'/;\n let attempts = 10;\n while (--attempts >= 0) {\n try {\n // Try to limit log output from message pipe errors.\n await new Promise(resolve => setTimeout(resolve, 100));\n await parentMessagePipe.sendMessage('test-handlers-ready', {});\n return;\n } catch (/** @type {!GenericErrorResponse} */ e) {\n if (!EXPECTED_ERROR.test(e.message)) {\n console.error('Unexpected error in signalTestHandlersReady', e);\n return;\n }\n }\n }\n console.error('signalTestHandlersReady failed to signal.');\n}", "async function parent() {\n logger();\n console.log(\"parent called\");\n}", "function fatalError(msg) {\r\n\t\timpress.log.error(msg);\r\n\t\tconsole.log(msg.red);\r\n\t\tprocess.exit(1);\r\n\t}", "function endIfErr (err) {\n if (err) {\n console.error(err);\n process.exit(1);\n }\n}", "function logHello() {\n console.log(hello());\n\n if(counter === 5) {\n clearInterval(intervalId);\n }\n\n counter++;\n\n}", "exit() {\n this.emit(\"shutdown\", this);\n this.discordCli.destroy();\n process.exit(0);\n }", "function handleAppExit (options, err) { \n if (err) {\n console.log(err.stack)\n }\n\n if (options.cleanup) {\n\tclient.publish(kitchen_alarm_topic, 'false', {qos: 2, retain: true});\n }\n\n if (options.exit) {\n process.exit()\n }\n}", "function waitForInstance(handle){return $mdComponentRegistry.when(handle)[\"catch\"]($log.error);}", "function showVersionAndExit(): never {\n process.stdout.write(`${BUILD_INFO.VERSION_STRING}\\n`);\n log.debug(\"BUILD_INFO_COMMIT: %s\", BUILD_INFO.COMMIT);\n log.debug(\"BUILD_INFO_TIME_RFC3339: %s\", BUILD_INFO.BUILD_TIME_RFC3339);\n log.debug(\"BUILD_INFO_HOSTNAME: %s\", BUILD_INFO.BUILD_HOSTNAME);\n log.debug(\"BUILD_INFO_BRANCH_NAME: %s\", BUILD_INFO.BRANCH_NAME);\n\n // Cleanly shut down logging system.\n throw new ExitSuccess();\n}", "function wait(message) {\r\n setTimeout(\r\n function time(){ console.log(message); },\r\n 1000\r\n );\r\n }", "onExit () {\n this.log('homebridge exiting')\n }", "function endIfErr (err) {\n if (err) {\n console.error(err)\n process.exit(1)\n }\n}", "async function ChatlogProcess() {\r\n //Optimizes send times, removes fast dupes, keeps the order, does not work while restarting\r\n let purged = 0;\r\n if (cursedConfig.chatlog.length != 0 && !cursedConfig.onRestart) {\r\n let actionTxt = cursedConfig.chatlog.shift();\r\n let before = cursedConfig.chatlog.length;\r\n cursedConfig.chatlog = cursedConfig.chatlog.filter(el => el != actionTxt);\r\n purged = before - cursedConfig.chatlog.length;\r\n popChatGlobal(actionTxt);\r\n cursedConfig.chatStreak++;\r\n } else {\r\n cursedConfig.chatStreak = 0;\r\n }\r\n\r\n //Spam block\r\n if (cursedConfig.chatStreak > 5 || purged > 3) {\r\n cursedConfig.isRunning = false;\r\n cursedConfig.chatlog = [];\r\n popChatSilent({ Tag: \"ERROR S011\" }, \"Error\");\r\n }\r\n setTimeout(ChatlogProcess, 500);\r\n}" ]
[ "0.615669", "0.57047313", "0.56274146", "0.5616755", "0.5528896", "0.5430029", "0.53931326", "0.5348744", "0.5301851", "0.5294547", "0.5290841", "0.5235755", "0.5185641", "0.5180669", "0.5176925", "0.51713663", "0.5159321", "0.5150351", "0.5141504", "0.51240903", "0.51159567", "0.51086", "0.5102471", "0.5091161", "0.5091161", "0.5091161", "0.50899", "0.5084872", "0.49961686", "0.49890208", "0.4988577", "0.49799293", "0.4963865", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.49638003", "0.4948791", "0.49149507", "0.48964852", "0.48873556", "0.48873556", "0.48873556", "0.4884621", "0.48819888", "0.488194", "0.48793995", "0.4878479", "0.48776734", "0.48767313", "0.4871127", "0.48565522", "0.48550984", "0.4850309", "0.48362258", "0.48296478", "0.48274407", "0.48251867", "0.48251867", "0.4823741", "0.48226866", "0.482221", "0.4815725", "0.4798674", "0.4796844", "0.47911763", "0.4787189", "0.47868687", "0.4779651", "0.4774883", "0.4771664", "0.47680554", "0.47568837" ]
0.0
-1
get the list of ports:
function printList(portList) { // portList is an array of serial port names for (var i = 0; i < portList.length; i++) { // Display the list the console: console.log(i + " " + portList[i]); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function listPorts() {\n dataPort = [];\n SerialPort.list().then(\n ports => {\n ports.forEach(port => {\n dataPort.push(port.path + \"\");\n // console.log(\"burak\");\n // console.log(port.path);\n })\n },\n err => {\n console.error('Error listing ports', err)\n }\n )\n }", "function getPorts(){\n $.get('/ports', function(data){\n portList = data;\n })\n}", "function list_port() {\n SerialPort.list(function (err, ports) {\n ports.forEach(function(port) {\n console.log(port.comName);\n });\n });\n}", "function createPorts() {\n\tlist = [\n\t//[isrc, jsrc, idest, jdest],\t\n\t\t[14, 79, 14, 00],\n\t\t[15, 79, 15, 00],\n\t\t[16, 79, 16, 00],\n\t\t[17, 79, 17, 00],\n\t\t[18, 79, 18, 00],\n\t];\n\treturn list;\n}", "getPorts(params) {\n console.error(\"User needs to provide method for getting component ports, look at examples\");\n }", "list() {\n\n return SerialPort.list()\n .then(function(ports) {\n\n return (ports.filter(function(port) {\n // the CAN-USB-COM returns a particular device ID\n // so we filter for that before supplying the list to the\n // caller\n return port.vendorId === '0403' && port.productId === '6001';\n }));\n\n });\n }", "function listPorts(err, ports){\n\tports.forEach(function(port){\n\t\tconsole.log(port.comName);\n\t\tconsole.log(port.pnpId);\n\t\tconsole.log(port.manufacturer);\n\t if(port.manufacturer.indexOf(\"Arduino\") > -1){\n\t\t arduinoPort = port.comName;\n\t\t console.log(\"Arduino is: \" + arduinoPort);\n\t\t\tarduino = new sp.SerialPort(arduinoPort, {\n\t\t\t\tbaudrate: 115200,\n\t\t\t\tparser: sp.parsers.readline(\"\\n\")\n\t\t\t});\n\t\t\tarduino.on(\"open\", onOpen);\n\t }\n\t});\n}", "async function getPorts(){\n const SerialPort = require('serialport')\n try{\n const ports = await SerialPort.list();\n console.log(ports);\n $('.selectCom').empty();\n $.each(ports, function(i, p) {\n $('.selectCom').append($('<option></option>').val(p.path).html(p.path));\n });\n var elems = document.querySelectorAll('select');\n var instances = M.FormSelect.init(elems, {});\n }catch(e){\n console.log(e);\n }\n }", "function printList(portList) {\n for (var i = 0; i < portList.length; i++) {\n console.log(i + \" \" + portList[i]);\n }\n}", "static get port() {}", "logPorts() {\n console.log(\"this.ports\");\n console.log(this.ports);\n console.log(\"this.ports[0]\");\n console.log(this.ports[0]);\n console.log(\"typeof this.ports[0]\");\n console.log(typeof this.ports[0]);\n }", "function getPort(){\n\t\treturn this.port;\n\t}", "static getViewports() {\n return this.Viewports;\n }", "constructor() {\n this.ports = new Array(4);\n }", "function getNodePorts(obj) {\n if (obj.id === 'node2' || obj.id === 'node9') {\n var node2Ports = [\n { id: 'port1', offset: { x: 0.2, y: 1 } },\n { id: 'port2', offset: { x: 0.8, y: 1 } },\n { id: 'port3', offset: { x: 0.2, y: 0 } },\n { id: 'port4', offset: { x: 0.8, y: 0 } },\n ];\n return node2Ports;\n } else {\n var ports = [\n { id: 'portLeft', offset: { x: 0, y: 0.5 } },\n { id: 'portRight', offset: { x: 1, y: 0.5 } },\n { id: 'portBottom', offset: { x: 0.5, y: 1 } },\n { id: 'portTop', offset: { x: 0.5, y: 0 } },\n ];\n return ports;\n }\n}", "function parsePorts(stdoutLines) {\n let portsRe\n switch (process.platform) {\n case 'win32':\n portsRe = /TCP\\s+(?:\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\:(?:\\d+)\\s+(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\:(\\d+)/\n break\n case 'darwin':\n default:\n portsRe = /TCP\\s+(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\:(\\d+)\\-\\>(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\:(\\d+)/\n }\n let ports = []\n stdoutLines.forEach(line => {\n const portsMatch = line.match(portsRe)\n if (!portsMatch) return\n ports.push(portsMatch[2])\n })\n return ports\n}", "function printList(portList) {\n // portList is an array of serial port names\n for (var i = 0; i < portList.length; i++) {\n // Display the list the console:\n console.log(i + \" \" + portList[i]);\n }\n}", "function printList(portList) {\n // portList is an array of serial port names\n for (var i = 0; i < portList.length; i++) {\n // Display the list the console:\n console.log(i + \" \" + portList[i]);\n\n }\n}", "addPorts(...ports) {\n this.ports.push(...ports.map(port => ({ port: port })));\n }", "function printList(portList) {\r\n // portList is an array of serial port names\r\n for (var i = 0; i < portList.length; i++) {\r\n // Display the list the console:\r\n console.log(i + \" \" + portList[i]);\r\n }\r\n }", "function printList(portList) {\n for (var i = 0; i < portList.length; i++) {\n // Display the list the console:\n println(i + \" \" + portList[i]);\n }\n}", "function printList(portList) {\n for (var i = 0; i < portList.length; i++) {\n // Display the list the console:\n println(i + \" \" + portList[i]);\n }\n}", "function updatePortsConfig() {\n config.set('ports', ports.map((port) => port.number));\n}", "function printList(portList) {\n // portList is an array of serial port names\n for (var i = 0; i < portList.length; i++) {\n // Display the list the console:\n println(i + \" \" + portList[i]);\n }\n\n\n}", "function printList(portList) {\n // portList is an array of serial port names\n for (var i = 0; i < portList.length; i++) {\n // Display the list the console:\n console.log(i + \" \" + portList[i])\n }\n}", "function printList(portList) {\n // portList is an array of serial port names\n for (var i = 0; i < portList.length; i++) {\n // Display the list the console:\n console.log(i + \" \" + portList[i]);\n }\n}", "function printList(portList) {\n // portList is an array of serial port names\n for (var i = 0; i < portList.length; i++) {\n // Display the list the console:\n print(i + \" \" + portList[i]);\n }\n}", "function printList(portList) {\n // portList is an array of serial port names\n for (var i = 0; i < portList.length; i++) {\n // Display the list the console:\n print(i + \" \" + portList[i]);\n }\n}", "function printList(portList) {\n // portList is an array of serial port names\n for (var i = 0; i < portList.length; i++) {\n // Display the list the console:\n print(i + \" \" + portList[i]);\n }\n}", "function printList(portList) {\n // portList is an array of serial port names\n for (var i = 0; i < portList.length; i++) {\n // Display the list the console:\n print(i + \" \" + portList[i]);\n }\n}", "function printList(portList) {\n // portList is an array of serial port names\n for (var i = 0; i < portList.length; i++) {\n // Display the list the console:\n print(i + \" \" + portList[i]);\n }\n}", "function printList(portList) {\n // portList is an array of serial port names\n for (var i = 0; i < portList.length; i++) {\n // Display the list the console:\n print(i + \" \" + portList[i]);\n }\n}", "function printList(portList) {\n for (var i = 0; i < portList.length; i++) {\n // Display the list the console:\n print(i + \" \" + portList[i]);\n }\n}", "_makePortList(config, start=1, end=1000, interval=1) {\n\n var portList;\n // a given list takes precedence over a range\n if (Array.isArray(config.ports)) {\n\n // Ignore invalid values\n portList = utilities.filterValidPorts(config.ports);\n\n } else {\n this.start = parseInt(config.start) || start;\n this.end = parseInt(config.end) || end;\n this.interval = parseInt(config.interval) || interval;\n\n if (!utilities.isValidPort(this.start) ||\n !utilities.isValidPort(this.end) ||\n this.end < this.start) {\n\n throw new Error('Invalid port range or interval, default range is '+\n `${start}-${end} by ${interval}`);\n\n }\n\n portList = utilities.makeArrayForIntervalRange(this.start,this.end,this.interval);\n\n }\n\n if (portList.length === 0) {\n throw new Error('No ports to scan (check port config passed to scanner)');\n }\n\n return portList;\n }", "async function getAllConnections(portNum) {\n let data = \"\";\n try {\n let connections = await fetch(\"http://localhost:\" + portNum + \"/connections\");\n data = await connections.json();\n } catch (err) {\n app.loadingModalStatus.push(names[portNum] + \" Agent may not be connected\");\n console.log(names[portNum]);\n isConnected[names[portNum]] = false;\n console.error(names[portNum] + \" Agent may not be connected\");\n return [];\n }\n\n // filter connections to active connections in each name\n let filtered = data.results.filter(function (entry) {\n return (entry.state === \"active\");\n });\n\n return filtered;\n}", "getPort() {\n return super.getAsInteger(\"port\");\n }", "function printList(portList) {\n for (var i = 0; i < portList.length; i++) {\n print(i + \" \" + portList[i]);\n }\n}", "function gotList(thelist) {\n println(\"List of Serial Ports:\");\n // theList is an array of their names\n for (var i = 0; i < thelist.length; i++) {\n // Display in the console\n println(i + \" \" + thelist[i]);\n }\n}", "function getPortMappingsP () {\n var deferred = Q.defer()\n getPortMappings(\n function (mappings) { // on success\n deferred.resolve(mappings)\n },\n function (error) { // on failure\n deferred.reject(error)\n }\n )\n return deferred.promise\n}", "get port() {\n return this.getNumberAttribute('port');\n }", "get port() {\n return this.getNumberAttribute('port');\n }", "function gotList(thelist) {\n println(\"List of Serial Ports:\");\n // theList is an array of their names\n for (var i = 0; i < thelist.length; i++) {\n // Display in the console\n println(i + \" \" + thelist[i]);\n }\n}", "function gotList(thelist) {\n\n console.log(\"Got List of Serial Ports:\");\n // theList is an array of their names\n for (var i = 0; i < thelist.length; i++) {\n // Display in the console\n console.log(i + \" \" + thelist[i]);\n }\n}", "getPort() {\n return this._port;\n }", "getPort() {\n return this._port;\n }", "function gotList(thelist) {\n print(\"List of Serial Ports:\");\n // theList is an array of their names\n for (var i = 0; i < thelist.length; i++) {\n // Display in the console\n print(i + \" \" + thelist[i]);\n }\n}", "function gotList(thelist) {\n print(\"List of Serial Ports:\");\n // theList is an array of their names\n for (let i = 0; i < thelist.length; i++) {\n // Display in the console\n print(i + \" \" + thelist[i]);\n }\n}", "function gotList(thelist) {\n \n println(\"List of Serial Ports:\");\n // theList is an array of their names\n for (var i = 0; i < thelist.length; i++) {\n // Display in the console\n println(i + \" \" + thelist[i]);\n }\n}", "function printList(portList) {\n // portList is an array of serial port names\n for (var i = 0; i < portList.length; i++) {\n // Display the list the console:\n print(i + \" \" + portList[i]);\n }\n}", "function printList(portList) {\n // portList is an array of serial port names\n for (var i = 0; i < portList.length; i++) {\n // Display the list the console:\n print(i + \" \" + portList[i]);\n }\n}", "get nextPort() {\n return this.portList[this.portIndex] || 0;\n }", "function getPortscanUses() {\n return (0, _property.get)(\"_sourceTerminalPortscanUses\");\n}", "function printList(portList) {\n // portList is an array of serial port names\n for (var i = 0; i < portList.length; i++) {\n // Display the list the console:\n print(i + \" \" + portList[i]);\n }\n}", "get port() { return this._port; }", "function printList(portList) {\n // create a select object:\n portSelector = createSelect();\n portSelector.position(10, 40);\n // portList is an array of serial port names\n for (var i = 0; i < portList.length; i++) {\n // add this port name to the select object:\n portSelector.option(portList[i]);\n }\n // set an event listener for when the port is changed:\n portSelector.changed(mySelectEvent);\n}", "function getAvailableRouters() {\n return ['127.0.0.1 1234 1'];\n}", "function getPort () {\n return _port++;\n}", "function getUsedTcpPorts (waitingState) {\n let usedPorts = [];\n for (let id in waitingState) {\n const cond1 = waitingState[id].services !== undefined;\n const cond2 = cond1 && waitingState[id].services.manticore !== undefined;\n const cond3 = cond2 && waitingState[id].services.manticore[`core-tcp-${id}-0`].external !== undefined;\n if (cond3) {\n usedPorts.push(waitingState[id].services.manticore[`core-tcp-${id}-0`].external);\n }\n }\n return usedPorts;\n}", "function getAvailablePort(defaultPort = 3000) {\n return new Promise((resolve, reject) => {\n // Get a list of all ports in use\n child_process__WEBPACK_IMPORTED_MODULE_0___default.a.exec('lsof -i -P -n | grep LISTEN', (error, stdout, stderr) => {\n if (error) {\n // likely no permission, e.g. CI\n resolve(defaultPort);\n return;\n }\n\n const portsInUse = [];\n const regex = /:(\\d+) \\(LISTEN\\)/;\n stdout.split('\\n').forEach(line => {\n const match = line.match(regex);\n if (match) {\n portsInUse.push(Number(match[1]));\n }\n });\n let port = defaultPort;\n while (portsInUse.includes(port)) {\n port++;\n }\n resolve(port);\n });\n });\n}", "function getCellPortList(cell, direction)\n{\n var ports = _.filter(_.flatMap(cell.connections, function(val, key) {\n return {key:key, value:val};\n }), function(val) {\n return cell.port_directions[val.key] == direction;\n });\n return ports;\n}", "function showPorts(node, show) {\n diagram = node.diagram;\n if (!diagram || diagram.isReadOnly || !diagram.allowLink) return;\n it = node.ports;\n while (it.next()) {\n port = it.value;\n port.stroke = (show ? \"black\" : null);\n }\n }", "function getPublicPorts(ports, callback) {\n async.waterfall([\n function(callback) {\n redisClient.keys(redisPrefix + \":ports:*\", callback);\n },\n function(portsKeys, callback2) {\n var redisCommands = portsKeys.map(function(k) {\n return [\"hmget\", k, \"port\", \"users\"];\n });\n redisClient.multi(redisCommands).exec(function(error, redisData) {\n var portsData = {};\n for(var i in redisData) {\n var data = redisData[i];\n portsData[data[0]] = data[1];\n }\n callback2(null, portsData);\n });\n }\n ], function(error, portsData) {\n var filterPorts = ports.filter(function(port) {\n if(portsData[port.port]) {\n port.users = portsData[port.port];\n }\n return !port.hidden;\n });\n callback(filterPorts);\n });\n}", "function gotList(thelist) {\n \n println(\"List of Serial Ports:\");\n\n\n menu = createSelect();\n var title = createElement('option', 'Choose a port:');\n menu.child(title);\n menu.position(windowWidth/2, windowHeight-50);\n menu.changed(openPort);\n\n for (var i = 0; i < thelist.length; i++) {\n var thisOption = createElement('option', thelist[i]);\n thisOption.value = thelist[i];\n menu.child(thisOption);\n println(i + \" \" + thelist[i]);\n }\n}", "function attachedInputPorts( node ) { \n\n return _.filter( node.inPorts, \n function( port) { return port.listAttached().length > 0; });\n}", "function getPeerList() {\r\n _doGet('/node/peer-list/all');\r\n }", "get portId() {\n return this.data[3];\n }", "function getPort() {\n return server.get('port');\n}", "static set port(value) {}", "function showPorts(node, show) {\n diagram = node.diagram;\n if (!diagram || diagram.isReadOnly || !diagram.allowLink) return;\n it = node.ports;\n while (it.next()) {\n port = it.value;\n port.stroke = (show ? \"black\" : null);\n }\n }", "function showPorts(node, show) {\r\n\t\tvar diagram = node.diagram;\r\n\t\tif (!diagram || diagram.isReadOnly || !diagram.allowLink) return;\r\n\t\tvar it = node.ports;\r\n\t\twhile (it.next()) {\r\n\t\t var port = it.value;\r\n\t\t port.stroke = (show ? \"#cccccc\" : null);\r\n\t\t port.fill = (show ? \"#dddddd\" : null);\r\n\t\t}\r\n\t }", "closePorts() {\n for (let i = 0; i < this.ports.length; i++) {\n if (this.ports[i] != -1 && this.ports[i] != 0) {\n this.ports[i].close();\n }\n }\n }", "function createPorts(data) {\n const ports = {};\n const group = [];\n for (let i = 0; i < data.length; i++) {\n const origin = data[i].origin;\n const sourcePosition = data[i].sourcePosition;\n const destination = data[i].destination;\n const targetPosition = data[i].targetPosition;\n\n if (destination in ports) {\n ports[destination] = {\n count: ports[destination].count + 1,\n position: targetPosition\n };\n } else {\n ports[destination] = {\n count: 1,\n position: targetPosition\n };\n }\n }\n const portsMod = [];\n Object.keys(ports).forEach(function(key) {\n portsMod.push({\n port: key,\n count: ports[key].count,\n coordinates: ports[key].position\n });\n });\n return portsMod;\n}", "function getList(){\n\t$.get('/hosts', function(hostList){\n\t\thosts = hostList;\n\t\t$('#pages').empty();\n for(var key in hostList){\n \tvar ports = hostList[key]['port'];\n \tif(typeof hostList[key]['port'] === 'string') ports = hostList[key]['port'].split(', ');\n \tfor(var port in ports) {\n var div = $('<div id=' + hostList[key]['ip'] + '-' + ports[port] + ' class=\"host\"><p>' + hostList[key]['reverse'] + '</p></div>');\n if (hostList[key]['thumbnails']) addThumbnail(div, ports[port], hostList[key]['thumbnails'], key);\n $(div).click(redirect);\n $('#pages').append($(div));\n }\n }\n\t})\n\t\t.done(function(){\n\t\t\twriteConfig();\n\t\t});\n}", "function getNewPortCount(){\n\tvar porttype = \"\";\n\tvar L1 = 0;var L2 = 0;var Open = 0;var direct = 0;\n\tfor(var i = 0; i < devPortInfoArray.length; i++){\n\t\tporttype = devPortInfoArray[i].PortTypeInfo\n\t\tporttype.toLowerCase();\n\t\tif(porttype==\"l1\")\n\t\t\tL1++\n\t\telse if(porttype==\"l2\")\n\t\t\tL2++\n\t\telse if(porttype==\"open port\")\n\t\t\tOpen++\n\t\telse\n\t\t\tdirect++\n\t}\n\tvar connectivity = 'L1=\"'+L1+'\",L2=\"'+L2+'\",Open=\"'+Open+'\"Direct=\"'+direct+'\"';\n\treturn connectivity\n}", "function electronSerialportDemoStuff() {\n SerialPort.list((err, ports) => {\n console.log('ports', ports);\n if (err) {\n document.getElementById('error').textContent = err.message\n return\n } else {\n document.getElementById('error').textContent = ''\n }\n\n if (ports.length === 0) {\n document.getElementById('error').textContent = 'No ports discovered'\n }\n\n const headers = Object.keys(ports[0])\n const table = createTable(headers)\n tableHTML = ''\n table.on('data', data => tableHTML += data)\n table.on('end', () => document.getElementById('ports').innerHTML = tableHTML)\n ports.forEach(port => table.write(port))\n table.end();\n })\n}", "function extractPort(ServiceName){\n\tconst appInfo = client.getInstancesByAppId(ServiceName);\n\treturn { port:appInfo[0].port['$'], hostname:appInfo[0].hostName }\n\n}", "static get PORT_PMA_3() {\n return new Port(\"HOST\", 0, 2.13, 16.18, 0, 180, 0);\n }", "get portInput() {\n return this._port;\n }", "get portInput() {\n return this._port;\n }", "function getFreePort() {\n return ports.find((port) => port.usableCache);\n}", "function findInterestingPorts(ports) {\n var foundPorts = [];\n for (var _i = 0, ports_1 = ports; _i < ports_1.length; _i++) {\n var port = ports_1[_i];\n for (var _a = 0, keywords_1 = keywords; _a < keywords_1.length; _a++) {\n var keyword = keywords_1[_a];\n if (port.displayName.indexOf(keyword) !== -1) {\n foundPorts.push(port);\n break;\n }\n }\n }\n return foundPorts;\n }", "function readCOM() {\n var sp = require(\"serialport\");\n var mod0select = document.getElementById(\"mod0select\");\n var mod1select = document.getElementById(\"mod1select\");\n var mod2select = document.getElementById(\"mod2select\");\n var mod3select = document.getElementById(\"mod3select\");\n\n // Read this.ports from Serial port and create a variable ports.\n sp.list().then((ports) => {\n var i = 0;\n ports.forEach(function (port) {\n i = i + 1;\n\n // Add port to list\n // There has to be a better way to do this\n var option = document.createElement(\"option\");\n option.text = port.path;\n option.setAttribute(\"value\", i);\n mod0select.add(option);\n\n var option = document.createElement(\"option\");\n option.text = port.path;\n option.setAttribute(\"value\", i);\n mod1select.add(option);\n\n var option = document.createElement(\"option\");\n option.text = port.path;\n option.setAttribute(\"value\", i);\n mod2select.add(option);\n\n var option = document.createElement(\"option\");\n option.text = port.path;\n option.setAttribute(\"value\", i);\n mod3select.add(option);\n });\n });\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}", "getPort2() {\n return 0;\n }", "get _nextPort() {\n return this.portList[this.portIndex++] || 0;\n }", "IsPortAllowed() {\n\n }", "function getPeerList () {\n var data = {\n peerlist: true,\n pid: peerId,\n }\n var msg = JSON.stringify(data);\n ws.send(msg)\n}", "get toPortInput() {\n return this._toPort;\n }", "lists() {\n const board = ReactiveCache.getBoard(this.selectedBoardId.get());\n const ret = board.lists();\n return ret;\n }", "list() {\n\t\treturn this.devices.map(d => d.toJSON());\n\t}", "_buildDevicesPortmap(devices) {\n const dev2portmap = {};\n devices.forEach(device => {\n const lags = device.readKV('network.lags');\n if (lags) {\n const portmap = {};\n const ports = lags.port;\n const groups = {};\n for (let p in ports) {\n if (ports[p].group) {\n const portnr = parseInt(p);\n const group = ports[p].group;\n if (group in groups) {\n groups[group].ports.push(portnr);\n }\n else {\n groups[group] = {\n type: ports[p].type,\n port: portnr,\n ports: [ portnr ],\n group: group\n };\n }\n portmap[portnr] = groups[group];\n }\n }\n dev2portmap[device._id] = portmap;\n }\n });\n Log('portmap:', JSON.stringify(dev2portmap, null, 1));\n return dev2portmap;\n }", "get listenerPort() {\n return this._listenerPort;\n }", "function list() {\n return networks;\n }", "getAvailablePort() {\n var port = Math.floor(Math.random() * (5000 - 4000 + 1)) + 4000;\n while(this.portArray.indexOf(port)>0){\n port = Math.floor(Math.random() * (5000 - 4000 + 1)) + 4000;\n }\n console.log(\"port :\"+port);\n this.portArray.push(port);\n return port; \n }", "getSwarmPeers() {\n var swarmPeers = []\n this.ipfs.swarm.peers(function(err, peerInfos) {\n if (err) {\n this.app.logger.error(err)\n }\n peerInfos.forEach(element => {\n swarmPeers.push({\n id: new PeerId(element.peer.id).toB58String(),\n addrs: multiaddr(element.addr.buffer).toString()\n })\n })\n })\n return swarmPeers\n }", "function list() {\n return request({\n url: `/nodes`,\n method: 'GET'\n })\n}", "function getPort() {\n var self = this;\n if (typeof self.parameters.port === 'undefined') {\n return self.parameters.secure ? 443 : 80;\n } else {\n return self.parameters.port;\n }\n}", "function isPortAllowed(port) {\n if (!port || typeof port != \"string\" || port.length == 0) {\n return false;\n }\n\n var allowed = config.permissions.allowedPorts;\n \n //Allow all if list not defined\n if (!allowed) {\n return true;\n }\n \n //Allow only specific\n for (var i = 0; i < allowed.length; i++) {\n if (allowed[i].toLowerCase() == port.toLowerCase()) {\n return true;\n }\n }\n \n return false;\n}", "get host(){\n return new Array(this._host);\n }" ]
[ "0.7853014", "0.75441885", "0.74799854", "0.7265588", "0.71404546", "0.71372634", "0.69666374", "0.65937644", "0.65558815", "0.6530326", "0.6418495", "0.6373536", "0.6326681", "0.62959504", "0.6288749", "0.6274038", "0.626407", "0.6226336", "0.6221951", "0.6214548", "0.6206073", "0.6206073", "0.6204331", "0.6196938", "0.6187205", "0.6171396", "0.6144772", "0.6144772", "0.6144772", "0.6144772", "0.6144772", "0.6144772", "0.6077613", "0.6063892", "0.60520154", "0.604699", "0.6038562", "0.6036857", "0.6024198", "0.60191774", "0.60191774", "0.5999008", "0.5973423", "0.5967365", "0.5967365", "0.59580374", "0.59553665", "0.59275115", "0.5921228", "0.5921228", "0.590448", "0.5899535", "0.5878948", "0.58771855", "0.5873863", "0.5866461", "0.585286", "0.58502656", "0.5845398", "0.57941675", "0.5781327", "0.5725453", "0.5698375", "0.5665771", "0.56555086", "0.56498533", "0.5647825", "0.56393254", "0.5636319", "0.56314915", "0.558796", "0.55633485", "0.55525845", "0.5543436", "0.5527615", "0.54882556", "0.5481526", "0.546065", "0.546065", "0.54589486", "0.5458687", "0.54405546", "0.5425047", "0.5404866", "0.53855836", "0.5379834", "0.53708196", "0.53685975", "0.5367752", "0.5358878", "0.5358516", "0.53551704", "0.53512686", "0.5338364", "0.53131014", "0.5307696", "0.5289296", "0.52846533", "0.527468" ]
0.6384153
12
Start function to create new pvid
function replaceAdParam(srcStr, pName, pValue) { var paramRegEx = new RegExp("\\b" + pName + "=[^&#\"']*"); srcStr = srcStr.replace(paramRegEx, pName + "=" + pValue); return srcStr; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function makevid(preformer){\r\n\r\n// image\r\n\tprefimg='<img class=\"png\" width=\"180\" height=\"148\" src=\"http://cdn-i.highwebmedia.com/roomimage/'+preformer+'.jpg\" img style=\"float:right;margin-right:100px;margin-top:10px;border-width:5px;border-style:double; \">';\r\n\tFversion=readCookie(\"CBversion\")\r\n\tif(!Fversion){Fversion=\"http://ccstatic.highwebmedia.com/static/flash/CBV_2p644.swf\"}\r\n\tvideodata2 = videodata2.replace(\"ladroop\",preformer);\r\n\tnewvid=document.createElement('div');\r\n\tnewvid.style.clear=\"both\";\r\n\tnewvid.innerHTML=prefimg+videodata1+Fversion+videodata2;\r\n\tdocument.getElementsByClassName('block')[0].appendChild(newvid)}", "function start() {\r\n intro.classList.add('hidden');\r\n startKnop.classList.add('hidden');\r\n video.classList.remove('hidden');\r\n\r\n filmpje = document.createElement('source');\r\n filmpje.src = 'videos/1+2.mp4';\r\n filmpje.type = 'video/mp4';\r\n video.appendChild(filmpje);\r\n video.play();\r\n}", "function createVideo() {\n var video = getVideoObject();\n submitVideo(video, 'create_video', onCreateSuccess);\n}", "function spawnAllVideos() {\n createVideo(new THREE.Vector3(0,0,0), \"field\", \"edited\");\n}", "function preload(){\n vid = createVideo(\"videos/2.mp4\");\n}", "function videoStarter() {\n\n\t$('#hero').vide({\n\t\tmp4:'videos/headerloop4.mp4',\n\t\togv:'videos/headerloop4.ogv',\n\t\twebm:'videos/headerloop4.webm'\n\t\t}, {\n\t\tloop: true,\n\t\tmuted: true,\n\t\tautoplay: true,\n\t\tposterType: \"jpg\",\n\t\tclassName: \"tn-video\"\n\t});\n\n}", "function startParade() {\n player.playVideo();\n // Lets the video start for a brief moment before the GIF cycling is called\n setTimeout(function(){\n imgCycle(0);\n $('#chyron h1').text(paradeTitle);\n $('#wrapper').removeClass('loading');\n },400);\n \n }", "function startVideo() {\n\n // start video\n vid.play();\n // start tracking\n ctrack.start(vid);\n trackingStarted = true;\n // start loop to draw face\n// drawLoop();\t\n\tvar t2 = setTimeout(\"drawLoop()\",10000);\t\n setCommandValue(\"System is loading ...\");\n var t2 = setTimeout(\"setCommandValue('Round 1, ready? 😎')\",4000);\n var t2 = setTimeout(\"setCommandValue('Now, follow my order 😜')\",7000);\n var t2 = setTimeout(\"setCommandValue('Show your happy to endless work 😅')\",10000);\n var t9 = setTimeout(\" round1 = true\",10000);\n\n}", "function createPVCs() //----this application configuration----\r\n{\r\n //buildProcessVariableChart(id, title, timeLine, timeLineUnits, faceColor, leftVariable, minLeft, maxLeft, setPointLeft, right1Variable, minRight1, maxRight1, right2Variable, minRight2, maxRight2, scale, transX, transY)<br>\r\n buildProcessVariableChart(\"hwsPVC\", \"Heating Hot Water\",60,\"Minutes\",\"yellow\",\"HWS(\\u00B0F)\", 60, 220,160, null, null, null, null,null,null,.2,20,50);\r\n buildProcessVariableChart(\"fanPVC\", \"Fan Static Pressure\",60,\"Minutes\",\"#ffd700\",\"STP(in W.C.)\", 0, 5, 3.25, \"Fan(HZ)\", 60, 180, null, null, null, .3,10,150);\r\n buildProcessVariableChart(\"pumpPVC\", \"Hot Water Flow \",60,\"Minutes\",\"#adff2f\",\"HWS(\\u00B0F)\", 60, 220, 150, \"Flow(GPM)\", 0, 600, \"OAT(\\u00B0F)\",-20, 120,.4,20,290);\r\n}", "function startLocalPreview() {\n log_d(\"Starting local video\");\n $('#webcamsSelect').val(window.configuredDevice);\n var succHandler = function (sinkId) {\n window.localPreviewStarted = true;\n log_d(\"Local video started. Setting up renderer\");\n var rendererContent = RENDER_LOCAL_TMPL.replace('#', '_local');\n $('.feeds-wrapper').append($(rendererContent));\n CDO.renderSink(sinkId, 'userFeed_local');\n };\n service.startLocalVideo(CDO.createResponder(succHandler));\n}", "function trackVideoStart( videoid )\n\t{\n\t\tconsole.log( videoid + \" : start\" );\n\t\t\n\t\t// commented out Omniture/SiteCatalyst code\n\t\t/*if (typeof (s_dell) != 'undefined') \n\t\t{\n\t\t\ts_dell.linkTrackVars = 'prop2,prop13,prop49,eVar24';\n\t\t\ts_dell.linkTrackEvents = 'event16';\n\t\t\ts_dell.events = s_dell.apl( s_dell.events, 'event16', ',', 2 );\n\t\t\ts_dell.eVar24 = videoid;\n\t\t\ts_dell.tl( true, 'o', videoid );\n\t\t}*/\n\t}", "function create() {\n // var name = [ 'tobi', 'loki', 'jane', 'manny' ][ Math.random() * 4 | 0 ];\n // console.log( '- creating job for %s', name );\n // jobs.create( 'video conversion', {\n // title: 'converting ' + name + '\\'s to avi', user: 1, frames: 200\n // } ).save();\n // setTimeout( create, Math.random() * 3000 | 0 );\n}", "function startStream() {\r\n\r\n if (navigator.platform == \"iPhone\" || navigator.platform == \"Linux armv8l\") {\r\n vid = createCapture(VIDEO, constraints)\r\n } else {\r\n\r\n vid = createCapture(VIDEO);\r\n }\r\n\r\n vid.position(0, 0)\r\n button.remove()\r\n select(\"#accept\").remove()\r\n\r\n classifyVideo()\r\n\r\n}", "function start() {\n\n id = realtimeUtils.getParam('id');\n if (id) {\n // Load the document id from the URL\n realtimeUtils.load(id.replace('/', ''), onFileLoaded, onInitialize);\n init();\n } else {\n // Create a new document, add it to the URL\n realtimeUtils.createRealtimeFile('MyWebb App', function (createResponse) {\n window.history.pushState(null, null, '?id=' + createResponse.id);\n id=createResponse.id;\n realtimeUtils.load(createResponse.id, onFileLoaded, onInitialize);\n init();\n });\n \n }\n \n \n }", "function onClickTakeVPS() {\n\n // Add all frame controls to the controller\n clrImgTags();\n vpsController.desiredFrameControllers.clear();\n var sel = document.getElementById(\"lstFrames\");\n for (var j = 0; j < sel.length; j++) {\n addNewImgTag(j);\n logMessage(sel.options[j].text + \"=\" + sel.options[j].value);\n var id = sel.options[j].value;\n vpsController.desiredFrameControllers.append(frameControllers[id]);\n }\n // Prepare VPS\n prepareVariablePhotoSequence();\n\n}", "function makeViewer(pSize=null, prepend=[], append=[]){\n\tviewerParams.haveUI = false;\n\tviewerParams.ready = false; \n\tconsole.log(\"Waiting for viewer init ...\")\n\tclearInterval(viewerParams.waitForInit);\n\tviewerParams.waitForInit = setInterval(function(){ \n\t\tvar ready = confirmViewerInit();\n\t\tif (ready){\n\t\t\tconsole.log(\"Viewer ready.\")\n\t\t\tclearInterval(viewerParams.waitForInit);\n\t\t\tviewerParams.ready = true;\n\t\t\tviewerParams.pauseAnimation = false;\n\t\t\tviewerParams.parts.options_initial = createPreset(); //this might break things if the presets don't work...\n\t\t\t//console.log(\"initial options\", viewerParams.parts.options)\n\n\t\t\t//to test\n\t\t\tif (pSize) {\n\t\t\t\tviewerParams.PsizeMult.Gas = pSize;\n\t\t\t\tconsole.log('new Psize', pSize)\n\t\t\t}\n\t\t\tsendInitGUI(prepend=prepend, append=append);\n\t\t}\n\t}, 100);\n}", "function playerCreation() {\n console.log(\"player-creation\");\n //scrolltotop();\n }", "function startVideoContent()\n{\n app.log(2, 'startVideoContent');\n setTimeout(function()\n {\n Callcast.AddSpot({spotReplace: 'first-unoc', spotNodup: 1, spotType: 'youtube',\n ytid: 'ZAvL3j3hOCU', // youtube is a conference\n spotDivId: 'demo-video-1'\n });\n }, 1000);\n setTimeout(function()\n {\n Callcast.AddSpot({spotReplace: 'last-unoc', spotNodup: 1, spotType: 'youtube',\n ytid: 'BW44KXIu7Q8', // Daphne Koller coursera interview\n spotDivId: 'demo-video-2'\n });\n }, 1000);\n return false;\n}", "function start() {\n if (started === true) return;\n started = true;\n console.debug(scriptname, \"started\");\n let container = video.parentElement.closest('div[id]');\n if (container === null) {\n container = video.parentElement;\n }\n self.container = container;\n container.appendChild(self.elements.toolbar);\n container.appendChild(self.elements.notify);\n self.elements.buttons.download.href = self.videolink();\n /**\n * Events\n */\n self.on('click', e => {\n e.stopPropagation();\n let target = e.target, btn;\n if ((btn = e.target.closest('[class*=\"-bt\"]')) !== null) {\n if (btn.classList.contains('download-bt')) {\n btn.href = self.videolink();\n if (btn.href === doc.location.href) {\n e.preventDefault();\n }\n }\n if (btn.classList.contains('clipboard-bt')) {\n e.preventDefault();\n copyToClipboard(self.videolink());\n }\n if (btn.classList.contains('subtitles-bt')) {\n if (this.href === doc.location.href) e.preventDefault();\n }\n if (typeof btn.dataset.notify === s) {\n self.notify(btn.dataset.notify);\n }\n }\n return false;\n });\n self.on('contextmenu', e => e.preventDefault());\n\n self.ready = true;\n trigger(self.video, 'streamgrabber.ready');\n if (video.paused) self.show();\n }", "function startCreating() {\n mainVm.isCreating = true;\n mainVm.isEditing = false;\n }", "function trackVideoStart() {\n\n flushParams();\n correlateMediaPlaybackEvents();\n\n s.Media.open(videoFileName, videoStreamLength, omniturePlayerName());\n s.Media.play(videoFileName, 0, 0);\n }", "function newProject(spec) {\n //first upload the files for pictures and pvs source\n uploadFile(spec.prototypeImage, function (res) {\n var uploadedImageFile = JSON.parse(res.responseText).fileName;\n uploadFile(spec.pvsSpec, function (res) {\n var uploadedSpecFile = JSON.parse(res.responseText).fileName;\n //call websocket to create new project\n ws.send({\n type: \"createProject\",\n uploadedSpecFileName: uploadedSpecFile,\n clientSpecFileName: spec.pvsSpec.name,\n projectName: spec.projectName,\n uploadedImageFileName: uploadedImageFile,\n clientImageFileName: spec.prototypeImage.name\n }, function (res) {\n console.log(res);\n if (!res.error) {\n currentProject = res;\n d3.select(\"div#body\").style(\"display\", null);\n ws.startPVSProcess(res.spec.split(\".pvs\")[0], currentProject.name,\n pvsProcessReady);\n var imagePath = \"../../projects/\" + currentProject.name + \"/\" +\n currentProject.image;\n updateImage(imagePath);\n updateProjectName(currentProject.name);\n d3.select(\"#imageDragAndDrop.dndcontainer\").style(\"display\", \"none\");\n }\n });\n });\n });\n\t}", "function StartupExternalVideoSource() {\n dbExternalXY.find({}, {}, function (err, docs) {\n if (docs.length > 0) {\n // console.log(docs[0].X)\n\n fs.readFile(path.join(__dirname, 'config.xml'), \"utf8\", function read(err, data) {\n var readjsondata;\n if (data != '') {\n readjsondata = JSON.parse(data);\n if (readjsondata.startup == '2') {\n const { exec } = require(\"child_process\");\n\n // let data = 'ffplay -f dshow -rtbufsize 702000k -framerate 60 -x 700 -y 1080 -left 670 -top 0 -i video=\"USB Video\":audio=\"@device_cm_{33D9A762-90C8-11D0-BD43-00A0C911CE86}\\\\wave_{6B25EFFC-EB1F-4827-A7CE-A6C5CA92EFA2}\" -threads 3 -noborder'\n let data = 'ffplay -f dshow -rtbufsize 702000k -framerate 60 -x '+ docs[0].w +' -y '+ docs[0].h +' -left '+ docs[0].l + ' -top '+ docs[0].t +' -i video=\"USB Video\":audio=\"Digital Audio Interface (2- USB Digital Audio)\" -threads 3 -noborder -alwaysontop'\n\n exec(data, (error, stdout, stderr) => {\n if (error) {\n console.log(`error: ${error.message}`);\n return;\n }\n if (stderr) {\n console.log(`stderr: ${stderr}`);\n // setTimeout((function() {\n // return process.exit();\n // }), 5000);\n return;\n }\n console.log(`stdout: ${stdout}`);\n });\n }\n }\n });\n }\n })\n}", "function piloteVideo4() {\r\n\t\tif (LGDM.paused) {\r\n\t\t\tLGDM.play();\r\n \r\n\t\t} else {\r\n\t\t\tLGDM.pause();}\r\n }", "function createPause(){\n pauseScreen = initScene();\n\n // SCENE COMPONENTS GO HERE.\n // THE ACTUAL SCENE HAS YET TO BE CREATED.\n\n // lights\n \t\tvar light = createPointLight();\n \t\tlight.position.set(0,200,20);\n \t\tpauseScreen.add(light);\n\n // camera\n \t\tpauseCam = new THREE.PerspectiveCamera( 90, window.innerWidth / window.innerHeight, 0.1, 1000 );\n \t\tpauseCam.position.set(0,50,1);\n \t\tpauseCam.lookAt(0,0,0);\n }", "async function newRecording() {\n\tconsole.log(\"Starting new recording...\");\n\n\tlet currentOutput = path.join(Config.recordings, (new Date().toISOString()).replace(/[:TZ\\.]/g, '-'));\n\tcurrentOutputFile = currentOutput + \".h264\";\n\tcurrentCamera = newCamera(currentOutputFile);\n\tcurrentCamera.start();\n\tconsole.log(`Started recording: ${currentOutputFile}`);\n\n\tcurrentSubjects = 0;\n\n\tcurrentVid = await randomBytes(8);\n\tcurrentKey = await randomBytes(32);\n\n\tlet bytes = Buffer.allocUnsafe(3);\n\tbytes.writeUInt8(sn, 0);\n\tbytes.writeUInt16LE(Config.reconnectIn / 100, 1);\n\n\tupdateKeyCharac(Buffer.concat([currentKey, bytes, currentVid, lastHash.subarray(0,20)]));\n}", "function startNew(options) {\n return Private.startNew(options);\n }", "function startNew(options) {\n return Private.startNew(options);\n }", "function init() {\n const rand = Math.random();\n const video_index = Math.floor(number_videos * rand);\n console.log(video_index);\n const vidPlayer = document.getElementById('videoPlayer');\n vidPlayer.innerHTML = `<source src=\"./goal/${video_index}\" type=\"video/mp4\">`;\n\n window.addEventListener('load', function() {\n console.log('loaded');\n vidPlayer.play();\n }, false);\n\n // const VP = document.getElementById('videoPlayer')\n // const VPToggle = document.getElementById('butt')\n\n // VPToggle.addEventListener('click', function() {\n // if (vidPlayer.paused) vidPlayer.play()\n // else vidPlayer.pause()\n // })\n}", "createResult() {\n this.scene.launch(\"End\", [count, t]);\n this.scene.pause();\n console.log(\"pausiert\");\n }", "function startPublishing() {\n\t\tif (!publisher) {\n\t\t\tvar parentDiv = document.getElementById(\"myCamera\");\n\t\t\tvar publisherDiv = document.createElement('div'); // Create a div for the publisher to replace\n\t\t\tpublisherDiv.setAttribute('id', 'opentok_publisher');\n\t\t\t\n\t\t\t// Remove loading screen and append the video \n\t\t\t$('div#user1_loading').css('display', 'none');\n\t\t\tparentDiv.appendChild(publisherDiv);\n\t\t\t\n\t\t\tvar publisherProps = {width: VIDEO_WIDTH, height: VIDEO_HEIGHT};\n\t\t\tpublisher = TB.initPublisher(apiKey, publisherDiv.id, publisherProps); // Pass the replacement div id and properties\n\t\t\tsession.publish(publisher);\n\t\t}\n\t}", "function startVideo() {\n video.isReady = true;\n}", "function start(){\n\t\n}", "function startVideo() {\n console.log(\"Inside Start Video\");\n stream.getVideoTracks()[0].enabled = true;\n }", "function PStart() {\r\n\t\ttry {\r\n\t\t\tvar permalink = _r3PlayerInstance.masterPlayer.getTrack().permalink;\r\n\t\t} catch (e) {\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tif ('string' != typeof permalink || permalink == '') {\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tJSONReq('GetTrack',\r\n\t\t\t'{\"playlistPermalink\":\"' + permalink + '\",\"sequence\":0}',\r\n\t\tfunction(track) {\r\n\t\t\t// Replace the inner text node of the track label with a link.\r\n\t\t\tMakeLink(capelm, track, track.Title + GetTrackTime(track));\r\n\t\t\tResetTA();\r\n\t\t});\r\n\t}", "startPlyr() {\n\n // Add started class to handle display banners hide/show\n this.container.classList.add('tubia__started');\n this.displayIsShown = false;\n\n // Call Google Analytics and Death Star.\n this.analytics();\n\n // Configure Honeybadger to start monitoring the system\n this.codemonitor.configure();\n\n // Remove our click listener to avoid double clicks.\n this.playButton.removeEventListener('click', this.startPlyrHandler, false);\n\n // Hide the play button.\n this.playButton.classList.toggle('tubia__active');\n\n setTimeout(() => {\n // Show our spinner loader.\n this.hexagonLoader.classList.toggle('tubia__active');\n // If lottie animation is not active hide the poster image.\n if (!this.options.lottie) {\n this.posterPosterElement.style.display = 'none';\n }\n // Remove the button.\n this.playButton.parentNode.removeChild(this.playButton);\n // Load our player.\n this.loadPlyr();\n }, 200); // Wait for the play button to hide.\n\n // Destroy our display ad if it exists.\n const displayAd = document.getElementById('tubia__display-ad');\n if (displayAd) {\n displayAd.parentNode.removeChild(displayAd);\n }\n }", "function setup() {\n noCanvas(400, 400);\n\n vid = createVideo(\n ['roadworkahead.mp4'],\n vidLoad\n );\n\n vid2 = createVideo(\n ['theycall.mp4'],\n vidLoad\n );\n \n vid3 = createVideo(\n ['bible.mp4'], \n vidLoad\n );\n \n vid4 = createVideo(\n ['2bros.mp4'], \n vidLoad\n );\n \n vid5 = createVideo(\n ['eve.mp4'], \n vidLoad\n );\n \n vid6 = createVideo(\n ['chip.mp4'], \n vidLoad\n );\n \n vid7 = createVideo(\n ['RedDress.mp4'], \n vidLoad\n );\n vid8 = createVideo(\n ['Sprite.mp4'],\n vidLoad\n );\n\n vid9 = createVideo(\n ['mouse.mp4'],\n vidLoad\n );\n \n vid10 = createVideo(\n ['Backstreet.mp4'], \n vidLoad\n );\n \n vid11 = createVideo(\n ['eep.mp4'], \n vidLoad\n );\n \n vid12 = createVideo(\n ['pizza.mp4'], \n vidLoad\n );\n \n vid13 = createVideo(\n ['wakeup.mp4'], \n vidLoad\n );\n \n vid14 = createVideo(\n ['raccoon.mp4'], \n vidLoad\n );\n vid15 = createVideo(\n ['who-are.mp4'],\n vidLoad\n );\n\n vid16 = createVideo(\n ['whoWant.mp4'],\n vidLoad\n );\n \n vid17 = createVideo(\n ['run.mp4'], \n vidLoad\n );\n \n vid18 = createVideo(\n ['church.mp4'], \n vidLoad\n );\n \n vid19 = createVideo(\n ['morning.mp4'], \n vidLoad\n );\n \n vid20 = createVideo(\n ['scream-kid.mp4'], \n vidLoad\n );\n \n vid21 = createVideo(\n ['dance-luke.mp4'], \n vidLoad\n );\n \n vid22 = createVideo(\n ['adel-luke.mp4'],\n vidLoad\n );\n\n vid23 = createVideo(\n ['taco.mp4'],\n vidLoad\n );\n \n vid24 = createVideo(\n ['hello.mp4'], //replace with new video file\n vidLoad\n );\n \n vid25 = createVideo(\n ['vodka.mp4'], //replace with new video file\n vidLoad\n );\n \n vid26 = createVideo(\n ['Ah-mouse.mp4'], //replace with new video file\n vidLoad\n );\n \n vid27 = createVideo(\n ['drop.mp4'], //replace with new video file\n vidLoad\n );\n \n vid28 = createVideo(\n ['kush.mp4'], \n vidLoad\n );\n \n vid29 = createVideo(\n ['kevin.mp4'], \n vidLoad\n );\n \n vid30 = createVideo(\n ['kermit.mp4'], \n vidLoad\n );\n \n vid31 = createVideo(\n ['fresh.mp4'], \n vidLoad\n );\n \n vid32 = createVideo(\n ['dance.mp4'],\n vidLoad\n );\n\n vid33 = createVideo(\n ['chill.mp4'],\n vidLoad\n );\n \n vid34 = createVideo(\n ['wow.mp4'], \n vidLoad\n );\n \n vid35 = createVideo(\n ['tort.mp4'], \n vidLoad\n );\n \n vid36 = createVideo(\n ['mole.mp4'], \n vidLoad\n );\n //create video refrence page\n \n \n //Matt helped me create some arrays, I was using Python logic for Lists before he corrected me.\n h = hour();\n s = second();\n list1 = [vid6, vid14, vid23, vid25, vid28, vid31, vid35, vid36, vid33]; \n //list1 is noon\n list2 = [vid, vid4, vid2, vid3, vid9, vid16, vid13, vid11, vid15, vid17, vid18, vid19, vid20, vid22]; \n //list2 is morning\n list3 = [vid5, vid7, vid8, vid10, vid12, vid21, vid24, vid26, vid27, vid29, vid30, vid32, vid34]; \n //list3 is evening\n \n vid.size(400, 400);\n \n //with Matts help I can now hide the videos, also kfrajer on Processing Forum helped with hiding and loading up the videos. https://forum.processing.org/two/discussion/23870/p5js-problem-with-asynchronous-video-loading-playing\n \n vid.hide();\n vid2.hide();\n vid3.hide();\n vid4.hide(); \n vid5.hide(); \n vid6.hide(); \n vid7.hide(); \n vid8.hide();\n vid9.hide();\n vid10.hide();\n vid11.hide(); \n vid12.hide(); \n vid13.hide(); \n vid14.hide(); \n vid15.hide();\n vid16.hide();\n vid17.hide();\n vid18.hide(); \n vid19.hide(); \n vid20.hide(); \n vid21.hide(); \n vid22.hide();\n vid23.hide();\n vid24.hide();\n vid25.hide(); \n vid26.hide(); \n vid27.hide(); \n vid28.hide(); \n vid29.hide(); \n vid30.hide(); \n vid31.hide();\n vid32.hide();\n vid33.hide();\n vid34.hide(); \n vid35.hide(); \n vid36.hide(); \n \n vid.volume(0);\n vid2.volume(0);\n vid3.volume(0);\n vid4.volume(0);\n vid5.volume(0);\n vid6.volume(0);\n vid7.volume(0);\n vid8.volume(0);\n vid9.volume(0);\n vid10.volume(0);\n vid11.volume(0);\n vid12.volume(0);\n vid13.volume(0);\n vid14.volume(0);\n vid15.volume(0);\n vid16.volume(0);\n vid17.volume(0);\n vid18.volume(0);\n vid19.volume(0);\n vid20.volume(0);\n vid21.volume(0);\n vid22.volume(0);\n vid23.volume(0);\n vid24.volume(0);\n vid25.volume(0);\n vid26.volume(0);\n vid27.volume(0);\n vid28.volume(0);\n vid29.volume(0);\n vid30.volume(0);\n vid31.volume(0);\n vid32.volume(0);\n vid33.volume(0);\n vid34.volume(0);\n vid35.volume(0);\n vid36.volume(0);\n \n //The hour function and a bit of tweaking with Matts help now the hour is specific to what time of day a video will load\n \n //below is more than 12, pm\n if (hour() > 12) {\n currentVideo = random(list3);\n }\n//below is less than 12, am\n if (hour() < 12) {\n currentVideo = random(list2);\n }\n //currentVideo.show();\n //below is equal to 12, noon\n if (hour() == 12) {\n currentVideo = random(list1);\n }\n currentVideo.show(); \n currentVideo.loop();\n currentVideo.volume(1);\n \n }", "start() {// [3]\n }", "function init() {\n spielstart();\n}", "function PickNewVideo(iVideoInfo, iAutoPlay, iQuote, iPageObjectIds)\r\r\n{\r\r\n DebugLn(\"PickNewVideo\");\r\r\n if (isObject(iVideoInfo))\r\r\n {\r\r\n DebugLn(\"iVideoInfo.Description = \" + iVideoInfo.Description);\r\r\n DebugLn(\"iVideoInfo.Link = \" + iVideoInfo.Link);\r\r\n \r\r\n if (iVideoInfo.Link && \r\r\n iVideoInfo.Link.length > 0)\r\r\n {\r\r\n pageObjectIds = {VideoDiv: \"VideoDiv\", \r\r\n NamePar: \"VideoName\", \r\r\n DescPar: \"VideoDesc\"};\r\r\n \r\r\n if (isObject(iPageObjectIds))\r\r\n {\r\r\n if (StringLength(iPageObjectIds.VideoDiv) > 0)\r\r\n pageObjectIds.VideoDiv = iPageObjectIds.VideoDiv;\r\r\n if (StringLength(iPageObjectIds.NamePar) > 0)\r\r\n pageObjectIds.NamePar = iPageObjectIds.NamePar;\r\r\n if (StringLength(iPageObjectIds.DescPar) > 0)\r\r\n pageObjectIds.DescPar = iPageObjectIds.DescPar;\r\r\n }\r\r\n \r\r\n // Reset video division\r\r\n SetElementHtml(pageObjectIds.VideoDiv,LoadingHtml());\r\r\n\r\r\n // Set video link \r\r\n DebugLn(\"iVideoInfo.AudioPlayer = \" + iVideoInfo.AudioPlayer);\r\r\n videoLink = iVideoInfo.Link;\r\r\n if (StringLength(iVideoInfo.AudioPlayer) > 0)\r\r\n {\r\r\n videoLink = iVideoInfo.AudioPlayer;\r\r\n }\r\r\n DebugLn(\"videoLink = \" + videoLink);\r\r\n\r\r\n // Put video on page.\r\r\n var so = new SWFObject(videoLink, \"VideoEmbed\", \"425\", \"355\", \"9\", \"#6f7a9e\");\r\r\n if (so)\r\r\n {\r\r\n DebugLn(\"Have swf object.\");\r\r\n\r\r\n if (iVideoInfo.Attribute)\r\r\n\t{\r\r\n DebugLn(\"iVideoInfo.Attribute.length = \" + iVideoInfo.Attribute.length);\r\r\n for (iiAtt=0; iiAtt<iVideoInfo.Attribute.length; iiAtt++)\r\r\n {\r\r\n DebugLn('iiAtt = ' + iiAtt + \": \" + \r\r\n iVideoInfo.Attribute[iiAtt].Name + \" = \" + iVideoInfo.Attribute[iiAtt].Value);\r\r\n so.addVariable(iVideoInfo.Attribute[iiAtt].Name, iVideoInfo.Attribute[iiAtt].Value);\r\r\n }\r\r\n\t}\r\r\n\r\r\n if (iAutoPlay)\r\r\n so.addVariable(\"autoplay\", 1);\r\r\n\r\r\n if (StringLength(iVideoInfo.AudioPlayer) > 0)\r\r\n so.addVariable(\"playlist_url\", iVideoInfo.Link);\r\r\n\r\r\n swfHtml = so.getSWFHTML();\r\r\n if (swfHtml && \r\r\n swfHtml.length > 0)\r\r\n\t{\r\r\n DebugLn(\"swfHtml = \" + swfHtml.replace(/</, \"@\"));\r\r\n SetElementHtml(pageObjectIds.VideoDiv,swfHtml);\r\r\n //so.write(pageObjectIds.VideoDiv);\r\r\n }\r\r\n else\r\r\n {\r\r\n SetElementHtml(pageObjectIds.VideoDiv,BadFlashErrorHtml());\r\r\n }\r\r\n }\r\r\n else\r\r\n {\r\r\n SetElementHtml(pageObjectIds.VideoDiv,JavascriptErrorHtml());\r\r\n }\r\r\n\r\r\n // Put name with video.\r\r\n videoName = iVideoInfo.Name;\r\r\n DebugLn(\"videoName = \" + videoName);\r\r\n SetElementHtml(pageObjectIds.NamePar, videoName);\r\r\n \r\r\n // Put description with video.\r\r\n videoDesc = \"\";\r\r\n if (StringLength(iVideoInfo.Description) > 0)\r\r\n {\r\r\n videoDesc = iVideoInfo.Description;\r\r\n if (iQuote)\r\r\n videoDesc = '\"' + videoDesc +'\"';\r\r\n else\r\r\n videoDesc = videoDesc;\r\r\n }\r\r\n else if (StringLength(iVideoInfo.Date) > 0)\r\r\n {\r\r\n if (StringLength(iVideoInfo.Number) > 0)\r\r\n videoDesc += \"Message \" + iVideoInfo.Number;\r\r\n videoDesc += \"<br/>\" + iVideoInfo.Date;\r\r\n if (StringLength(iVideoInfo.Speaker) > 0)\r\r\n videoDesc += \"<br/>\" + iVideoInfo.Speaker;\r\r\n }\r\r\n DebugLn(\"videoDesc = \" + videoDesc);\r\r\n SetElementHtml(pageObjectIds.DescPar, videoDesc);\r\r\n }\r\r\n }\r\r\n}", "start () {}", "function setupVideos() {\n vid2 = $('#vid02')[0];\n vidSB01 = $('#vidSB01')[0];\n }", "start() {}", "start() {}", "start() {}", "start() {}", "start() {}", "start() {}", "function setUpVideo( _id )\n {\n scope.stopVideoTimer();\n\n if( !videos[ _id ] ) return;\n currentVidVo = videos[ _id ];\n\n firedProgressEvents = [];\n video.setAttribute( 'src', getVideoPath());\n }", "function start() {\n\n}", "makeViewer(player) {\n player.once('spawn', () => {\n const port = this.getFreePort();\n player.viewerPort = port;\n viewer(player, { firstPerson: true, port });\n });\n }", "start() {\n const { creator, conf } = this;\n const upStreaming = conf.getVal('upStreaming');\n\n if (upStreaming) {\n this.liveOutput();\n } else if (ScenesUtil.isSingle(creator)) {\n this.mvOutput();\n } else {\n if (ScenesUtil.hasTransition(creator)) {\n ScenesUtil.fillTransition(creator);\n this.addXfadeInput();\n } else {\n this.addConcatInput();\n }\n\n this.addAudio();\n this.addOutputOptions();\n this.addCommandEvents();\n this.addOutput();\n this.command.run();\n }\n }", "function onClickManualPIDBtn() {\n $(\"#ConfigurePID_ContainerNewSetPoint\").show();\n $(\"#ConfigurePID_ContainerNewRampTarget\").hide();\n $(\"#ConfigurePID_ContainerNewOutput\").hide();\n\n writeCommand(\"manual\");\n \nfunction pausecomp(millis)\n {\n var date = new Date();\n var curDate = null;\n do { curDate = new Date(); }\n while(curDate-date < millis);\n}\npausecomp(500);\n\n writeCommand(\"manualPID\");\n}", "start() {\n this.createContext();\n }", "function makeId() {\n //create an id from praxis number, username and suffix\n //complete version\n vm.setId = praxis+''+vm.name+''+vm.ownId;\n console.log('Setting own id from '+vm.setId+' to '+vm.ownId);\n //send complete peer id to all clients\n socket.emit('update:pid', vm.setId);\n }", "started() {\r\n\r\n\t}", "function makeVideo(id) {\n var video = document.createElement('video')\n var source = document.createElement('source')\n\n video.width = '400'\n video.height = '200'\n video.controls = true\n\n source.src='./video/' + id +'.mp4'\n source.type='video/mp4'\n\n video.appendChild(source)\n\n return video\n}", "function startProcessing (vid, callback) {\n setInterval(function intervalCallback() {\n vid.read(function vidReadCallback(err, mat) {\n if (err) {\n console.error(\"Error:\", err);\n throw err;\n }\n detect(mat, callback);\n });\n }, 150);\n}", "static defaultStart (component) {\n store.commit('START_PROCESS', 'vk')\n component.loading = true\n component.result = []\n }", "function loadFirstVid(){\n\t\t\t\t \tplayer = new YT.Player('vframe', {\n\t\t\t\t\t\t\t videoId: videos[videoCounter].url, //'47dtFZ8CFo8',\n\t\t\t\t\t\t\t playerVars: { 'autoplay': 1, 'controls': 0 , 'autohide':1, 'showinfo':0, 'controls':1, 'iv_load_policy':3, 'disablekb':1, 'modestbranding':1, 'rel':0, 'theme':'light', 'color':'white'},\n\t\t\t\t\t\t\t events: {\n\t\t\t\t\t\t\t 'onReady': onPlayerReady,\n\t\t\t\t\t\t\t 'onStateChange': onPlayerStateChange\n\t\t\t\t\t\t\t\t }\n\t\t\t\t\t });\n\t\t\t\t }", "function initVideo() {\n video = document.getElementById(\"video\");\n video.addEventListener(\"canplaythrough\", startVideo, true);\n video.addEventListener(\"ended\", videoDone, true);\n video.src = \"vids/goat.mp4\";\n\n video.isReady = false;\n video.preload = \"auto\";\n}", "function videoStarter() {\r\n\r\n\t$('#stream-boy').vide({\r\n\t\tmp4:'video/streamboy-clip.mp4',\r\n\t\togv:'video/streamboy-clip.ogv',\r\n\t\twebm:'video/streamboy-clip.webm',\r\n\t\tposter:'img/space-poster.jpg',\r\n\t\t}, {\r\n\t\tloop: true,\r\n\t\tmuted: true,\r\n\t\tautoplay: true,\r\n\t\tposterType: \"jpg\",\r\n\t\tclassName: \"stream-boy\"\r\n\t});\r\n\r\n\t$('#space-video').vide({\r\n\t\tmp4:'video/space-planet-with-reverse50.mp4',\r\n\t\togv:'video/space-planet-with-reverse50.ogv',\r\n\t\twebm:'video/space-planet-with-reverse50.webm',\r\n\t\tposter:'img/space-poster.jpg',\r\n\t\t}, {\r\n\t\tloop: true,\r\n\t\tmuted: true,\r\n\t\tautoplay: true,\r\n\t\tposterType: \"jpg\",\r\n\t\tclassName: \"space-video\"\r\n\t});\r\n\r\n\t// Get instance of the plugin\r\n\tvar spaceVideo = $('#space-video').data('vide');\r\n\tvar spaceVideoObject = spaceVideo.getVideoObject();\r\n\r\n\thud.mousemove(function( event ) {\r\n\r\n\t\tvar pageCoords = \"( \" + event.pageX + \", \" + event.pageY + \" )\";\r\n\t\tvar hudPosition = hud.position();\r\n\r\n\t\t// Find the position of the cursor inside the \"HUD\" relative to the width of the window\r\n\t\t// Divide by 4 and round up to get a clean percentage\r\n\t\tvar innerHudPosition = Math.round( ( event.pageX - hudPosition.left + 200 ) / 4 );\r\n\r\n\t\t//console.log(\"Camera Position: \" + innerHudPosition + \"%\");\r\n\t\t//console.log(\"Video Time: \" + spaceVideoObject.currentTime );\r\n\r\n\t\t// Set the video frame position relative to innerHudPosition\r\n\t\tspaceVideoObject.currentTime = innerHudPosition / 2;\r\n\t\tspaceVideoObject.pause();\r\n\r\n\t});\r\n\r\n\thud.mouseover(function() {\r\n\t\tspace.addClass(\"seeking-state\");\r\n\t});\r\n\r\n\thud.mouseout(function() {\r\n\t\t// setTimeout(function() { spaceVideoObject.play(); }, 1000);\r\n\t\tspaceVideoObject.play();\r\n\t\tspace.removeClass(\"seeking-state\");\r\n\t});\r\n}", "function start(){\r\n ba_cnvs=document.createElement(\"canvas\");\r\n ba_ctx=ba_cnvs.getContext(\"2d\");\r\n ba_vid=document.createElement(\"video\");\r\n \r\n ba_vid.crossOrigin=\"Anonymous\";\r\n\r\n ba_vid.src=ba_url;\r\n \r\n // target element\r\n ba_targ=document.querySelector(\".js-calendar-graph-svg\");\r\n ba_targ.setAttribute(\"width\",grid_w*14); //14 and 13 are from svg (github follows this )\r\n ba_targ.setAttribute(\"height\",grid_h*13); \r\n ba_targ=ba_targ.children[0];\r\n window.removeEventListener(\"click\",start);\r\n \r\n document.querySelector(\".js-calendar-graph-svg\").innerHTML=createElement(grid_w,grid_h);\r\n //initialize the grid\r\n for(var y=0;y<grid_h;y++){\r\n el_arr[y]=[];\r\n for(var x=0;x<grid_w;x++){\r\n el_arr[y].push(getElemAt(x,y));\r\n }\r\n }\r\n \r\n \r\n ba_vid.oncanplaythrough=playBadApple;\r\n \r\n}", "function startPausePressed() {\n \n switch (hdxAV.status) {\n\n case hdxStates.AV_SELECTED:\n // if we have selected but not yet started an algorithm,\n // this is a start button\n hdxAV.setStatus(hdxStates.AV_RUNNING);\n if (hdxAV.delay == -1) {\n hdxAV.startPause.innerHTML = \"Next Step\";\n }\n else {\n hdxAV.startPause.innerHTML = \"Pause\";\n }\n\n hdxAV.algStat.innerHTML = \"Initializing\";\n\n\t// vertices and/or edges here? Update only if useV is specified\n\tif (hdxAV.currentAV.hasOwnProperty(\"useV\")) {\n initWaypointsAndConnections(hdxAV.currentAV.useV,\n\t\t\t\t\thdxAV.currentAV.useE,\n\t\t\t\t\tvisualSettings.undiscovered);\n\t}\n\n\t// remaining AV-specific preparation, after which the AV's\n\t// code property should be HTML for the pseudocode\n hdxAV.currentAV.prepToStart();\n\t\n // set pseudocode\n document.getElementById(\"pseudoText\").innerHTML = hdxAV.currentAV.code;\n \n // reset all execution counts\n hdxAV.execCounts = [];\n hdxAV.maxExecCount = 0;\n\n showHidePseudocode();\n hdxAVCP.showEntries();\n\n // get the simulation going, always start with the \"START\"\n // action, then do it\n \n addBreakpointListeners();\n resizePanels();\n hdxAVCP.hideEntries();\n newMapTileSelected();\n hdxAV.nextAction = \"START\";\n hdxAV.nextStep(hdxAV.currentAV);\n break;\n \n case hdxStates.AV_RUNNING:\n // if we are in a running algorithm, this is a pause button\n // the running algorithm will pause when its next\n // timer event fires \n hdxAV.setStatus(hdxStates.AV_PAUSED);\n if (hdxAV.delay == -1) {\n hdxAV.startPause.innerHTML = \"Next Step\";\n }\n else {\n hdxAV.startPause.innerHTML = \"Resume\";\n }\n break;\n \n case hdxStates.AV_PAUSED:\n\n // depending on whether we're stepping or not, button\n // will need different labels\n if (hdxAV.delay == -1) {\n hdxAV.startPause.innerHTML = \"Next Step\";\n }\n else {\n hdxAV.startPause.innerHTML = \"Pause\";\n }\n\n // in all cases, we set status to running and perform the next step\n hdxAV.setStatus(hdxStates.AV_RUNNING);\n hdxAV.nextStep(hdxAV.currentAV);\n break;\n\n default:\n alert(\"startPausePressed, unexpected status=\" + hdxAV.status);\n }\n}", "function start(){\n\tpickRandomFile();\n}", "function init() {\n\t// Load the video data and populate the array of all video IDs\n\t$.getJSON('vids.json', function(data) {\n\t\tfor (var i=0;i<data.vids.length;i++) {\n\t\t\tif(i%2==0) {\n\t\t\t\tvid_array[(i/2)+1] = data.vids[i];\n\t\t\t}\n\t\t}\n\t\tswitchToVideo(vid_array.length-1);\n\t\tswitchToPage(1);\n\t\tchangeNowPlaying(vid_array.length-1);\n\t\tpopulatePages();\n\t\t$('#page-1').addClass('current-page');\n\t\t$('#scriptless').remove();\t\t\n\t}); \n}", "async function startVideo() {\n //It is async because we need to AWAIT loading the files \n //The loadFromUrl method is locating the model data (shard file and json manifest) from the 'models folder')\n await faceapi.nets.tinyFaceDetector.loadFromUri(modelsPath),\n await faceapi.nets.faceLandmark68Net.loadFromUri(modelsPath),\n await faceapi.nets.faceRecognitionNet.loadFromUri(modelsPath),\n await faceapi.nets.faceExpressionNet.loadFromUri(modelsPath),\n //This requests the user to provide access to the camera \n navigator.mediaDevices\n .getUserMedia({\n video: true, \n })//Then a callback is invoked and the stream coming from our camera is directed towards the video element \n .then((stream) => (video.srcObject = stream))\n //Since you never will know if this might fail (it's a stream!) it is good practice to catch it \n .catch((err) => console.error(err));\n}", "function preload() {\n video = createCapture(VIDEO);\n \n}", "function startPrototype(){\n \n $(\"#welcome\").fadeOut(1500);\n setTimeout(function () {\n $(\"#main\").fadeIn(1500);\n startP5();\n }, 1000); \n}", "function create_video_element( caller_rtc_id, cls )\n{\n\ttrace(\"Creating a video for \" + rtc_name( caller_rtc_id ) );\n\t$(\"#video-box\").append(\"<div class='slot \" + cls + \"'><video rtc_id='\"+caller_rtc_id+\"' rtc_name='\"+rtc_name(caller_rtc_id)+\"'></video><div class='video-button'><span class='name'>\"+rtc_name(caller_rtc_id)+\"</span><span class='kickout'>Kickout</span></div></div>\");\n\t\n\t/**\n\t * \n\t * 이 콜백 함수는\n\t * \n\t * 내가 들어가 있는 방에\n\t * \n\t * 나를 포함한, 입장하하는 사용자 마다 호출된다.\n\t * \n\t * 이 함수는 callback_connect_success() 다음에 호출된다.\n\t */\n\tif ( typeof callback_create_video_element == 'function' ) callback_create_video_element( caller_rtc_id, cls );\n\treturn $(\"#video-box video[rtc_id='\"+caller_rtc_id+\"']\")[0];\n}", "function main() {\n\t\tstage = new createjs.Stage(canvasID);\n\t\tstage.enableMouseOver(10);\n\t\tstage.mouseMoveOutside = true;\n captionManager = new CaptionManager(stage);\n\n createjs.Ticker.setFPS(60);\n\t\tcreatejs.Ticker.addEventListener('tick', stage);\n\n\t\tsetGameMode(GAME_MODES.PREPARING);\n\t}", "start() {\n this.currentTaskType = \"teil-mathe\";\n this.v.setup();\n this.loadTask();\n }", "started() { }", "function createPOV(config) {\n\t //Pull the configurations out of the config object. Each configuration\n\t //is then merged with the default one via `assign`\n\t var cameraConfig = config.camera;\n\t var cursorConfig = config.cursor;\n\n\t //Create a container to hold the camera\n\t var cameraContainer = document.createElement('a-entity');\n\t //Move the camera slightly away from the origin so that the origin is in view\n\t //from the spawn location\n\t cameraContainer.setAttribute('position', { x: 0, y: 0, z: 4 });\n\n\t //Create the camera and add it to the container\n\t var camera = createCamera(cameraConfig);\n\t cameraContainer.appendChild(camera);\n\n\t //Create the cursor and attach it to the camera\n\t var cursor = createCursor(cursorConfig);\n\t camera.appendChild(cursor);\n\n\t return cameraContainer;\n\t}", "function newGameVideo() {\n //light up the island for the first time\n}", "function start() {\n console.log(\"start\");\n\n document.querySelector(\"#generate\").addEventListener(\"click\", generate);\n}", "function vidLoad() {\n\tvid.noLoop();\n}", "function startVideo(){\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n canvas.getContext('2d').\n drawImage(video, 0, 0, canvas.width, canvas.height);\n $scope.sendPicture();\n}", "function startPomo(pomoId) {\n let mainpage = document.getElementById(\"main-page\");\n let timerpage = document.getElementById(\"timer-page\");\n mainpage.style.display = \"none\";\n timerpage.style.display = \"\";\n setPomo(pomoId);\n setCurrentPomo(pomoId);\n let desc = document.getElementById(\"task\");\n desc.innerHTML = \"Current Task: \" + getPomoById(pomoId).taskName;\n startPomoTimer();\n previousState = JSON.parse(JSON.stringify(getPomoById(pomoId)));\n getPomoById(pomoId).actualPomos++;\n setStatus(pomoId, SESSION_STATUS.inprogress);\n}", "function loadNewVideo(vid){\n console.log('loadNewVideo:',vid);\n player.loadVideoById(vid);\n}", "started() {\n\n }", "started() {\n\n }", "started() {\n\n }", "showLocalVideo() {}", "function create(id, start) {\n let embed = `<iframe width=\"320\" height=\"180\" src=\"https://www.youtube-nocookie.com/embed/${id}?controls=0&amp;start=${start}\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>`\n let soundboard = document.getElementById(\"soundboard\");\n let container = document.createElement(\"span\");\n container.innerHTML = embed;\n soundboard.appendChild(container);\n}", "function create() {\n _this.background = document.createElement('div');\n _this.background.classList.add('video-modal-background', 'is-hidden');\n\n _this.player = document.createElement('div');\n _this.player.classList.add('video-modal-player', 'is-hidden');\n\n _this.close = document.createElement('div');\n _this.close.classList.add('video-modal-close');\n _this.player.appendChild(_this.close);\n\n _this.iframe = document.createElement('iframe');\n _this.iframe.setAttribute('frameborder', '0');\n _this.iframe.setAttribute('width', '100%');\n _this.iframe.setAttribute('height', '100%');\n _this.iframe.setAttribute('allowfullscreen', true);\n _this.iframe.setAttribute('src', _this.embedURL);\n _this.player.appendChild(_this.iframe)\n\n document.body.appendChild(_this.background)\n document.body.appendChild(_this.player)\n }", "started() {\n\n\t}", "started() {\n\n\t}", "started() {\n\n\t}", "started() {\n\n\t}", "started() {\n\n\t}", "started() {\n\n\t}", "started() {\n\n\t}", "started() {\n\n\t}", "function piloteVideo() {\r\n\t\tif (roi.paused) {\r\n\t\t\troi.play();\r\n \r\n\t\t} else {\r\n\t\t\troi.pause();}\r\n }", "function uiStart()\n{\n console.log(\"[start]\");\n uiSetState(UI_STARTING);\n showSpinner(uiLocalVideo, uiRemoteVideo);\n\n sendMessage({\n id: 'START',\n });\n}", "function create() {\n if (gameState === \"Menu\") {\n menuGroupSetup();\n } else if (gameState === \"Playing\") {\n game.world.removeAll();\n stageGroupSetup();\n entityGroupSetup();\n guiGroupSetup();\n game.sound.setDecodedCallback([monsterLaugh, mainTheme], playIntro);\n } else if (gameState === \"GameOver\") {\n gameOverGroupSetup();\n } else if (gameState === \"Win\") {\n gameWinGroupSetup();\n }\n\n game.input.mouse.capture = true;\n cursors = game.input.keyboard.createCursorKeys();\n }", "function createPlayer() {\n}", "started () {}", "function createParticle(m, v, x, y) {\n\tvar p = new Particle(m, v, x, y);\n\tparticles[particles.length] = p;\n\n\t$('#num-particles').html('<b>Particles: </b>' + particles.length);\n}", "function startNewGame() {\n if (!document.fullscreenElement) { p.wrapper.requestFullscreen(); }\n p.loadingWidth = 0;\n p.matrix = [];\n p.ready = false;\n p.timeOfStart = 0;\n p.timeOfEnd = 0;\n clearTimeout(p.timeOut1);\n clearTimeout(p.timeOut2);\n\n createMatrix();\n if (p.startGame) { startTimer(); }\n }" ]
[ "0.61306745", "0.5994796", "0.59340876", "0.59247714", "0.58977413", "0.58869493", "0.5836164", "0.5828873", "0.5799598", "0.57475215", "0.5691742", "0.56917155", "0.5624253", "0.5618819", "0.56136113", "0.55715996", "0.55389524", "0.55300015", "0.5529355", "0.5518904", "0.5513406", "0.54725194", "0.5461745", "0.545085", "0.5412514", "0.5409036", "0.5397412", "0.5397412", "0.5372684", "0.5364771", "0.53563976", "0.5356259", "0.5349273", "0.5346902", "0.53406423", "0.53355986", "0.5313192", "0.53102165", "0.5302191", "0.52849114", "0.5281874", "0.5278691", "0.52731055", "0.52731055", "0.52731055", "0.52731055", "0.52731055", "0.52731055", "0.52724826", "0.52687806", "0.5267485", "0.5267422", "0.5257979", "0.5256584", "0.5251787", "0.5245799", "0.5244776", "0.52357244", "0.52326536", "0.52257925", "0.5225242", "0.52210474", "0.52206236", "0.5218903", "0.5211793", "0.52024716", "0.5198534", "0.5196417", "0.5192005", "0.5188304", "0.5187595", "0.5176089", "0.51757824", "0.5175201", "0.517497", "0.51664656", "0.51575804", "0.51290345", "0.51286006", "0.51267886", "0.51258725", "0.51258725", "0.51258725", "0.512065", "0.51184255", "0.5117692", "0.5102294", "0.5102294", "0.5102294", "0.5102294", "0.5102294", "0.5102294", "0.5102294", "0.5102294", "0.5094176", "0.5084608", "0.50786996", "0.5078388", "0.5077066", "0.507041", "0.5069172" ]
0.0
-1
Random Num Generator for pvid
function randomNum() { var randomNumber = Math.round(999999999 * Math.random()); return randomNumber; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function randomNumGen() {\n return Math.floor(Math.random() * 102) + 19;\n }", "function getRandomNumber () {}", "function rand() {\r\n if(!gnt--) {\r\n prng(); gnt = 255;\r\n }\r\n return r[gnt];\r\n }", "random(): number {\n let u: number = (prng.random(): any);\n return this._random(u);\n }", "function generate_rndm_nums()\n{\n\trndmslot = Math.floor(Math.random()*101) % 5;\n\trndmnum = Math.floor(Math.random()*11);\n}", "function R(n) { return Math.floor(n*Math.random()); }", "function randomRpsInt() {\n return Math.floor(Math.random() *3);\n}", "function generateNumber() {\n return Math.floor(Math.random() * 256);\n }", "next_rand() {\n this.jitter_pos *= 10;\n if (this.jitter_pos > 10000000000)\n this.jitter_pos = 10;\n return (this.jitter * this.jitter_pos) % 1;\n }", "function randomNumberGenerator(){\n return Math.floor(Math.random()*1000);\n }", "function generateNum() {\n\treturn Math.floor(Math.random()*100)\n}", "next_rand() {\n\t\tthis.jitter_pos *= 10;\n\t\tif (this.jitter_pos > 10000000000)\n\t\t\tthis.jitter_pos = 10;\n\t\treturn (this.jitter * this.jitter_pos) % 1;\n\t}", "function randToRpsInt() {\n return Math.floor(Math.random() * 3);\n}", "function randToRpsInt() {\n return Math.floor(Math.random() * 3);\n}", "function getRandomNum () {\n return Math.floor(Math.random() * 17) + 16\n }", "function genNum(){\n\tvar ranNum = []\n\tfor(i = 0; i < 10; i++){\n\t\tranNum.push(Math.round(Math.random() *100));\n\t}\n\tretun ranNum;\n}", "function genNum(){\n\trandomNum = Math.floor(Math.random() * Math.floor(numberMax + numberMin)) \n}", "function randomNum(){\n\tvar random = Math.floor(Math.random() * 4);\n\ttrueTag = random;\n\treturn random;}", "function rnd() \n{\n\t\t\n rnd.seed = (rnd.seed*9301+49297) % 233280;\n return rnd.seed/(233280.0);\n}", "function ranToRpsInt(){\n return Math.floor(Math.random()*3);\n \n}", "function random() {\n\t\tseed = Math.sin(seed) * 10000;\n\t\treturn seed - Math.floor(seed);\n\t}", "function random () {\n\t\n\tseed = 312541332155 * (4365216455 + seed) % 7654754253243312;\n\t\n\treturn 0.0000001 * (seed % 10000000);\n\t\n}", "function randomNumberGenerator() {\n\treturn (Math.floor(((Math.random() * 9) + 1)));\n}", "function randomPkmnNum() {\n for (var i=0; i<4; i++) {\n var num = (Math.floor(Math.random() *11) +1);\n imgValue.push(num);\n }\n console.log (imgValue);\n }", "function gen_random(){\r\n\treturn 0.3\r\n}", "function randomNumbGen100 () \n {\n return Math.floor(Math.random() * 100 + 1);\n }", "function rng () {\n return random()\n }", "function rng() {\n return random();\n }", "function rng() {\n return random();\n }", "function rng() {\n return random();\n }", "function rng() {\n return random();\n }", "function genNum() {\n // 198 = 99 - (-99)\n return Math.floor((Math.random() * 198) - 99);\n}", "function generateNumber() {\n\t\treturn Math.floor(Math.random() * tipsArray.length);\n\t}", "function randomNumGen(num){\n return Math.floor(Math.random() * num );\n}", "function getRandomNum() {\n\treturn Math.floor(Math.random() * -999 + 2250);\n}", "function secretNumberGenerator() {\n secretNumber = (Math.floor(Math.random()*100));\n console.log(\"Secret number = \" + secretNumber);\n }", "function randomNumber() {\r\n return Math.random;\r\n}", "function gerarProbabilidade() {\r\n return Math.random();\r\n}", "function nextSeq(){\r\n return Math.floor(Math.random() * 4)\r\n}", "function generateRandomNumber(){\n return Math.floor((Math.random()*100)+1);\n }", "function randomNum(){\n return Math.floor(Math.random() * 256)\n}", "function r(){return Math.random().toString().slice(2,7)}", "function randomNr() {\n return Math.floor(Math.random() * 9999);\n}", "function generateNum() {\n return Math.round(Math.random() * 100);\n}", "function random_nums() {\n\t\t\tvar max = all_coords.length + 1;\n\t\t\treturn Math.floor(Math.random() * max) \n\t\t}", "function generateNum() {\n goalNumber = Math.floor((Math.random() * 120) + 19);\n }", "function randomNumGen(){\n\t\tvar randomNumber = (Math.floor(Math.random() * 4) + 1).toString();\n\t\tcolorOrder.push(randomNumber);\n\t}", "function randomNumber() {\n return (1 + Math.round(Math.random() * 4));\n}", "function randomNumberGenerator() {\n return Math.floor(Math.random() * 102) + 19;\n}", "generateRandomNumber() {\n return this.generateRandom(0, 10);\n }", "function randomNumGen(){\n return Math.floor(Math.random() * 100 + 1);\n}", "function genNmb(){\n\tscrtNmb = Math.floor(Math.random()*100)+1;//create a secret number by randomizing each time the game starts or restarts\n}", "function randomNumber(){\n return (Math.round(1 * Math.random()) + 1);\n }", "function generateVal() {\n return Math.floor((Math.random() * 100) + 1);\n }", "function generateRandomNumb() {\n const oprand1 = Math.floor(Math.random() * 10);\n const oprand2 = Math.floor(Math.random() * 10);\n return [oprand1,oprand2];\n}", "function generateRandomPokemon(){\n const MAX = 809;\n const MIN = 1;\n const id = Math.floor(Math.random() * (MAX - MIN) + MIN)\n return id;\n}", "function generateNumber() {\n return _.shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9]).slice(0, 4);\n}", "rNum() {\n return Math.floor(Math.random() * (61) + 15) / 100;\n }", "function randNumber () {\n\treturn Math.floor(Math.random() * 10);\n}", "function randomNumber() {\n return (Math.round(Math.random()*100)+1);\n }", "function Random_no() {\n return Math.floor((Math.random() * 4)+1);\n}", "function generateNumber () {\n answer = Math.floor(Math.random()*(10));\n numberInGrid = puzzles[answer];\n }", "function generateTarget(num){\r\n return Math.floor(Math.random() * 10);\r\n}", "function generateTarget(num){\r\n return Math.floor(Math.random() * 10);\r\n}", "function randomNumber() {\n return Math.floor(Math.random() * 256);\n}", "randomLikeGenerator() {\n return Math.floor(Math.random() * 10) + 1\n }", "function getRandomNr() {\n return Math.floor(Math.random() * 10) + 300\n}", "function getRandomNumber () {\n return Math.floor(Math.random() * 256);\n}", "randomNumber() {\n\t\treturn random([1, 2, 3, 4, 5, 6]);\n\t}", "function randomNum(){\n let pcNum = Math.floor(Math.random() * 5) + 1;\n return pcNum;\n}", "function random() {\n\t\tr = (r + 0.1) % 1\n\t\treturn r\n\t}", "function numerorandom () {\r\n return Math.floor(Math.random() * 5) + 1;\r\n}", "function generateRandomNumber() {\n return Math.floor(Math.random() * 255)\n}", "function generateRandomNumber(num){\r\n return Math.floor(Math.random() * num)\r\n}", "function generateTarget() {\n const secretNum = Math.floor(Math.random() * 10);\n return secretNum;\n}", "function randN(n){\r\n\t\treturn Math.random()*n;\r\n\t}", "gen_rnd()\n {\n var a, x;\n\n x = (this.seeda << 1) & 0xff;\n a = x + this.seedc;\n\n if (this.seeda > 0x7f)\n a++;\n\n this.seeda = a & 0xff;\n this.seedc = x;\n\n a = a / 0x100; // a = any carry left from above\n x = this.seedb;\n a = (a + x + this.seedd) & 0xff;\n\n this.seedb = a;\n this.seedd = x;\n\n return a;\n }", "function randomNumberGenerator(){\n return Math.floor(Math.random()*1000);\n}", "function generateRandomNum(n) {\n return Math.floor(Math.random() * n)\n}", "rando() {\n randomNum = Math.floor(Math.random() * 20);\n }", "getRandom(n) {\n return Math.floor(Math.random() * n)\n }", "function randomNumber(){\r\n return Math.random();\r\n}", "function genRanNum(min,max){\r\n return Math.floor(Math.random() * (max - min)) + min;\r\n}", "function numberGenerator() {\n var numero = Math.floor(Math.random() * numeroTotaleGiocate) + 1;\n return numero;\n}", "function prob() {\n\t\treturn Math.ceil(Math.random()*100)\n\t}", "function getIdPublicacion(){\n\treturn Math.round(Math.random() * 20) + 1;\n}", "randomNum() {\n return Math.floor(Math.random() * 600);\n }", "_random() {\n return Math.rnd();\n }", "function generateRandNum()\n{\n return Math.ceil(Math.random() * 10)\n}", "function randomNumber() {\n rndNumber = Math.floor((Math.random()*100)+1);\n }", "function randomNum(){\n return Math.floor(Math.random() * 14);\n}", "function getRandomValue() {\n return Math.random() * 10 >= 8 ? 4:2;\n }", "function randomNums(){\n \n return (Math.random()* 1000);\n }", "function random() {\n var x = Math.sin(seed++) * 10000;\n return x - Math.floor(x);\n}", "function rng() {\n return random();\n } // updates generator with a new instance of a seeded pseudo random number generator", "function generateNumber() {\n result = Math.floor(Math.random() * 4) + 1\n return result\n}", "function getRandomNumber(num) {\n return Math.floor(Math.random() * num);\n }", "function randn() {\n var u = 0, v = 0;\n while(u === 0) u = Math.random(); //Converting [0,1) to (0,1)\n while(v === 0) v = Math.random();\n return Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);\n}", "function randomNumber() {\n pick = Math.floor(Math.random() * parkList.length);\n}", "function randomNum() {\r\n return Math.floor(Math.random() * 20 + 1);\r\n}" ]
[ "0.72758335", "0.7219318", "0.7172872", "0.71435195", "0.7057339", "0.7038372", "0.70312816", "0.6980145", "0.6977365", "0.69728273", "0.69627815", "0.69466364", "0.69245386", "0.69245386", "0.6923437", "0.6915384", "0.69142437", "0.69129294", "0.6910269", "0.69099253", "0.6909814", "0.6900113", "0.6899952", "0.6883519", "0.6881534", "0.6874327", "0.6860153", "0.6843191", "0.6843191", "0.6837662", "0.6837662", "0.683079", "0.6815709", "0.6814742", "0.68058825", "0.6805767", "0.68041885", "0.6802859", "0.68016267", "0.67882407", "0.6781129", "0.6780181", "0.6772982", "0.67631936", "0.6760868", "0.6755653", "0.6742837", "0.673997", "0.67378706", "0.6734194", "0.6733316", "0.6726876", "0.67233676", "0.6723308", "0.67220265", "0.6718654", "0.6717923", "0.6716902", "0.6706103", "0.6690122", "0.6685556", "0.66764545", "0.6676391", "0.6676391", "0.66697437", "0.6664127", "0.6658413", "0.66525686", "0.6652161", "0.6650416", "0.6646126", "0.66434157", "0.6642374", "0.6640355", "0.6638564", "0.6636981", "0.6634144", "0.6630999", "0.6620462", "0.6617389", "0.66103435", "0.66087466", "0.6607395", "0.66068524", "0.66064507", "0.6603204", "0.6599745", "0.65937775", "0.65937394", "0.6593023", "0.6592647", "0.65849066", "0.6582536", "0.65818226", "0.6581596", "0.65815485", "0.65798765", "0.6578144", "0.65773666", "0.6576561" ]
0.6594815
87
Remove first and last character
function removeChar(str) { //You got this! let arr = str.split('') arr.pop() arr.shift() let s = arr.join('') return s }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function removeChar(str){\n var str = str.split('');\n var removedLastChar = str.pop();\n var removedFirstChar = str.shift();\n var str = str.join(''); \n return str;\n}", "function removeFirstAndLast (str) {\n let value = str.slice(1, str.length - 1);\n return value;\n}", "function removeLastChar(text) {\n\n var textArray = text.split(\"\");\n textArray.pop();\n var newText = textArray.join(\"\");\n\n return newText;\n\n\n}", "function removeChar(str){\n str1 = str.split('');\n str1.shift();\n str1.pop();\n return str1.join('');\n \n }", "function keepFirst(s) {\n\treturn s.substring(0, 2);\n}", "function delLastChar( s ){\n\treturn delLast(s,1);\n}", "function removeChar(str) {\n\t// convert the str into array\n\t// remove the portion of the array starting at 1 and excluding the last element\n\t// return it\n\treturn str.split('').slice(1, -1).join('');\n}", "function removeChar(str){\n return str.substring(1,str.length -1);\n \n }", "function stripLastChar(myString) {\n return myString.substring(0, myString.length - 1).trim();\n }", "function removeChar(str){\n return str.slice(1, str.length-1)\n}", "function removeChar(str) {\n\n\n return str.slice(1, str.length - 1)\n\n}", "function removeChar(str){\n return str.substring(1, str.length-1)\n }", "function removeChar(str) {\n return str.slice(1, -1);\n}", "function removeChar(str) {\n return str.slice(1, -1);\n}", "function removeChar(str) {\n return str.slice(1, -1);\n}", "function removeChar(str) {\n\treturn str.slice(1, -1);\n}", "function removeChar(test){\r\n let newChars = test.slice(1,-1);\r\n return newChars;\r\n }", "function keepFirst(str) {\n return str.substring(0, 2);\n}", "function RemoveRougeChar(convertString, separa){\r\n\tif(convertString.substring(0,1) == separa){\r\n\t\treturn convertString.substring(1, convertString.length) \r\n\t\t}\r\n\treturn convertString;\r\n}", "function keepFirst(str)\n{ \n const length = str.length;\n return str.substring(0,2);\n}", "function removeChar(str) {\n let result = str.split(\"\");\n result.pop();\n result.shift();\n return result.join(\"\");\n}", "function removeChar(str) {\n return str.slice(1, str.length - 1);\n}", "function keepFirst(aString){\n return aString[0] + aString[1];\n}", "function removeChar(str){\n //You got this!\n var ultima = str.length - 1;\n var corte = str.substring(1, ultima);\n return corte;\n}", "function removeFirstLast(str){\n if(str.length < 3){\n return str;\n }else{\n let newstr = str.slice(1, str.length - 1);\n console.log(newstr);\n // console.log(str[str.length - 1]);\n }\n}", "function removeChar(value, char) {\n if (!value.length || !char.length) {\n return '';\n }\n\n if (char.includes(value[0])) {\n return '' + removeChar(value.slice(1), char);\n }\n\n return value[0] + removeChar(value.slice(1), char);\n}", "function splitAndLeave(str, char, last) {\n char = char || \"\\/\";\n\n char = new RegExp(char, 'g');\n\n var split = str.split(char);\n var i = last ? split.length - 1 : 0;\n return split[i];//.slice(0, i).join(char) + char;\n\n}", "function undoubleEnding (str) {\n if (str.substr(-2) === 'kk' || str.substr(-2) === 'tt' || str.substr(-2) === 'dd') {\n return str.substr(0, str.length - 1)\n } else {\n return str\n }\n}", "function keepFirst(string)\n{\n return string.substring(0, 2);\n}", "function keepLast(str)\n{\n\treturn str.slice(str.length - 2)\n}", "function removeLeadingAndTrailingWhitespace(string: string){\n\t\t\t\t\t\n\t\t\t\t\t//Remove the first character of whitespace, if it's there\n\t\t\t\t\tif (string.indexOf(' ') === 0){\n\t\t\t\t\t\tstring = string.slice(1);\n\t\t\t\t\t}\n\n\t\t\t\t\t//Remove the last character of whitespace, if it's there\n\t\t\t\t\tif (string.lastIndexOf(' ') === string.length -1){\n\t\t\t\t\t\tstring = string.slice(0, -1);\n\t\t\t\t\t}\n\t\t\t\t\treturn string;\n\t\t\t\t}", "function removeEnds(string) {\n let arr = string.split('')\n let remove = ''\n if (arr.length < 3) {\n return ''\n } else {\n newArr = arr.slice(1, -1)\n remove = newArr.join('')\n }\n return remove;\n}", "function addFirstAndLastLetter(str)\n{\n first = str.substring(0,1);\n alert(first + str + first);\n}", "function concatLastFirst(capitalFirstLast){\n capitalLastFirst = capitalFirstLast.charAt(1) + capitalFirstLast.charAt(0);\n alert(capitalLastFirst);\n}", "function firstAndLast(word)\n{\n var firstLastLetter = word.charAt(0)+word.charAt(word.length-1);\n return firstLastLetter.toUpperCase();\n}", "function keepFirst(str) {\n return str.split(str[2])[0]\n}", "function removeChar(str) {\n return (newStr = str.slice(1, -1));\n}", "function undoOneLetter(){\n if(calculation.length>0){\n calculation = calculation.slice(0, -1) //delete last char\n }\n}", "function removeFirst(x, y){\n return x.toString().replace(y, \"\");\n }", "function removeChar(str){\n //You got this!\n return str.substr(1, str.length - 2);\n}", "function removeChar(str, char) {\n return str.split(char).join(\"\");\n }", "function deleteFirstAndLastWhiteSpace(str){\n\tvar rv=str;\t\n\tvar imax=rv.length;\n\tfor(var i=0; i<imax; ++i){\n\t\tvar nochange1=true;\n\t\tvar nochange2=true;\n\t\t\n\t\t//delete all WSP at the end of each unfolded header field value\t\t\n\t\tif(rv[rv.length-1]==' ' || rv[rv.length-1]=='\\t'){\n\t\t\trv = rv.slice(0,rv.length-1);\t\t\t\n\t\t\tnochange1=false;\n\t\t}\n\t\t\n\t\t//delete any WSP remaining before and after the colon separating field name form value\n\t\tif(rv[0]==' ' || rv[0]=='\\t'){\n\t\t\trv = rv.slice(1,rv.length);\n\t\t\tnochange2=false;\n\t\t}\n\t\t\n\t\tif(nochange1==true && nochange2==true) break;\t\t\n\t}\t\n\treturn rv;\n}", "function stripTail(str){var arr=str.match(/(.+)(-[^-]+)$/);var st='';if(arr&&arr.length===3){st=arr[1];}return st;}", "function stripTail(str){var arr=str.match(/(.+)(-[^-]+)$/);var st='';if(arr&&arr.length===3){st=arr[1];}return st;}", "function trimOut(inp)\r\n{\r\n\tlet temp=inp.substring(inp.lastIndexOf(\"/\")+1,inp.length);\r\n\treturn temp.trim();\r\n}", "function trimStart (chr, string) {\n let output = string\n while (output[0] === chr) {\n output = output.splice(0, 1)\n }\n return output\n}", "function removeO(string){\nreturn string.replace(/[o]/g,'');\n}", "function firstToLast(str,c){\n if(str.lastIndexOf(c)===-1) return -1\n return str.lastIndexOf(c)-str.indexOf(c);\n}", "function trim(cadena)\r\n{\r\n\tfor(i=0; i<cadena.length; )\r\n\t{\r\n\t\tif(cadena.charAt(i)==\" \")\r\n\t\t\tcadena=cadena.substring(i+1, cadena.length);\r\n\t\telse\r\n\t\t\tbreak;\r\n\t}\r\n\r\n\tfor(i=cadena.length-1; i>=0; i=cadena.length-1)\r\n\t{\r\n\t\tif(cadena.charAt(i)==\" \")\r\n\t\t\tcadena=cadena.substring(0,i);\r\n\t\telse\r\n\t\t\tbreak;\r\n\t}\r\n\t\r\n\treturn cadena;\r\n}", "static trimFilename(str) {\n let lastIndex;\n for (let i = 0; i < str.length; ++i) {\n if (str[i] == String.fromCharCode(0)) {\n lastIndex = i;\n break;\n }\n }\n return str.slice(0, lastIndex);\n }", "function cutFirst(a){\n return a.substr(2)\n}", "function changeFirstToLastLetter(str) \n {\n if (str.length <= 1)\n {\n return str;\n }\n pos = str.substring(1, str.length - 1);\n alert((str.charAt(str.length - 1)) + pos + str.charAt(0));\n}", "function cleanUpString(str) {\n return str.replace(/\\(.+\\)/, '').trim();\n }", "function FFString_trimRight( value ){\n\tif(value==null || value==\"\") return \"\";\n\n\tvar length = value.length;\n\n\tvar i;\n\tfor(i=length-1;i>=0;i--){\n\t\tif(value.charAt(i) != \" \") break;\t\t\t\n\t}\n\treturn value.substring(0,i+1);\t\n}", "function righttrim(value)\n{\n\twhile( value.length != 0 )\n\t{\n\t\tmychar=value.substring(value.length-1);\n\t\tif( mychar == \"\\u0020\" )\n\t\t{\n\t\t\tvalue=value.substr(0,value.length-1);\n\t\t}\n\t\telse\n\t\t\tbreak;\n\t\t\n\t}\n\treturn value;\n}", "function firstToLast(str,c){\n if(str.indexOf(c) === -1) return -1;\n return str.lastIndexOf(c) - str.indexOf(c);\n}", "function removeMiddleName(string) {\n\n let arrayString = string.split(\" \");\n let first = arrayString[0];\n let last = arrayString[arrayString.length-1];\n let firstLast = first +\" \" + last;\n \n if (arrayString.length === 1){\n return first;\n }\n else{\n return firstLast;\n }\n \n }", "function removeLast(x, y){\n return replaceLast(x, y, \"\");\n }", "function backspace(str){\n\t\t//prevents NaN input\n\t\tif(str === '0') return '0';\n\t\treturn str.substring(0, str.length-1);;\n\t}", "function removePalabrasCompuestas(texto) {\r\r\n\r\r\n for (i = 0; i < texto.length; i++) {\r\r\n if (texto.charAt(i) == \" \") {\r\r\n return texto.substr(0, i);\r\r\n }\r\r\n }\r\r\n\r\r\n return texto;\r\r\n}", "function cutString(S){\n let newS;\n newS=S.substring(1,S.length-1);\n return newS;\n}", "function LastChar (stringname){\n\treturn stringname.slice(-1);\n}", "function deleteLast(numStr) {\n\n if (numStr.length == 1) {\n return \"\";\n } else {\n numStr = numStr.slice(0, -1);\n return numStr;\n }\n }", "function cutFirst(str){\n return str.substr(2);\n}", "function trim(str)\r\n{\r\n\r\nwhile(''+str.charAt(0)==' ') str=str.substring(1,str.length);\r\n\r\nwhile(''+str.charAt(str.length-1)==' ') str=str.substring(0,str.length-1);\r\n\r\nreturn str;\r\n}", "function firstToLast1(str,c){\n return (str.indexOf(c) < 0) ? -1 : str.lastIndexOf(c) - str.indexOf(c);\n}", "function cutFirst(str){\n return str.slice(2)\n }", "function front_back(str)\n{\n frist = str.substring(0,1);\n return frist+str+frist;\n}", "clearLastChar() {\r\n const { displayValue } = this.state\r\n\r\n this.setState({\r\n displayValue: displayValue.substring(0, displayValue.length - 1) || ''\r\n })\r\n }", "function removeFirstCharFromString(pString) {\n if (pString) {\n pString = pString.substr(1, pString.length - 1);\n return pString;\n }\n return \"\";\n}", "function cutFirst(sentence){\n sentence = sentence.substring(2);\n return sentence\n }", "function removeChar(str) {\n //You got this!\n let newStr = \"\";\n for (let i = 1; i < str.length - 1; i++) {\n newStr += str[i];\n }\n return newStr;\n}", "function remove(s){\n return s.replace(/!+$/, '');\n}", "function stripSpecialChars(original) {\n return original.replace(/[^\\w]/gi, '');\n}", "function tw(val)\n{\n return val.replace(/ /g, \"\");\n}", "function lefttrim(value)\n{\n\twhile( value.length != 0 )\n\t{\n\t\tmychar=value.substring(0,1);\n\t\tif( mychar == \"\\u0020\" )\n\t\t{\n\t\t\tvalue=value.substr(1);\n\t\t}\n\t\telse\n\t\t\tbreak;\n\t\t\n\t}\n\treturn value;\n}", "function removeChars(str, char) {\n let newStr = ' ';\n let last = 0;\n for (let i = 0; i <= str.length; i++) {\n if (char.includes(str[i]) || i === str.length) {\n newStr += str.slice(last, i);\n last = i + 1;\n }\n }\n return newStr;\n}", "function rtrim()\n{\n return this.replace( /\\s+$/g,'');\n}", "function righttrim(strSrc){\r\n\tvar len = strSrc.length;\r\n\tif(typeof(strSrc)!=\"string\")\r\n\t\treturn strSrc;\r\n\tfor (var i=len-1; i>=0; i--)\r\n\t\tif(strSrc.charAt(i)!=\" \")\r\n\t\t\tbreak;\r\n\tstrSrc=strSrc.substring(0,i+1);\r\n\treturn strSrc;\r\n}", "function trimRight(text, ending) {\n while (text.length >= ending.length && text.lastIndexOf(ending) === text.length - ending.length) {\n text = text.substring(0, text.length - ending.length);\n }\n \n return text;\n }", "_trim(s) { return (s.charAt(0) == '#') ? s.substring(1, 7) : s }", "function removeChar(str) {\n let s = '';\n for (let i = 1; i < str.length - 1; i++) {\n s = s + str[i];\n }\n return s;\n}", "function fixStart(str)\n{\n //var firstChar = str.slice(0,1);\n var str1 = str.split(\"\");\n // var re = new RegExp(/(?!^)${firstChar}/,\"g\");\n // var str1 = str.replace(re,'*');\n for (var i = 1; i < str.length; i+=1)\n {\n if (str[i] === str[0])\n {\n str1[i] = '*';\n }\n }\n str1 = str1.join(\"\");\n console.log(str,\" is replaced : \",str1);\n return str1;\n}", "static removePrefix(value) {\n if (value.includes(InitialPrefix) && value.includes(EndPrefix)) {\n return value\n .toString()\n .replace(InitialPrefix, \"\")\n .replace(EndPrefix, \"\");\n }\n return value;\n }", "function rtrim(para) {\n\twhile(para.substring(para.length-1, 1) == ' ') {\n\t\tpara = para.substring(0, para.length-1);\n\t}\n\n\treturn para;\n}", "function rtrim(str, char=\" \") {\r\n // If both the charcter and string are not\r\n // string, then no need to proceed.\r\n if (typeof(str) != 'string' || typeof(char) != 'string') {\r\n return;\r\n }\r\n var pattern = new RegExp(char + '+$', 'g');\r\n return str.replace(pattern, '');\r\n }", "function reverseCharacters(x){\n return x.toString().split(\"\").reverse().join(\"\");\n }", "function takeString1(mystring)\n{ \n //start is second last char\n \n return mystring.substring(mystring.length-2);\n}", "function fixStart (str) {\n\tvar firstLetter = str.charAt(0);\n\tvar remainder = str.slice(1, str.length);\n\tvar replaced = remainder.replace(RegExp(firstLetter, 'g'), '*');\n\tvar result = firstLetter.concat(replaced);\n\tdocument.write(result + '<br>');\n}", "function scrub(txt){\r\n return txt.replace(/[^a-zA-Z ]/g, \"\")\r\n }", "function unformat(x)\n\t\t{\n\t\t\tvar x = x.split('/').reverse().join('-');\n\t\t\treturn x;\n\t\t}", "function trimR(s) {\n if (s[s.length - 1] === \"R\" && s[s.length - 2] === \"/\") {\n s = s.substring(0, s.length - 2);\n }\n if (s[s.length - 1] === \"/\") {\n s = s.substring(0, s.length - 1);\n }\n return s;\n}", "function removeSpecialCharacters (title) {\n title = title.replace(/,/g, '')\n title = title.replace(/:/g, '')\n title = title.split('(').join('')\n title = title.split(')').join('')\n title = title.split('!').join('')\n title = title.split('?').join('')\n title = title.split('.').join('')\n return title;\n }", "function contamination1(text, char){\n if(char.length===0) return '';\n return text.replace(/./g,char);\n}", "function rtrim(s) {\n return s.replace(/\\s+$/, '');\n}", "function stringStrip(sickPersonName:String) {\n\t\tvar temp = sickPersonName.Split(\":\"[0]);\n\t\tsickPersonDisease = temp[0];\n}", "function untrail (str) {\n const sep = require('path').sep\n\n if (str.substr(str.length - 1) === sep) {\n return str.substr(0, str.length - 1)\n } else {\n return str\n }\n}", "function noSpace(x){\n return x.split(\"\").filter(el => {return el!==\" \"}).join(\"\")\n }", "function first_last(str1)\n{\n if(str1.length <= 1)\n {\n return str1;\n }\n else\n {\n mid_char = str1.substring(1,str1.length -1)\n return(str1.charAt(str1.length-1) + mid_char + str1.charAt(0));\n }\n}", "function StringRTrim(str, symbol){\n while(str.endsWith(symbol)) str = str.substr(0, str.length - 1);\n return str\n}" ]
[ "0.72691405", "0.6929681", "0.68435603", "0.68313366", "0.68193316", "0.67914224", "0.6725234", "0.6719821", "0.66925335", "0.6624974", "0.66161114", "0.65817165", "0.6571325", "0.6555372", "0.6555372", "0.6551751", "0.65439194", "0.65239716", "0.6498269", "0.643453", "0.64221483", "0.6403255", "0.63657266", "0.6357656", "0.63414955", "0.63158035", "0.6314517", "0.62880623", "0.62775433", "0.6271499", "0.6264716", "0.6261758", "0.62583035", "0.6227049", "0.61961526", "0.6183261", "0.6170053", "0.615123", "0.6141046", "0.61327404", "0.6129927", "0.61199075", "0.6094812", "0.6094812", "0.6090646", "0.6056142", "0.6036499", "0.6033994", "0.6017826", "0.6015309", "0.60129714", "0.6012392", "0.59901994", "0.59807277", "0.59741807", "0.597346", "0.595846", "0.59482104", "0.5946889", "0.5940149", "0.5938626", "0.59265023", "0.5924692", "0.5923092", "0.5922501", "0.5902598", "0.5899662", "0.5897076", "0.5895436", "0.5889091", "0.58741295", "0.5871722", "0.5860293", "0.58589846", "0.5853704", "0.5849635", "0.5842767", "0.584216", "0.5839377", "0.58274394", "0.5826536", "0.5825758", "0.5823727", "0.5814734", "0.5808753", "0.5803786", "0.5802013", "0.5788261", "0.57845736", "0.5783041", "0.57695556", "0.5762238", "0.5756412", "0.5753771", "0.5750081", "0.5748766", "0.5748315", "0.57435215", "0.57428485", "0.574034" ]
0.6428404
20
Add all index of an array
function positiveSum(arr) { let sum = 0 arr.map( num => num > 0 ? sum += num : null) return sum }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function addAllToArray(items,arr){for(var i=0;i<items.length;i++){arr.push(items[i]);}}", "calAllIndex() {\n for (let i = 0; i < this.length; i++) {\n for (let j = 0; j < this.breath; j++) {\n let index = i + \"-\" + j;\n this.indexes.push(index);\n }\n }\n return this.indexes;\n }", "function add(array) {\n var sum = 0;\n for (index = 0; index < a.length; ++index) {\n sum+=array[index];\n }\n return sum;\n}", "function addToAll(arr, n){\n arr.forEach(function(_, index) {\n this[index] += n ;\n }, arr); //Value to use as this when executing callbackFn.\n return arr;\n}", "function addToArray(array) {\n return array.concat(0);\n}", "function addToArray(array) {\n return array.concat(0);\n}", "function sumOfArray(sum, value, index, array) {\n return sum + value;\n}", "function sumIndices(array1, array2) {\n const summedArray = [];\n const maxLength = array1.length > array2.length ? array1.length : array2.length;\n for (let i = 0; i < maxLength; i++) {\n summedArray[i] = 0;\n if (typeof array1[i] === 'number') {\n summedArray[i] += array1[i]\n }\n if (typeof array2[i] === 'number') {\n summedArray[i] += array2[i]\n }\n }\n return summedArray;\n }", "function addAll(arr){\n let total = 0;\n arr.forEach(element => total += element)\n return total\n}", "function add(array, other) {\n return array.map(function (v, i) {\n return v + other[i];\n });\n }", "function sumArr(array){\n\n}", "function sadd_array(arr) {\n var sum = arr[0];\n for (let i = 1; i < arr.length; i++) {\n sum = sum.sadd(arr[i]);\n }\n return sum;\n }", "function sum_array(total, sum){\n \t\t\treturn total + sum;\n }", "function addN(arr, n) {\n arr.forEach((ele, i) => {\n arr[i] += n\n })\n return arr\n}", "function addAllValues(array){\n let currentTotal = 0;\n console.log(array);\n console.log(array[1]);\n for ( let i = 0; i < array.length; i++){\n currentTotal = currentTotal + array[i];\n }\n return currentTotal;\n}", "function addValues(arr) {\n const sum = arr.reduce(function (acc, item, index) {\n return (acc += item);\n });\n return sum;\n}", "function _l(array, idx) {\n if (array.layout) {\n let n_array = [];\n for (let i = idx.length - 1; i >= 0; --i) {\n n_array.push(idx[i] + 1);\n }\n return n_array;\n }\n return idx;\n}", "function sumArray(accumulator, current) { \n return accumulator + current\n }", "function sumIndexes(arrayParam){\n //local variable to sumIndexes function defining and assignment to keep track of the total\n var sum = 0;\n //outer for loop\n for(index = 0; index < arrayParam.length; index++){\n //inner for loop\n for(j=0; j < arrayParam[index].length; j++){\n sum += arrayParam[inde][j];\n }\n }\n return sum;\n}", "function addAllToArray(items, arr) {\n for (var i = 0; i < items.length; i++) {\n arr.push(items[i]);\n }\n}", "function addAllToArray(items, arr) {\n for (var i = 0; i < items.length; i++) {\n arr.push(items[i]);\n }\n}", "function sum(accumulator,value,index,arr){\n return accumulator + value; \n}", "function arrayPlusArray(arr1, arr2) {\n \n let total = 0\n \n for (let i =0; i < arr1.length; i++){\n total += arr1[i] + arr2[i]\n }\n return total\n }", "InsertArrayElementAtIndex() {}", "function arrayAdd(a, b){ \n\t\tif(!a){ return arrayClone(b); } \n\t\tif(!b){ return arrayClone(a); } \n\t\tvar c = new Array(); \n\t\tfor(var i = 0; i < Math.max(a.length,b.length); c[i] = a[i] + b[i++]); \n\t\treturn c; \n\t}", "function sumArray(p, v, i, a) {\n return parseInt(p, 10) + parseInt(v, 10);\n}", "function arrAdd(...arr){\n let sum =0;\n for(let i of arr){\n sum = sum +i;\n }\n return sum;\n}", "function sumArray(arr) {\n var acc = 0,\n i;\n for (i = 0; i < arr.length; ++i) {\n acc += arr[i];\n }\n return acc;\n }", "function arrAdd(arr, value, num){\n\tfor (var i=0; i<num; i++){\n\t\tarr.push(value);\n\t}\n}", "function addArray(array) {\r\n if (array.length === 1) {\r\n return array[0];\r\n }\r\n\r\n return addArray(array.slice(1)) + array[0];\r\n}", "function sumArray(x) {\n\tvar sum = 0;\n\tfor (var i = 0; i < x.length; i++) {\n \t\tsum += x[i];\n\t}\n \treturn sum;\n }", "function addSevenNewArray(array) {\n var plusSevenArray = [];\n\n for (var i in array) {\n plusSevenArray[i] = array[i] + 7;\n }\n\n return plusSevenArray;\n}", "function addOneArray(someArray) {\n let newArray = []; \n for(let i = 0; i < someArray.length; i++) {\n newArray[i] = someArray[i] + 1;\n }\n return newArray;\n}", "function sumAll(a) {\n var c = 0\n for (var i = 0; i < a.length; i++) {\n var v = a[i];\n c += v\n }\n return c\n}", "function arraySum(data) {\n\t\treturn data.reduce(function(a, b) {\n\t\t\treturn a + b;\n\t\t}, 0);\n\t}", "function sumUp() {\n for (let i = 0; i < totalArray.length; i++) {\n sum += totalArray[i] << 0;\n }\n}", "function sumAll(array) {\n let sum = 0;\n // TODO: loop to add items\n\n for(i in array) { //logic failed with a for of loop, curious as to why\n sum += array[i];\n }\n\n return sum;\n}", "function simpleArraySum(ar) {\n let sum = 0\n for(let i = 0; i < ar.length; i++) {\n sum+=ar[i]\n }\n return sum\n}", "function plusUn(array) { // Function qui va ajouter +1 a chacuns des tableaux\n for (var i = 0; i < array.length; i++) { // Première boucle qui va parcourir les éléments du 1er tableau\n for (var j = 0; j < array[i].length; j++) { // Deuxième boucle qui va parcourir les éléments des sous-tableaux\n array[i][j] += 1; // On ajoute +1 a chacun des éléments du sous-tableau\n }\n }\n return array; // On retourne le tableau a la fin\n}", "add(num, arr) {\n let ret = [];\n\n for (var i = 0, len = arr.length; i < len; i++) {\n ret.push(arr[i] + num);\n }\n\n return ret;\n }", "function reIndexArray(arr) {\n var newArr = [];\n var count = 0;\n for (var i in arr) {\n newArr[count++]=arr[i]\n }\n return newArr;\n }", "function sumArray(total, num) {\n return total + num\n}", "function addOnes(arr) {\n\tfor (var i=0; i<arr.length; i++) {\n\t\tarr[i] = arr[i]+1;\n\t}\n\treturn arr;\n}", "addFromArray(value) { \n for(let i = 0; i < value.length; i++)\n {\n this.add(value[i])\n }\n }", "function changeIndexValues(array) {\n var newArray = [];\n for(var i = 0; i < array.length; i++) {\n newArray.push([i, Number(array[i])]);\n }\n return newArray;\n}", "function total(index) {\n\n var total = 0\n matrix[index].forEach(element => {\n total += element\n })\n return total; \n\n }", "function sum(arr){\n return arr.reduce(function(d, i){ return i + d; });\n }", "function addToArray(array) {\n return array.concat(10); // concat creates a copy of the array, then mutates that copy\n}", "function pushIndices(quote,index){\n quoteBasket.push(index);\n}", "function Add5ToAllArrayItems(arr) {\n var newArr = [];\n var newArr2 = [];\n for (let i = 0; i < arr.length; i++) {// 500\n for (let j = 0; j < arr.length; j++) {// 500\n newArr.push(arr[i] + 5);// 500 * 500 = 500^2\n newArr2.push(arr[i] + 5);\n }\n }\n return newArr;\n}", "function sumArray(array) {\n return array.reduce(function (prev, cur) {\n return prev + cur;\n }, 0);\n }", "function add(arr1, arr2) {\n return arr1.map(function (value, index) {\n return value + arr2[index];\n });\n}", "function updateArrays() {\n diceArray += result + ' ';\n totalArray.push(result);\n}", "function simpleArraySum(ar) {\r\n /*\r\n * Write your code here.\r\n */\r\n let sum = 0;\r\n for (let value of ar) {\r\n sum+=value;\r\n }\r\n \r\n return sum\r\n}", "function addAllOpt(arr){\n if(Array.isArray(arr) && arr.length !== 0 ){\n return addAll(arr)\n }\n return 0\n}", "function copiarArray(myArray){\n var arrayAux = [];\n for(let i in myArray){\n var e = []\n for(let j in myArray[i]){\n e.push(myArray[i][j]+0);\n }\n arrayAux.push(e);\n }\nreturn arrayAux;\n}", "function addOneByMap(arr) {\n arr.map(function (item, index) {\n arr[index] = item + 1;\n });\n return arr;\n}", "function addAndLog(array) {\n for (var ii = 0; ii < array.length; ii++) {\n for (var jj = 0; jj < array.length; jj++) {\n console.log(array[ii] + array[jj]);\n }\n }\n}", "function addV(u,v){\r\n\tvar w = new Array();\r\n\tvar i=0;\r\n\tfor(i=0;i<u.length;i++){\r\n\t\tw[i] = u[i]+v[i];\r\n\t}\r\n\treturn w;\r\n}", "function sumArrays(a1, a2) {\n return a1.map((el, i) => el + a2[i])\n}", "function sumationArr(arrOfArrays) {\n let result = new Array(arrOfArrays.length);\n for (let i = 0; i < arrOfArrays.length; i++) {\n let sum = 0;\n for (let x = 0; x < arrOfArrays[i].length; x++) {\n sum += arrOfArrays[i][x];\n }\n result[i] = sum;\n }\n return result;\n}", "function sumArrayPlain(arr) {\n\n window.performance.mark('pStart');\n\n var sum = 0;\n for (var i = 0; i < arr.length; i++)\n sum += arr[i];\n\n pEnd = new Date().getTime();\n /* Adding data to the global array */\n window.performance.mark('pEnd');\n console.log(\"sumArrayPlain result: \" + sum);\n }", "function addOneToArray(addingOne){\n //that adds one to every number in an array\n var added = [];\n for (let i = 0; i < addingOne.length; i++) {\n addingOne[i]++;\n added.push(addingOne[i]);\n }\n return addingOne;\n}", "function sumArr(x) {\n var sum = 0;\n for (let i = 0; i < x.length; i++) {\n sum= sum + x[i];\n \n }\n return sum;\n }", "function arrayAdd(a, b){\r\n\t\tif(!a){ return arrayClone(b); }\r\n\t\tif(!b){ return arrayClone(a); }\r\n\t\tvar c = new Array();\r\n\t\tfor(var i = 0; i < Math.max(a.length,b.length); c[i] = a[i] + b[i++]);\r\n\t\treturn c;\r\n\t}", "function addAll () {\n\tvar args = Array.prototype.slice.call(arguments);\n\tvar total = 0;\n\n\tfor (let i = 0; i < args.length; i++) {\n\t\ttotal += args[i];\n\t}\n\treturn total;\n}", "function addNForLoop(arr, n) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] += n\n }\n return arr\n}", "function arrayAdd (array1, array2){\n let arraySum = []\n let i\n for (i=0;i<array1.length;i++){\n arraySum.push(array1[i]+array2[i])\n }\n return arraySum\n}", "function sumArray(arr){\n var sum = 0;\n for(var i = 0; i<arr.length; i++){\n sum += arr[i];\n }\n return sum;\n }", "function armazenador(array, obj, index) {\n array\n array[index] = obj;\n return array;\n}", "array_add_items(from_array, to_array) {\n for (let i = 0; i < from_array.length; i++) {\n to_array.push(from_array[i]);\n }\n }", "function sumArray(arr) {\n let total=0;\n for (let i=0;i<arr.length;i++){\n total+=arr[i];\n }\n return total;\n }", "function arraySum(x) {\n var sum=0;\n for (i=0; i<x.length; i++) {\n sum = sum + x[i];\n }\n return sum;\n}", "function addElementToBeginningOfArray(array, element){\nreturn [element,...array];\n}", "function sum(array){\n var newArr = array.map(function(num){\n return num + 1;\n });\n return newArr;\n}", "function sumArray(array, result = 0, count = 0) {\r\n if (count === array.length) {\r\n return result;\r\n }\r\n result += array[count];\r\n count++;\r\n return sumArray(array, result, count);\r\n}", "function addElementToBeginningOfArray(array, add){\n return [add, ...array]\n}", "function sum_array(values) {\n return values.reduce(function(acc, a) { return acc + a; }, 0);\n}", "function sumArray(a, i, j) {\n var s = 0;\n for (var x = i; x < j; x++) {\n s += a[x];\n }\n return s;\n}", "function sumArray(aRay) {\n var arraySum = 0;\n for (var i = 0; i < aRay.length; i++) {\n arraySum += aRay[i];\n }\n return arraySum;\n}", "function addAndLog(array) {\n for (var i = 0; i < array.length; i++) {\n for (var j = 0; j < array.length; j++) {\n console.log(array[i] + array[j]);\n }\n } \n}", "addOnIndex(index, value) {\n if (index < 0) {\n console.error(`Index must be greater than 0!`);\n return false;\n }\n\n index = Math.floor(index);\n\n if (this.length <= index) {\n this.add(value);\n } else {\n const temp = this.get(index);\n this.data[index] = value;\n\n for (let i = index + 1; i < this.length; i++) {\n this.data[i + 1] = this.data[i];\n }\n\n this.data[index + 1] = temp;\n this.length++;\n }\n }", "function sumArray(array) {\n\tvar result = 0\n\tarray.forEach(function(element) {\n\t\tresult += element;\n\t});\n\treturn result \n}", "function arrayPlusArray(arr1, arr2) {\n let newArr1 = arr1.reduce((acc, c) =>(acc+c))\n let newArr2 = arr2.reduce((acc, c) =>(acc+c))\n return newArr1 + newArr2\n}", "function sumArray (x) {\n\nvar sum =0;\nfor(var i=0; i< x.length; i++){\nsum = sum + x[i];\n}\nreturn sum;\n\n}", "function addElementToEndOfArray(array, element){\narray = [...array, element];\nreturn(array);\n}", "function sum(arr) {\n \tconst len = arr.length;\n \tlet result = 0;\n \tfor (let i = 0; i < len; i++) {\n \t\tresult += arr[i];\n \t}\n \treturn result;\n }", "function arrayAdd(in1, in2){\n return in1.reduce(array_1[0], array_1.[array_1.length - 1]) + in2.reduce(array_2[0], array_2.[array_2.length - 1]);\n }", "function sumAll(arr) {\n return 1;\n}", "function sumArray(arr) {\n var sum = 0;\n for (let i=0; i<arr.length; i++) {\n sum+=arr[i];\n }\n return sum\n }", "function arraySum(arr){\n let sum = 0;\n for(let i = 0; i < arr.length; i++){\n sum+=arr[i]\n }\n return sum;\n}", "function addElementToEndOfArray(array,element){\n return [...array,element]\n\n}", "function sum_array_length ( array_one, array_two, array_three, array_four){\n\n sum_array = [];\n sum_array.push.apply(sum_array, array_one);\n sum_array.push.apply(sum_array, array_two);\n sum_array.push.apply(sum_array, array_three);\n \n console.log( sum_array.length + \" \" + sum_array + \" sum_array longitud\" );\n \n}", "function add(matrix, inverseMatrix, startIndex, fromIndex, n, k) {\n for (var i = 0; i < n; ++i) {\n var x = startIndex + i * n;\n var fromX = fromIndex + i * n;\n matrix[x] += matrix[fromX] * k;\n inverseMatrix[x] += inverseMatrix[fromX] * k;\n }\n }", "function sumArray(array) {\n total = 0;\n for (i = 0; i < array.length; i++) {\n total += array[i];\n }\n return total;\n}", "function addSeven(arr){\n var newArr = []\n for(e in arr){\n newArr[e] = arr[e] + 7;\n }\n return newArr\n}", "function addElementToBeginningOfArray(array,element){\n return [element,...array]\n}", "function a(e,t){var n=i.length?i.pop():[],a=o.length?o.pop():[],s=r(e,t,n,a);return n.length=0,a.length=0,i.push(n),o.push(a),s}", "function add(array, element, index) {\n // Append to the end if index is not set\n if (!_Type__WEBPACK_IMPORTED_MODULE_1__[\"isNumber\"](index)) {\n array.push(element);\n }\n // Add to the beginning of array if index is 0\n else if (index === 0) {\n array.unshift(element);\n }\n // Add to indicated place if index is set\n else {\n array.splice(index, 0, element);\n }\n}", "function addElementsToFinal (arrayOfArrays) {\n //base case: no remaining elements in input array\n if (!arrayOfArrays.length) {\n return finalArray;\n }\n //for each subarray in the source arrays first element...\n for (var i = 0; i < arrayOfArrays[0].length; i++) {\n //...add to the results array\n finalArray.push(arrayOfArrays[0][i]);\n }\n //recursive function call of the rest of the source array\n return addElementsToFinal (arrayOfArrays.slice(1));\n }", "function arraysaver(ele, ind, val){\n\t\tif(ind.length == 1){\n\t\t\tele[buscar(ind.shift())]=val;\n\t\t} else {\n\t\t\tvar aux=buscar(ind.shift());\n\t\t\tif(!Array.isArray(ele[aux]))\n\t\t\t\tele[aux]=[];\n\t\t\tarraysaver(ele[aux], ind, val);\n\t\t}\n\t}" ]
[ "0.6395287", "0.63486606", "0.63447315", "0.6324168", "0.63031083", "0.63031083", "0.62665117", "0.61701673", "0.6124362", "0.61149746", "0.6105366", "0.60850364", "0.60814285", "0.6022867", "0.59830815", "0.5974806", "0.5946294", "0.59406817", "0.5907516", "0.58966327", "0.58966327", "0.58624816", "0.5851147", "0.58435833", "0.58116853", "0.5811008", "0.58057016", "0.5796878", "0.57793677", "0.5762695", "0.57567793", "0.57537967", "0.5730581", "0.57186675", "0.5716572", "0.5708887", "0.57084626", "0.5704184", "0.56968814", "0.56925786", "0.5688735", "0.5685601", "0.5685", "0.56837744", "0.5680884", "0.56789774", "0.56783205", "0.5671096", "0.5664832", "0.56536496", "0.56418526", "0.5636875", "0.56322217", "0.56305754", "0.56303835", "0.56285197", "0.56267464", "0.5618483", "0.5617798", "0.5613093", "0.5612825", "0.56094533", "0.5608731", "0.5606046", "0.5599549", "0.5599173", "0.5594582", "0.5591474", "0.5590326", "0.55867356", "0.5585557", "0.55841666", "0.55794656", "0.557945", "0.5575165", "0.5564796", "0.5564627", "0.5563816", "0.5560945", "0.55579966", "0.5545999", "0.55424607", "0.55418897", "0.55389357", "0.55385417", "0.55363894", "0.55339605", "0.5532445", "0.55296", "0.55286896", "0.55274385", "0.5523613", "0.5520703", "0.55199975", "0.5508278", "0.550526", "0.5503363", "0.54983", "0.549609", "0.54958504", "0.54903996" ]
0.0
-1
Mathematical Operations Take three values (operator as a string, num1, num2) return the result
function basicOp(operation, value1, value2) { if (operation == '+') { return value1 + value2 } else if (operation == '-') { return value1 - value2 } else if (operation == '*') { return value1 * value2 } else if (operation == '/') { return value1 / value2 } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function operate(num1, num2, operator)\n{\n let ans;\n if(operator == '+')\n ans = add(num1,num2);\n else if (operator == '-')\n ans = sub(num1,num2);\n else if ( operator == \"/\")\n ans = div(num1,num2);\n else \n ans = mul(num1,num2);\n return ans;\n}", "function operate(operator, num1,num2){\n num1 = parseFloat(num1)\n num2 = parseFloat(num2)\n switch(operator){\n case '*':\n return multiply(num1,num2);\n break;\n \n case '-':\n return minus(num1,num2);\n break;\n\n case '/':\n return divide(num1,num2);\n break;\n\n case '+':\n return add(num1,num2);\n break;\n }\n}", "function operate(operator, num1, num2) {\n switch (operator) {\n case \"+\":\n return add(num1, num2);\n case \"-\":\n return subs(num1, num2);\n case \"*\":\n return mult(num1, num2);\n case \"/\":\n return div(num1, num2);\n case \"%\":\n return module(num1,num2);\n case \"sqr\":\n return square(num1, num2);\n } \n}", "function operate(num1, num2, operator){\n if (operator == \"+\") return add(num1, num2);\n if (operator == \"-\") return subtract(num1, num2);\n if (operator == \"*\") return multiply(num1, num2);\n if (operator == \"/\") return divide(num1, num2);\n return \"wrong operator\";\n}", "function operate(operator, number1, number2) {\n let result;\n switch (operator) {\n case \"+\":\n result = add(number1, number2);\n break;\n case \"-\":\n result = subtract(number1, number2);\n break;\n case \"X\":\n result = multiply(number1, number2);\n break;\n case \"/\":\n result = divide(number1, number2);\n break;\n default:\n break;\n }\n return result;\n}", "function operate(num1, num2, operator) {\n if (operator == \"+\") {\n return add(num1, num2);\n } else if (operator == \"-\") {\n return subtract(num1, num2);\n } else if (operator == \"÷\") {\n return divide(num1, num2);\n } else if (operator == \"×\") {\n return multiply(num1, num2);\n }\n}", "function operate(num1, num2, operator){\n if(operator === '+') return add(num1, num2)\n if(operator === '-') return subtract(num1, num2)\n if(operator === '*') return multiply(num1, num2)\n if(operator === '/') return divide(num1, num2)\n}", "function operate(num1, operator, num2) {\n switch(operator) {\n case '+':\n return add(num1, num2);\n case '-':\n return subtract(num1, num2);\n case '*':\n return multiple(num1, num2);\n case '/':\n return divide(num1, num2);\n }\n}", "function operation(number1, number2, operator) {\n\n\n\n let res // result container\n // basic math operation\n switch(operator){\n case '+':\n res = parseFloat(number1) + parseFloat(number2)\n break\n case '-':\n res = parseFloat(number1) - parseFloat(number2)\n break\n case '/':\n res = parseFloat(number1) / parseFloat(number2)\n break\n case '*':\n res = parseFloat(number1) * parseFloat(number2)\n break\n default:\n return 0\n }\n\n // some scientific calculation\n\n\n return res\n}", "function operate(operator, num1, num2) {\n num1 = parseFloat(prevNum, 10);\n num2 = parseFloat(currentNum, 10);\n if (operator == 'add') {\n return add(num1, num2);\n } if (operator == 'subtract') {\n return subtract(num1, num2);\n } if (operator == 'multiply') {\n return multiply(num1, num2);\n } if (operator == 'divide') {\n return divide(num1, num2);\n } if (operator == '') {\n displayNum.textContent = '';\n }\n}", "function operation(inputOperator, num1, num2) {\n var result;\n if (inputOperator == \"add\") {\n let add = num1 + num2;\n result = `${num1} + ${num2} = ${add}`;\n console.log(result);\n } else if (inputOperator == \"substract\") {\n let subtract = num1 - num2;\n result = `${num1} - ${num2} = ${subtract}`;\n console.log(result);\n } else if (inputOperator == \"multiply\") {\n let multiply = num1 * num2;\n result = `${num1} * ${num2} = ${multiply}`;\n console.log(result);\n } else if (inputOperator == \"divide\") {\n let divide = num1 / num2;\n result = `${num1} / ${num2} = ${divide}`;\n console.log(result);\n }\n}", "function operate(operator,a,b) {\n\n if (operator == \"+\"){\n let results = addNums(a,b);\n return results;\n } else if (operator == \"-\"){\n let results = subtractNums(a,b);\n return results;\n } else if (operator == \"*\"){\n let results = multiplyNums(a,b);\n return results;\n } else if (operator == \"/\"){\n let results = divideNums(a,b);\n return results;\n }\n\n \n\n}", "function calculator(number1, number2, operator) {\n switch (operator) {\n case \"+\":\n value = number1 + number2;\n break;\n case \"-\":\n value = number1 - number2;\n break;\n case \"*\":\n value = number1 * number2;\n break;\n case \"/\":\n value = number1 / number2;\n break;\n case \"%\":\n value = number1 % number2;\n }\n return `${number1} ${operator} ${number2} = ${value}.`; //return result\n}", "function compute(operand1, operand2, operator){\n\toperand1 = Number(operand1);\n\toperand2 = Number(operand2);\n\t//console.log(operand1);\n\t//console.log(operand2);\n\tswitch (operator){\n\t\tcase '^': return Math.pow(operand1, operand2);\n\t\tcase '+': return operand1 + operand2;\n\t\tcase '-': return operand1 - operand2;\n\t\tcase '*': return operand1 * operand2;\n\t\tcase '/': return operand1 / operand2;\n\t}\n}", "function calculator(num1,operator,num2) {\r\n\r\n let result;\r\nswitch (operator) {\r\n \r\n case \"+\": result = num1+num2; break;\r\n case \"-\": result = num1-num2; break;\r\n case \"*\": result = num1*num2; break;\r\n case \"/\": result = num1/num2; break;\r\n case \"%\": result = num1%num2; break;\r\n case \"^\": result = Math.pow(num1,num2) ; break;\r\n case \"sin\": result = Math.sin(num1,num2) ; break;\r\n case \"cos\": result = Math.cos(num1,num2) ; break;\r\n case \"tan\": result = Math.tan(num1,num2) ; break;\r\n default: result = \"invalid operator\"; break;\r\n}\r\n return result;\r\n}", "function operate(operator, a, b) {\n a = Number(a);\n b = Number(b);\n switch (operator) {\n case \"+\":\n return add(a, b);\n case \"-\":\n return subtract(a, b);\n case \"*\":\n return mult(a, b);\n case \"÷\":\n if (b === 0) return null;\n else return divide(a, b);\n case \"%\":\n return percent(a);\n default:\n return null;\n}\n}", "function calculate(firstNum, secondNum, operator) {\n\tswitch(operator) {\n\t\tcase \"+\":\n\t\t\treturn firstNum + secondNum;\n\t\tcase \"-\":\n\t\t\treturn firstNum - secondNum;\n\t\tcase \"*\":\n\t\t\treturn firstNum * secondNum;\n\t\tcase \"/\":\n\t\t\treturn firstNum / secondNum;\n\t\tdefault:\n\t\t\tthrow \"Incorrect Operator\";\n\t}\n}", "function calculate(number1, number2, operator) {\n if (operator === 'add') {\n return suma();\n } else if (operator === 'multiply') {\n return inmultire();\n } else if (operator === 'substract') {\n return scadere();\n } else if (operator === 'divide') {\n return impartire();\n }\n\n function suma() {\n return (number1 + number2);\n }\n function impartire() {\n return (number1 / number2);\n }\n function inmultire() {\n return (number1 * number2);\n }\n function scadere() {\n return (number1 - number2);\n }\n}", "function evalPair(num1, num2, op) {\nvar eval = 0;\nswitch(op) {\n case '+': \n eval = num1+num2;\n break;\n case '-':\n eval = num1-num2;\n break;\n case '*':\n eval = num1*num2;\n break;\n case '/':\n eval = num1/num2;\n break;\n }\n return eval;\n}", "function operation(operator) {\n var position = (resultScreen.innerText).indexOf(operator);\n var operandTwo = parseInt((resultScreen.innerText).substr(position+1), 2);\n return operandTwo;\n }", "function calculator(numOne, numTwo, operator) {\n switch (operator) {\n case \"+\":\n return numOne + numTwo;\n break;\n case \"-\":\n return numOne - numTwo;\n break;\n case \"/\":\n return numOne / numTwo;\n break;\n case \"*\":\n return numOne * numTwo;\n break;\n default:\n return \"Error! Something went wrong\";\n }\n}", "function calculator(num1, operator, num2) {\n if (num2 === 0) { return \"Can't divide by 0!\"; }\n else {\n switch (operator) {\n case \"+\":\n return num1 + num2;\n case \"-\":\n return num1 - num2;\n case \"*\":\n return num1 * num2;\n case \"/\":\n return num1 / num2;\n }\n }\n}", "function calculator(num1,num2,operator){\n var res =parseInt(num1)+parseInt(num2);\n document.write(res);\n}", "function calculate(operand1, operand2, operator) {\n if (operator == \"+\") {\n return operand1 + operand2;\n } else if (operator == \"-\") {\n return operand1 - operand2;\n } else if (operator == \"*\") {\n return operand1 * operand2;\n } else if (operator == \"/\") {\n return operand1 / operand2;\n }\n}", "function calculate(num1, op, num2) {\n // ifs and elses (switch?) using num1, num2 and operator\n\n\n var result;\n\n switch (op) {\n case \"+\":\n result = num1 + num2;\n\n break;\n\n case \"-\":\n result = num1 - num2;\n\n break;\n\n case \"*\":\n result = num1 * num2;\n\n break;\n\n case \"/\":\n result = num1 / num2;\n\n break;\n\n default:\n\n }\n // console.log(result);\n return result;\n }", "function result(operator, num1, num2){\n var result = eval(num1 + operator + num2);\n $('#result').text(result);\n return result;\n\n}", "function calc(op, n1, n2) {\n var result = 0;\n switch (op) {\n case \"+\":\n result = n1 + n2;\n break;\n case \"-\":\n result = n1 - n2;\n break;\n case \"x\":\n result = n1 * n2;\n break;\n case \"/\":\n result = n1 / n2;\n break;\n }\n return result;\n}", "function calculator(number1, number2, operator) {\n switch (operator) {\n case \"+\":\n value = number1 + number2;\n break;\n\n case \"-\":\n value = number1 - number2;\n break;\n\n case \"*\":\n value = number1 * number2;\n break;\n\n case \"/\":\n value = number1 / number2;\n break;\n\n case \"%\":\n value = number1 % number2;\n }\n\n return \"\".concat(number1, \" \").concat(operator, \" \").concat(number2, \" = \").concat(value, \".\"); //return result\n} //call function and pass parameters and write result", "function cal(num1,num2,op){\n let y ;\n if(op == \"*\"){\n return duplicate(num1,num2);\n }\n else if(op == \"/\"){\n return division(num1,num2);\n }\n else if(op == \"-\"){\n y = num1.valueOf() - num2.valueOf(); \n return y.toString();\n }\n else if(op == \"+\"){\n num1 = parseFloat(num1);\n num2 = parseFloat(num2);\n y = num1+ num2;\n return y.toString();\n }\n\n }", "function calculate(first, second, operator) {\n switch (operator) {\n case '+':\n return Number(first) + Number(second);\n break;\n case '-':\n return Number(first) - Number(second);\n break;\n case '*':\n return Number(first) * Number(second);\n break;\n case '/':\n return Number(first) / Number(second);\n break;\n }\n}", "function doMath(operator, a, b) {\n return operator;\n}", "function calculator(number1, operator, number2) {\n switch (operator) {\n case \"+\": return number1 + number2;\n case \"-\": return number1 - number2;\n case \"*\": return number1 * number2;\n case \"/\":\n if (number2 == 0) return \"Can't divide by 0!\"\n return number1 / number2;\n }\n}", "function operate(operator, x, y) {\n if (operator === '+'){\n return add(x,y);\n }\n else if (operator === '-') {\n return subtract(x,y);\n }\n else if (operator === '*') {\n return multiply(x,y);\n }\n else {\n return divide(x,y);\n }\n}", "function operate(a, b, operator) {\n switch(operator) {\n case \"+\":\n return add(a, b);\n break;\n case \"-\":\n return subtract(a, b);\n break;\n case \"x\":\n return multiply(a, b);\n break;\n case \"÷\":\n return division(a, b);\n break;\n };\n}", "function calculate(a, b, operator){\n if (operator === \"+\"){\n return a+b\n }else if (operator === \"-\"){\n return a-b\n }else if (operator === \"*\"){\n return a*b\n }else if (operator === \"/\"){\n return a/b\n }\n}", "function operate(a, b)\n{\nswitch(operator){\n case \"add\":\n return add(a, b);\n break;\n \n case \"-\":\n return subtract(a, b);\n break;\n \n case \"*\":\n return multiply(a, b);\n break;\n \n case \"/\":\n return divied(a, b);\n break;\n}\n}", "function getCalculation(num1, num2, oparetor) {\n switch (oparetor) {\n case '+':\n return num1 + num2;\n case '-':\n return num1 - num2;\n case '*':\n return num1 * num2;\n case '/':\n return num1 / num2;\n default:\n return num1 % num2;\n }\n\n}", "calculate(){\r\n \r\n switch(this.operator){//evaluate the operator \r\n case \"^\"://if the operator is ^, then use the power formula\r\n return Math.pow(this.num1,this.num2); \r\n case \"*\"://if the operator is *, multiple the two numbers\r\n return this.num1*this.num2;\r\n case \"/\"://if the operator is ^,divide the two numbers\r\n return this.num1/this.num2; \r\n case \"+\"://if the operator is ^, add the two numbers\r\n return this.num1+this.num2;\r\n case \"-\"://if the operator is ^, subtract the two numbers\r\n return this.num1-this.num2; \r\n default://else error\r\n return \"ERROR\" \r\n }\r\n }", "function calculate(num1,num2,operator){\r\n if(operator==\"+\"){\r\n cal=num1+num2\r\n operator=\"Addition\"\r\n return \"The \"+operator+\" Of \"+num1+\" and \"+num2+\" is : \"+cal\r\n \r\n }\r\n else if(operator==\"-\"){\r\n cal=num1-num2\r\n operator=\"Subtraction\"\r\n return \"The \"+operator+\" Of \"+num1+\" and \"+num2+\" is : \"+cal\r\n \r\n }\r\n else if(operator==\"*\"){\r\n cal=num1*num2\r\n operator=\"Multiplication\"\r\n return \"The \"+operator+\" Of \"+num1+\" x \"+num2+\" is : \"+cal\r\n \r\n }\r\n else if(operator==\"/\"){\r\n cal=num1/num2\r\n operator=\"Divison\"\r\n return \"The \"+operator+\" Of \"+num1+\" and \"+num2+\" is : \"+cal\r\n \r\n }\r\n else if(operator==\"%\"){\r\n cal=num1%num2\r\n operator=\"Modulus Division \"\r\n return \"The \"+operator+\" Of \"+num1+\" and \"+num2+\" is : \"+cal\r\n \r\n }\r\n else{\r\n \r\n return \"Please Select Correct Operator\"\r\n \r\n }\r\n \r\n }", "function calculator(firstnumber,operator,secondnumber)\n{\n var totalval;\n switch(operator)\n {\n case '+':\n totalval = firstnumber + secondnumber;\n break;\n case '-':\n totalval = firstnumber - secondnumber;\n break;\n case '*':\n totalval = firstnumber * secondnumber;\n break;\n case '/':\n totalval = firstnumber / secondnumber;\n break;\n\n }\n return totalval\n}", "function operate(a,operator,b){\n\tswitch(operator){\n\t\tcase '+':\n\t\t\treturn add(a,b);\n\t\t\tbreak;\n\t\tcase '-':\n\t\t\treturn substract(a,b);\n\t\t\tbreak;\n\t\tcase '*':\n\t\t\treturn multiply(a,b);\n\t\t\tbreak;\n\t\tcase '/':\n\t\t\treturn divide(a,b);\n\t\t\tbreak;\n\t\tcase '=':\n\t\t\treturn b;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tclearAll();\n\t\t\talert(\"Error: Invalid operator!\");\n\t\t\treturn 0;\n\t\t\tbreak;\n\t}\n}", "function operate(operator, x, y) {\n x = Number(x);\n y = Number(y);\n \n switch (operator) {\n case '+':\n return add(x, y);\n case '-':\n return subtract(x, y);\n case '*':\n return multiply(x, y);\n case '/':\n return divide(x, y);\n case '^':\n return exponent(x, y);\n default:\n return null;\n }\n}", "function calculator(symbol, a, b) {\n if (symbol == \"+\") {\n return a+b;\n } else if (symbol == \"-\") {\n return a-b;\n } else if (symbol == \"/\") {\n return a/b;\n } else if (symbol == \"*\") {\n return a*b;\n } else {\n return \"invalid operator\"\n }\n}", "function Calc(a,b,operator) {\n\n switch (operator) {\n \n case '+':\n return a + b\n break;\n case '-':\n return a - b\n break;\n case '*':\n return a * b\n break;\n // case '%':\n // return a % b\n case '/':\n return a / b\n break;\n \n }\n \n }", "function basicOp(operation, value1, value2) {\n if (operation === \"+\") {\n return value1 + value2;\n } else if (operation === \"-\") {\n return value1 - value2;\n } else if (operation === \"*\") {\n return value1 * value2;\n } else if (operation === \"/\") {\n return value1 / value2;\n } else {\n return console.log(\"Wrong operation\");\n }\n}", "function operation(operator){\n let numberOne = parseInt(document.getElementById(\"numberOne\").value);\n let numberTwo = parseInt(document.getElementById(\"numberTwo\").value);\n let resultOp;\n if (operator === \"plus\"){\n resultOp = numberOne+numberTwo;\n }\n else if (operator === \"minus\"){\n resultOp = numberOne-numberTwo;\n }\n else if (operator === \"multiplier\"){\n resultOp = numberOne*numberTwo;\n }\n else if (operator===\"divider\"){\n resultOp = numberOne/numberTwo;\n }\n else {\n console.log(\"trace: problem\");\n }\n document.getElementById(\"result\").value = resultOp;\n}", "function operate(operator){\n \n if (input===\"\"){\n //nothing \n \n }\n else if(hasNum1){\n \n compute();\n }\n else{\n \n num1Val = parseFloat(input);\n hasNum1 = true;\n \n }\n \n opp=operator;\n\n input=\"\";\n \n}", "function operate(operator, x, y) {\n\n if (operator == \"+\") {\n return add(x, y);\n\n } else if (operator == \"-\") {\n return subtract(x, y);\n\n } else if (operator == \"x\") {\n return multiply(x, y);\n\n } else if (operator == \"÷\") {\n return divide(x, y);\n }\n}", "function calc(num1,opr,num2){\r\n if(opr === \"+\"){\r\n return num1 + num2\r\n }else if (opr === \"-\"){\r\n return num1 - num2;\r\n }else if(opr === \"*\"){\r\n return num1 * num2\r\n }else {\r\n return \"Wrong \"\r\n }\r\n}", "function basicOp(operation, value1, value2) {\n\tswitch (operation) {\n\t\tcase '+':\n\t\t\treturn value1 + value2;\n\t\t\tbreak;\n\t\tcase '-':\n\t\t\treturn value1 - value2;\n\t\t\tbreak;\n\t\tcase '/':\n\t\t\treturn value1 / value2;\n\t\t\tbreak;\n\t\tcase '*':\n\t\t\treturn value1 * value2;\n\t}\n}", "function arithmetic(a, b, operator) {\n switch (operator) {\n case \"add\":\n return a + b;\n case \"subtract\":\n return a - b;\n case \"multiply\":\n return a * b;\n case \"divide\":\n return a / b;\n return null;\n }\n}", "function doOp(op, v1, v2) {\n switch (op) {\n case '+': return v1 + v2;\n case '-': return v1 - v2;\n case '*': return v1 * v2;\n case '/': return v1 / v2;\n case '^': return Math.pow(v1, v2);\n default: throw new Error('Unknown operator: ' + op);\n }\n }", "function doMath(num1 ,num2 , operator) {\n if (num2 == null) {\n if(totalInt2 == null){\n totalInt2 = parseFloat(num1);\n }\n num2 = totalInt2;\n storeNum2 = parseFloat(num2);\n\n }\n if (operator == \"+\") {\n num1 = parseFloat(num1) + parseFloat(num2);\n }\n else if (operator == \"-\") {\n num1 = parseFloat(num1) - parseFloat(num2);\n }\n else if (operator == \"/\") {\n if(num2 == 0){\n $(\"#displayScreen p\").text(\"Error\");\n totalInt2 = null;\n return;\n }\n num1 = parseFloat(num1) / parseFloat(num2);\n }\n else if (operator == \"X\") {\n num1 = parseFloat(num1) * parseFloat(num2);\n }\n return num1.toFixed(3);\n}", "function basicOp(operation, value1, value2)\n{\n // Code\n switch(operation) {\n case '+':\n return value1 + value2;\n case '-':\n return value1 - value2;\n case '*':\n return value1 * value2;\n case '/':\n return value1 / value2;\n default:\n break;\n }\n}", "function basicOp(operation, value1, value2) {\n switch (operation) {\n case '+':\n return value1 + value2;\n break;\n case '-':\n return value1 - value2;\n break;\n case '*':\n return value1 * value2;\n break;\n case '/':\n return value1 / value2;\n break;\n default:\n break;\n }\n}", "function operate(operator, operand1, operand2) {\n return operator(operand1, operand2);\n}", "function operate(operator, operand1, operand2) {\n return operator(operand1, operand2);\n}", "function getResult(val1, val2, operation) {\r\n\tif(operation === '+') {\r\n\t\treturn val1 + val2;\r\n\t} else if(operation === '-') {\r\n\t\treturn val1 - val2;\r\n\t} else if(operation === '*') {\r\n\t\treturn val1 * val2;\r\n\t} else if(operation === '/') {\r\n\t\treturn val1 / val2;\r\n\t}\r\n\t}", "function getOperator()\n\t{\n\t\t// handle 2 consecutive operators\n\t\t\n\t\tif(acc == \"\" && this.value == \"-\")\n\t\t{\n\t\t\t// Here - is the sign of the number and not op\n\t\t\tacc = acc + this.value;\n\t\t\tdocument.getElementById(\"output\").value = acc;\n\t\t\treturn;\n\t\t}\n\t\telse if(acc == \"-\")\n\t\t{\n\t\t\t// Invalid input. Number expected after - operator\n\t\t\treturn;\n\t\t}\n\t\telse if(acc == \"\")\n\t\t{\n\t\t\t// consecutive operator.\n\t\t\t// consider the current one\n\t\t\tcurrOp = this.value;\n\t\t}\n\t\telse // normal case\n\t\t{\n\t\t\tcurrVal = applyOperator(currVal, acc, currOp);\n\t\t}\n\t\t\n\t\t// to display o/p for transaction chaining\n\t\tdocument.getElementById(\"output\").value = currVal;\n\t\t\n\t\tif(currVal == \"Undefined\")\n\t\t{\t\n\t\t\tresetValues(false);\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tacc = \"\";\n\t\tcurrOp = this.value;\n\t}", "function operate(operator, operand1, operand2) {\n return operator(operand1, operand2);\n}", "function mathOp(x, op, y)\n{\n switch (op)\n {\n case '+':\n return x + y;\n case '-':\n return x - y;\n case '*':\n return x * y;\n case '/':\n return x / y;\n case '**':\n return x ** y;\n case 'sqrt':\n return x ** 0.5;\n default: return 'Could not recognise input';\n }\n}", "function operation(operator) {\n\n document.getElementById('oper').innerHTML = operator;\n console.log(previousVal);\n if (opt == '+') { var reducer = (previousVal, displayVal) => previousVal + displayVal; }\n else if (opt == '-') { var reducer = (previousVal, displayVal) => previousVal - displayVal; }\n else if (opt == '*') { var reducer = (previousVal, displayVal) => previousVal * displayVal; }\n else if (opt == '/') { var reducer = (previousVal, displayVal) => previousVal / displayVal; }\n else if (opt == '=') { var reducer = (previousVal, displayVal) => previousVal + \" \"; }\n result = reducer((+previousVal), (+displayVal));\n document.getElementById('result').value = result;\n previousVal = result;\n opt = operator;\n displayVal = \" \";\n}", "function calculator (firstnumber, operator, secondnumber) {\n switch (operator) {\n case '+':\n return parseInt(firstnumber + secondnumber);\n break;\n case '-':\n return parseInt(firstnumber - secondnumber);\n break;\n case '*':\n return parseInt(firstnumber * secondnumber);\n break;\n case '/':\n if (secondnumber === 0) {\n return Infinity;\n break;\n } else {\n return parseInt(firstnumber / secondnumber);\n break;\n }\n default:\n console.log('Sorry, the arguments are not numbers');\n }\n}", "function calcByFollowingOper(operator, inpArr) {\n let res = inpArr[0];\n switch (operator) {\n case \"+\":\n for (let i = 1; i < inpArr.length; i++) {\n res += inpArr[i];\n }\n return res;\n case \"-\":\n for (let i = 1; i < inpArr.length; i++) {\n res -= inpArr[i];\n }\n return res;\n case \"/\":\n for (let i = 1; i < inpArr.length; i++) {\n res /= inpArr[i];\n }\n return res;\n case \"*\":\n for (let i = 1; i < inpArr.length; i++) {\n res *= inpArr[i];\n }\n return res;\n }\n}", "function operation(operator, value){\n\tif(operator == '+'){\n\t\treturn result + value;\n\t} else if (operator == '-'){\n\t\treturn result - value;\n\t} else if (operator == '*'){\n\t\treturn result * value;\n\t} else if (operator == '/'){\n\t\tif (value == 0){\n\t\t\tconsole.log(\"Cannot divide by zero try again\");\n\t\t\treturn result;\n\t\t} else {\n\t\t\treturn result / value;\n\t\t}\n\t} else {\n\t\tconsole.log(\"Not a valid operator\");\n\t}\n}", "function math (numberOne, numberTwo, operation){\n\n if (operation === 'add'){\n return (numberOne + numberTwo);\n }\n if (operation === 'subtract'){\n return (numberOne - numberTwo);\n }\n if (operation === 'multiply'){\n return (numberOne * numberTwo);\n }\n if (operation === 'divide'){\n return (numberOne / numberTwo);\n }\n\n return (NaN);\n\n}", "function evaluate1(numArr, opArr) {\n const left = evalPair(parseFloat(numArr[0]),parseFloat(numArr[1]),opArr[0]);\n const right = evalPair(parseFloat(numArr[2]),parseFloat(numArr[3]),opArr[2]);\n \n return evalPair(left,right,opArr[1]);\n}", "function answer(val1, val2){\n\n if(operation === '+'){return val1 + val2;}\n if(operation === '-'){return val1 - val2;}\n if(operation === 'X'){return val1 * val2;}\n if(operation === '/'){return (val1 / val2);}\n if(operation === '%'){return val1 % val2;}\n }", "function operate(operator, a, b) {\n switch (operator) {\n case add:\n return add(a, b);\n break;\n\n case subtract:\n return subtract(a, b);\n break;\n\n case multiply:\n return multiply(a, b);\n break;\n\n case divide:\n return divide(a, b);\n break;\n }\n}", "function operate(operator, operand1, operand2) {\n\treturn operator(operand1, operand2);\n}", "function operate(operator, operand1, operand2) {\n\treturn operator(operand1, operand2);\n}", "function getResult(val1, val2, operation) {\n\t\tif (operation === '+') {\n\t\t\treturn val1 + val2;\n\t\t} else if (operation === '-') {\n\t\t\treturn val1 - val2;\n\t\t} else if (operation === '*') {\n\t\t\treturn val1 * val2;\n\t\t} else {\n\t\t\treturn val1 / val2;\t\n\t\t} \n\t}", "function mathOperation() {\n if (lastOperation === \"x\") {\n result = parseFloat(result) * parseFloat(dis2Num);\n } else if (lastOperation === \"+\") {\n result = parseFloat(result) + parseFloat(dis2Num);\n } else if (lastOperation === \"-\") {\n result = parseFloat(result) - parseFloat(dis2Num);\n } else if (lastOperation === \"/\") {\n result = parseFloat(result) / parseFloat(dis2Num);\n } else if (lastOperation === \"%\") {\n result = parseFloat(result) % parseFloat(dis2Num);\n }\n}", "function calculate(n1, op, n2) {\n switch (op) {\n case '+':\n return n1 + n2;\n case '-':\n return n1 - n2;\n case '/':\n return n2 !== 0 ? n1 / n2 : null;\n case '*':\n return n1 * n2;\n default:\n return null;\n }\n}", "static get OP() {\n return {\n PLUS: 90,\n MINUS: 91,\n MULT: 92,\n DIV: 93,\n input_to_operation_map: {\n 90: \"PLUS\",\n 91: \"MINUS\",\n 92: \"MULT\",\n 93: \"DIV\",\n }\n };\n }", "function calculator(operator) {\n var a=parseInt(document.getElementById(\"op-one\").value);\n var b=parseInt(document.getElementById(\"op-two\").value);\n switch (operator){\n case \"+\":\n alert(a + b);\n break;\n case \"-\":\n alert(a - b);\n break;\n case \"*\":\n alert(a * b);\n break;\n case \"/\":\n alert(a / b);\n break;\n }\n\n}", "function mathOperation() {\n if (lastOperation === \"X\") {\n result = parseFloat(result) * parseFloat(displayTwoNum);\n } else if (lastOperation === \"+\") {\n result = parseFloat(result) + parseFloat(displayTwoNum);\n } else if (lastOperation === \"-\") {\n result = parseFloat(result) - parseFloat(displayTwoNum);\n } else if (lastOperation === \"/\") {\n result = parseFloat(result) / parseFloat(displayTwoNum);\n }\n}", "function operate(x, y, operator) {\n switch (operator) {\n case 'add':\n return add(x, y);\n\n case 'subtract':\n return subtract(x, y);\n\n case 'multiply':\n return multiply(x, y);\n \n case 'divide':\n return divide(x, y);\n\n default: \n alert('Use numbers and declare operator');\n };\n}", "function operation(op, num){\n if(op == 'square'){\n return Math.pow(num,2);\n }\n return Math.pow(num,3);\n}", "function calT(a, b, op) {\n\n var result;\n \n if (op == \"+\") {\n \n result = a + b;\n \n alert(result);\n }\n \n else if (op == \"-\") {\n \n result = a - b;\n \n alert(result);\n \n }\n \n else if(op == \"*\") {\n \n result = a * b;\n \n alert(result);\n }\n \n else if(op == \"/\"){\n \n result = a / b;\n \n alert(result);\n }\n \n \n }", "function operate(a, operation, b) {\n a = parseFloat(a)\n b = parseFloat(b)\n \n switch(operation) {\n case \"+\":\n return a+b\n case \"-\":\n return a-b\n case \"x\":\n return a*b\n case \"÷\":\n return a/b\n }\n}", "function doMath(operator, a, b) {\n var answer = operator(a, b);\n return answer;\n}", "function evaluate(operator) {\n let op2 = document.getElementById(\"lower\").value\n\n //Evaluating the expression \n let ch = expression.charAt((expression.length) - 1)\n if (ch == \"+\" || ch == \"-\" || ch == \"*\" || ch == \"/\") {\n //If user has clicked to evluate without the value of second operand,then add 0 automatically to complete it\n if (op2 == \"\") {\n op2 = 0\n }\n expression += op2;\n answer = calculate(parseInt(answer), parseInt(op2), operator)\n }\n\n //Updating the expression and displaying the result\n expressionSection.innerHTML = expression;\n inputSection.value = answer;\n}", "function evaluate() {\n var operand = resultdiv.innerHTML.split(operator);\n resultdiv.innerHTML = Math.floor(eval(parseInt(operand[0],2)\n + operator + parseInt(operand[1],2)\n )).toString(2);\n operator = '';\n}", "function calculator(act, num1, num2) {\n\n if (act === \"suma\") {\n return num1 + num2;\n } else if (act === \"resta\") {\n return num1 - num2;\n } else if (act === \"mult\") {\n return num1 * num2;\n } else if (act === \"div\") {\n return num1 / num2;\n } else {\n return \"escribe suma, resta, mult, div\";\n }\n\n}", "function calculate () {\r\n\tif (num1 == \"\" && num2 == \"\") {\r\n\t\tresult == \"0\";\r\n\t} \r\n\telse if (num1==0){result = num2}\r\n\telse if (num2==0){result = num1}\r\n\telse{\r\n\t\tresult = eval(num1 + operator + num2);\r\n\t\tif (isFinite(result) && !isNaN(result)){\r\n\t\t\tnum1 = String(result);\r\n\t\t\tdisplay.value = num1 = Math.round(num1*1000000000)/1000000000;\r\n\t\t} else {\r\n\t\t\tdisplay.value = \"ERROR\"\r\n\t\t}\r\n\t}\r\n\tnum2 = operator = \"\";\r\n\tconsole.log(\"num1 \" + num1);\r\n\tconsole.log(\"operator \"+ operator);\r\n\tconsole.log(\"num2 \" + num2);\r\n\tconsole.log(\"result \" + result);\r\n}", "function multiCalc(sym) {\n switch (sym) {\n case '+':\n num1 = Number(num1) + Number(num2);\n num2 = '';\n break;\n case '-':\n num1 = Number(num1) - Number(num2);\n num2 = '';\n break;\n case '/':\n num1 = Number(num1) / Number(num2);\n num2 = '';\n break;\n case '*':\n num1 = Number(num1) * Number(num2);\n num2 = '';\n }\n}", "function handleOperator(operator){\n\n\t// Prevent user from trying to pass '=' as first operator (e.g. 1=)\n\tif (calculation['operator'] == \"=\"){\n\t\tcalculation['operator'] = '';\t\n\t}\n\t\n\t\n\t// Triggers when there are two numbers and first operator (e.g. 1+1)\n\t// Call operate function which get result and displays it\n\tif (calculation['operand'] && calculation['operator'] && calculation['operand2']){\n\t\tcalculation['operator2'] = operator\n\t\t\n\t\toperate()\n\t\n\t// Triggers when there are one number and first operator (e.g 1+)\n\t// Changing the actual operator \n\t}else if (calculation['operand'] && calculation['operator']){\n\t\tcalculation['operator'] = operator;\n\t\n\t// Triggers when there is one number (e.g. 1)\n\t// Setting operator\n\t// This and above case could be in one line but are divided for clarity\n\t}else if (calculation['operand']){\n\t\tcalculation['operator'] = operator;\n\t}\n}", "function calculator(a, op, b) {\nif (op == '/' && b === 0) return \"Can't divide by 0!\"\nif (op == '+') return a + b;\nif (op == '*') return a * b;\nif (op == '-') return a - b;\nif (op == '/') return a / b; \n}", "function myCalculator(firstNumber, secondNumber, enteredOperator){\nif(enteredOperator == \"add\"){\n console.log(\"Gives the result of: \" + addTwoNumbers(firstNumber, secondNumber));\n} else if(enteredOperator == \"sub\"){\n console.log(\"Gives the result of: \"+ subTwoNumbers(firstNumber, secondNumber));\n}else if(enteredOperator == \"mul\"){\n console.log(\"Gives the result of: \" + mulTwoNumbers(firstNumber, secondNumber));\n} else if(enteredOperator == \"div\"){\n console.log(\"Gives the result of: \" + divTwoNumbers(firstNumber, secondNumber));\n}\n}", "function calculator (value1, value2, operation) {\n var result=0\n\n if (operation== 'addition') {\n\n result = value1 + value2 \n\n } else if (operation== 'subtraction') {\n result= value1 - value2\n } else if (operation== 'multiplication') {\n result= value1 * value2\n \n } else if (operation== 'division') {\n result= value1 / value2\n\n } else {\n result='Please insert a correct operation'\n }\n return result\n}", "function mathOperation(a, b, operation) {\n\tswitch (operation) {\n\t\tcase \"+\":\n\t\t\treturn summation(a, b);\n\t\tcase \"-\":\n\t\t\treturn substraction(a, b);\n\t\tcase \"*\":\n\t\t\treturn multiplication(a, b);\n\t\tcase \"/\":\n\t\t\treturn division(a, b);\n\t\tdefault:\n\t\t\talert(\"Введите в operation: [+, -, *, /]\");\n\t\t\treturn NaN;\n\t}\n}", "function operator(op)\n{\n if(op=='+' || op=='-' || op=='^' || op=='*' || op=='/' || op=='(' || op==')')\n {\n return true;\n }\n else\n return false;\n}", "function elementArithmetic(id1,id2,out_id,operator) {\n var value1 = +document.getElementById(id1).value;\n if (value1 != value1) {add_class('invalid-field',id1)}\n var value2 = +document.getElementById(id2).value;\n if (value2 != value2) {add_class('invalid-field',id2)}\n var out_elm = document.getElementById(out_id);\n //\n if (operator == '+') {\n out_elm.value = value1 + value2\n }\n else if (operator == '-') {\n out_elm.value = value1 - value2\n }\n else if (operator == '*') {\n out_elm.value = value1 * value2\n }\n else if (operator == '/') {\n out_elm.value = value1 / value2\n }\n else {\n console.log('Unknown operator: '+operator);\n }\n}", "function evaluate(x,op,y){\n if(op == \"+\") return x+y;\n if(op == \"-\") return x-y;\n if(op == \"X\") return x*y;\n else return x/y;\n\n}", "function checkOp(){\r\n if(op==\"+\"){\r\n realAnswer=num1+num2;\r\n }else if(op==\"-\"){\r\n realAnswer=num1-num2;\r\n }else if(op==\"*\"){\r\n realAnswer=num1*num2;\r\n }else{\r\n if(num1%num2!==0){\r\n numbers();\r\n }\r\n\r\n realAnswer=num1/num2;\r\n }\r\n}", "function operations(typeOperator) {\n\t\n\tif(typeOperator=='comma' && v!='v'){\n\t\tresText=resText+\".\";\n\t\tv='v';\n\t\tdv=1;\n\t\tanimateButtons('comma');\n\t}else if(typeOperator!='comma'){\n\t\tv='f';\n\t}\n\n\tif(typeOperator==\"sum\"){\n\t\tresText=resText+\"+\";\n\t\tanimateButtons('sum');\t \n\t}else if(typeOperator==\"minus\"){\n\t\tresText=resText+\"-\";\n\t\tanimateButtons('minus');\n\n\n\t}else if(typeOperator==\"times\"){\n\t\tresText=\"ans\"+\"×\";\n\t\tanimateButtons('times');\n\n\n\t}else if(typeOperator==\"divided\"){\n\t\tresText=\"ans\"+\"÷\";\n\t\tanimateButtons('divided');\n\n\t}\n\n\n\tif(typeOperator!='comma'){\n\n\t\tif(prevTypeOperator=='sum'){\n\t\t\tresNum=numberInstMemo+resNum;\n\t\t\tnumberInstMemo=0;\n\n\t\t}else if(prevTypeOperator=='minus'){\n\t\t\tresNum=resNum-numberInstMemo;\n\t\t\tnumberInstMemo=0;\n\n\t\t}else if(prevTypeOperator=='times' && d!=0){\n\t\t\tresNum=resNum*numberInstMemo;\n\t\t\tnumberInstMemo=0; \n\n\t\t}else if(prevTypeOperator=='divided' && d!=0){\n\t\t\tresNum=resNum/numberInstMemo;\n\t\t\tnumberInstMemo=0; \n\n\t\t}\n\n\t\tprevTypeOperator=typeOperator;\n\t\t\n\t}\n\t\n\t\n\tif(typeOperator=='equal'){\n\n\t\tresText='ans';\n\t\tanimateButtons('equal');\n\t\t\n\t}\n\n\tdocument.getElementById(\"resText\").innerHTML = resText;\n\tdocument.getElementById(\"resNum\").innerHTML = resNum;\n\t\n\td=0;\n\n\n}", "function calculateNum(firstNumber, operator, secondNumber) {\n if (operator === '+') { //.toFixed to round to 1 decimal point\n result = (firstNumber + secondNumber).toFixed(1);\n } else if (operator === '-') {\n result = (firstNumber - secondNumber).toFixed(1);\n } else if (operator === '*') {\n result = (firstNumber * secondNumber).toFixed(1);\n } else if (operator === '/') {\n result = (firstNumber / secondNumber).toFixed(1);\n }\n return result;\n}", "function checkOperator()\n{\n if (operator === `+`)\n { \n additionValue = inputArray.join(``);\n additionValue = parseFloat(additionValue);\n\n addition(additionValue);\n\n updateDisplay(total);\n resetArray();\n }\n else if (operator === `-`)\n {\n subtractionValue = inputArray.join(``);\n subtractionValue = parseFloat(subtractionValue);\n\n subtraction(subtractionValue);\n\n updateDisplay(total);\n resetArray();\n }\n else if (operator === `X`)\n {\n multiplicationValue = inputArray.join(``);\n multiplicationValue = parseFloat(multiplicationValue);\n\n multiplication(multiplicationValue);\n\n updateDisplay(total);\n resetArray();\n }\n else if (operator === `/`)\n {\n divisionValue = inputArray.join(``);\n divisionValue = parseFloat(divisionValue);\n\n division(divisionValue);\n\n updateDisplay(total);\n resetArray();\n }\n}", "function calc(){\n var a = parseFloat(document.getElementById('numbera').value);\n var b = parseFloat(document.getElementById('numberb').value);\n\n\n if (document.getElementById('operator').value == '+'){\n var res = a+b;\n\n }else if (document.getElementById('operator').value == '-'){\n var res = a-b;\n\n }else if (document.getElementById('operator').value == '*'){\n var res = a*b;\n\n }else {\n var res = a/b;\n }\n document.getElementById('result').innerHTML = res;\n\n\n}" ]
[ "0.8473871", "0.8417985", "0.8371187", "0.8349881", "0.8339949", "0.83288884", "0.83181113", "0.82958806", "0.8201051", "0.81657624", "0.8145202", "0.8034015", "0.8008417", "0.7982836", "0.7966775", "0.78906846", "0.7878468", "0.7877396", "0.78534144", "0.7851636", "0.7843367", "0.783863", "0.78221124", "0.77989584", "0.77796054", "0.7772752", "0.77515334", "0.77472353", "0.7744173", "0.77401334", "0.76998425", "0.7683835", "0.76757586", "0.76694876", "0.7666157", "0.76315767", "0.76282007", "0.7627551", "0.7624893", "0.7624109", "0.7623875", "0.76183426", "0.7611336", "0.76080155", "0.7575807", "0.7572684", "0.7557744", "0.7553278", "0.75525546", "0.75424117", "0.7506971", "0.750033", "0.74983263", "0.7497976", "0.7494538", "0.74712276", "0.74712276", "0.7463265", "0.7437359", "0.7424908", "0.7422101", "0.74132985", "0.73996294", "0.7398379", "0.7390519", "0.73903346", "0.7389901", "0.7382257", "0.737429", "0.736399", "0.736399", "0.73569834", "0.7341553", "0.73390794", "0.7335079", "0.73137486", "0.7297159", "0.72959614", "0.7283628", "0.72765464", "0.7246033", "0.72441727", "0.7243375", "0.7241864", "0.7236306", "0.72281903", "0.7224203", "0.7201604", "0.7200308", "0.71818095", "0.7180905", "0.7176719", "0.716339", "0.7157671", "0.71217996", "0.7111582", "0.7108365", "0.7094383", "0.70887864", "0.7088259" ]
0.7821531
23
Basic Hello World function
function greet(){ return "hello world!" }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function sayHello() {\n console.log('Hello, ' + name);\n }", "function greet (name) {\n console.log ('Hello World')\n}", "function sayHello() {\n console.log(\"Hello World!!\");\n}", "function sayhello(){\nconsole.log('Hello World!')\n}", "function helloWorld() {\n\tconsole.log('Hello, World!');\n}", "function hello() {\n\treturn \"Hello, world!\"\n}", "function hello() {\n console.log('hello world');\n }", "function sayHello() {\n console.log('Hello world!');\n}", "function sayHello() {\n console.log('hello world');\n}", "function sayHello() {\n\tvar greeting = \"Hello \" + name;\n\tconsole.log(greeting);\n}", "function helloWorld(name) {\r\n return \"hello world, \" + name\r\n}", "function sayHello() {\n console.log('Welcome to Javascript City!');\n}", "function sayHello(name) { \n console.log(\"Hello, \"+name);\n }", "function greet () {\n console.log(`Hello.`);\n}", "function simpleGreeting() {\n console.log(\"Hello Betty\");\n}", "function greeting() {\n console.log(\"Hello World\");\n}", "function sayHello(){\n console.log(\"hello!\");\n }", "function sayHello() {}", "helloWorld () {\n console.log('hello world!')\n }", "function sayHello() {\n return \"Hello World!\";\n}", "function helloWorld() {\n console.log('Hello, World!');\n}", "function helloWorld() {\n console.log('Hello, World!');\n}", "function helloWorld(){\n console.log(\"Hello World11\");\n}", "function hello() {\r\n\tconsole.log(\"Hello World!\");\r\n}", "function helloWorld () {\n return \"Hello World\";\n}", "function helloWorld() {\n console.log('Hello world!');\n}", "function helloWorld() {\n console.log(\"Hello world!\");\n}", "function SayHello1(){\n console.log(\"hello world\");\n}", "function sayHello () {\n return \"Hello World!\";\n}", "function sayHello() {\n return \"Hello World !\";\n}", "function sayHello(){}", "function helloWorld() {\n return \"Hello World\";\n}", "function sayHello(){\n return \"Hello World\"\n}", "function sayHello() {\n\tconsole.log(\"Hello\");\n}", "function sayHello(name) {\n\t\tconsole.log(\"Hello, my name is \" + name);\n\t}", "function main() {\n return 'Hello, World!';\n}", "function sayHello(name) {\n console.log(\"Hello\" + name);\n\n }", "function greet(name, lastName) {\n console.log('Hello World' + name + ' ' + lastName);\n}", "function greeter01(name) {\n return \"Hello, \" + name;\n}", "function printHello() {\n console.log( \"Hello, World!\");\n }", "function sayHello(name) {\r\n return \"Hello \" + name;\r\n}", "function hello(){\r\n\tconsole.log(\"Hello World\");\r\n}", "function hello() {\n console.log(\"Hello, World\");\n}", "function helloWorld() {\n return \"Hello world!\";\n}", "function greet() {\n console.log(\"Hello!\");\n}", "function sayHello (){\n console.log('hello!');\n}", "function sayHello() {\n console.log('Hello');\n}", "function sayHello() {\n console.log(\"Hello\");\n }", "function sayHello(name) {\n\treturn \"Hello \" + name + \"!\";\n}", "function sayHello(name) {\n console.log('Hello ' + name);\n\n}", "function hello() {\n console.log('Hello world!')\n}", "function sayHello() {\r\n console.log(\"Hello\")\r\n}", "function sayHello (name){\n\tconsole.log(\"hello there \" + name + \"!\");\n}", "function sayHello() {\n console.log(\"Hello!\");\n}", "function sayHello() {\n console.log(\"Hello!\");\n}", "function sayHello() {\n console.log('Hello!');\n}", "function hello()\n{\n console.log('Hello World!');\n}", "function printHello(){\n console.log(\"Hello World\");\n}", "function sayHello() {\n console.log('sayHello');\n}", "function greeting(){\n\tconsole.log(\"hello\");\n}", "function sayHello() {\n console.log(\"Hello\");\n}", "function sayHello() {\n console.log(\"Hello\");\n}", "function greet(){\n\tconsole.log(\"Hello\");\n}", "function greeting() {\n console.log(\"Hello Students.\");\n}", "function sayHello() {\n console.log('Hello');\n}", "function sayHello() {\r\n console.log(\"hello 1\");\r\n}", "function sayHello(name) {\n console.log(\"Hello \" + name + \"!\");\n}", "function sayHello() {\n console.log(\"Hello\");\n}", "function greet() {\n console.log(\"Hello there!\");\n}", "static helloWorld() {\r\n console.log('Hi there!');\r\n }", "function helloWorld() {\n return \"hello world\";\n}", "function helloWorld() {\n console.log('hello');\n}", "function sayHello(name) {\n return \"hello \" + name;\n}", "function helloErica() {\n console.log(\"Hello Erica!!\")\n }", "function sayHello (){\n console.log(\"hello\");\n}", "function hello(name) {\n\tconsole.log(\"Hello \" + name + \"!\");\n}", "function hello() {\n console.log(\"Hello, world!\");\n}", "function greet(name) {\n console.log('hello ' + name);\n}", "function sayHello1(name) {\n console.log(\"xin chao ban \" + name);\n}", "function sayHello(){\n console.log('hello');\n}", "function printHello(){\n console.log( \"Hello, World!\");\n}", "function sayHello() {\n console.log( 'Hello there!' );\n}", "function sayHelloWorld() {\n return helloWorld;\n}", "static helloWorld() {\n console.log('Hi there');\n }", "function sayHello() {\n console.log(\"Hi\");\n}", "function sayHi(name){\n\tconsole.log(\"Hello \" + name);\n}", "function hello(name) {\n console.log('Hello, World! My name is ' + name + '.')\n}", "sayHello() {\n return 'Hello,Molecular'\n }", "function greet(){\r\n console.log(\"Hello there!\");\r\n}", "function greet(){\r\n console.log('Hello Bellow');\r\n}", "function sayHello() {\n console.log('hello world .. this is my first function');\n}", "function sayHelloTo(name) {\n var message = \"Welcome to Javascript City \" + name + \"!\";\n console.log(message);\n}", "function sayHello(name) {\n return \"Hello, \" + name + \"!\";\n}", "function sayHello() {\n console.log(\"Hi\");\n}", "function hello(name) {\n console.log('Hello ' + name)\n}", "function welcome(name)\r\n{\r\n console.log(\"Hello, Welcome \",name);\r\n}", "function sayHi() {\n console.log('>> Hi')\n }", "function greet(name){\r\n console.log(\"hello \" + name + \" :)\");\r\n}", "function sayHello(name) {\n console.log(\"Hello\" + \" \" + name);\n\n}", "function sayHello(name) {\n return \"Hello, \" + name + \"!\"\n\n}" ]
[ "0.76628757", "0.7622883", "0.7593462", "0.7556521", "0.7513592", "0.75128376", "0.7504352", "0.745953", "0.7444117", "0.74412364", "0.74350256", "0.7434837", "0.7425533", "0.7418798", "0.7405245", "0.74043167", "0.73732007", "0.736835", "0.73586845", "0.7320423", "0.73132557", "0.73132557", "0.7312913", "0.7306314", "0.7302368", "0.7300261", "0.72985953", "0.7296582", "0.72952706", "0.7283399", "0.7281954", "0.727667", "0.7260199", "0.72550374", "0.7245601", "0.7232312", "0.7232008", "0.7221531", "0.7211942", "0.7198093", "0.71973383", "0.71957767", "0.71824557", "0.7167815", "0.71674496", "0.71581197", "0.71557474", "0.714733", "0.7147101", "0.71456003", "0.71454465", "0.7143129", "0.71337855", "0.71304494", "0.71304494", "0.71303034", "0.71294904", "0.7126097", "0.7124635", "0.7122357", "0.711967", "0.711967", "0.71076816", "0.7107587", "0.71048236", "0.70971286", "0.70947105", "0.7087003", "0.7084671", "0.70824045", "0.7080088", "0.7075659", "0.70693094", "0.7068061", "0.70646745", "0.70597184", "0.7057142", "0.7056467", "0.7054305", "0.7053581", "0.7051089", "0.7048661", "0.7044748", "0.7033105", "0.7026283", "0.70260644", "0.7025269", "0.7023291", "0.7022136", "0.70213515", "0.7020071", "0.7008858", "0.69952846", "0.6994469", "0.6993576", "0.6991551", "0.6986412", "0.69810075", "0.6980201", "0.697774" ]
0.6990889
96
Check to see if number is even or odd
function even_or_odd(number) { if (number % 2 === 0) { return "Even" } else { return "Odd" } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function oddChecker(num){\n\treturn num % 2 !== 0\n}", "function checkEven(number) {\n return +number % 2 === 0;\n }", "function evenIs(num){\n\treturn num % 2 == 0;\n}", "function even(number)\r\n{\r\n\treturn (number % 2) == 0\r\n}", "function even(number)\r\n{\r\n\treturn (number % 2) == 0\r\n}", "function checkEvenNumber(num) {\n return num % 2 === 0;\n}", "function isNumberOdd(number) {\r\n return number % 2 !== 0\r\n\r\n}", "function odd(n) {\n return n % 2 !== 0;\n }", "function isEven(number) {\n return number % 2 === 0;\n }", "function evenOrOdd(number) {\n return isEven(number) == \"EVEN\" ? isEven(number) : isOdd(number);\n}", "function isEven(number) {\n\t\t return number % 2 === 0;\n\t\t}", "function is_even(num) {\n return num % 2 == 0;\n}", "function isEven(num) {\n return (num % 2 == 0);\n }", "function odd (n) {\n\t return n % 2 === 1\n\t}", "function isOdd(num) { return num % 2; }", "function even_or_odd (num){\n\tvar tester = num % 2;\n\tif(tester === 0){\n\t\tconsole.log(\"the value passed is even\");\n\t}\n\telse if (tester === 1){\n\t\tconsole.log(\"the value passed is odd\");\n\t}\n\telse{\n\t\tconsole.log(\"enter a number\");\n\t}\n}", "function is_even(num) {\n if (num % 2 !== 0) {\n return false;\n }\n return true;\n}", "function even(num){\n return (num % 2 == 0);\n}", "function is_even(num) {\n if (num % 2 != 0) {\n return false\n } else {\n return true\n }\n}", "function isEven(number)\n{\n return 0 == (number % 2);\n}", "function isOdd(num) { return num % 2;}", "function isOdd(num) { return num % 2;}", "function isOdd(num) { return num % 2;}", "function isEven(number) {\n if (number % 2 === 0) { // 1\n return true // 1\n } else { // 1\n return false // 1\n }\n}", "function isEven(number) {\n return number % 2 == 0 \n}", "function isEven(num) {\n return num % 2 === 0\n}", "function isOdd(number){\n return number %2 === 1 ? true : false\n}", "function isEven(num) {\n return (num % 2 === 0);\n}", "isEven($number) {\n return $number % 2 === 0;\n }", "function isEven(num) {\n return num % 2 === 0\n}", "function checkOddEven(num){\n if(!Number.isInteger(num)){\n console.log(\"invalid\")\n }\n else{\n let isEven = num % 2 === 0;\n console.log(isEven ? 'even' : 'odd');\n }\n }", "function isEvenNumber(n) {\n return n % 2 === 0; // 1\n}", "function even(n) {\n return n % 2 === 0;\n }", "function odd (data) {\n return integer(data) && data % 2 !== 0;\n }", "function isEven(number) {\n if (number % 2 == 0) {\n console.log(\"EVEN\")\n }\n else {\n console.log(\"ODD\")\n }\n}", "function is_even(num){\n if(num % 2 == 0){\n return true;\n }\n return false;\n}", "function even (n) {\n\t return n % 2 === 0\n\t}", "function isEven(num) {\n return num % 2 === 0;\n}", "function isEven(num) {\n return num % 2 === 0;\n}", "function isOdd(num) {\n return num % 2 !== 0;\n}", "function isOdd(n) {\n return n % 2 !== 0;\n}", "function isOdd(number)\n{\n return 1 == (Math.abs(number) % 2);\n}", "function isEven(num) {\n return num % 2 === 0;\n}", "function isEven(num) {\n return num % 2 === 0;\n}", "function isEven(num) {\n return num % 2 === 0;\n}", "function isEven(num) {\n return num % 2 === 0;\n}", "function isOdd(num) {\n return num % 2 !== 0;\n}", "function isOdd(num){\r\n return num %2;\r\n}", "function odd(num){\n return !even(num)\n}", "function isEven(n) {\n return n %2 === 0\n}", "function isEven(num){\n\treturn num % 2===0; // is true or false statement\n}", "function isEven(num) {\n return num % 2 === 0 ? true: false;\n}", "function isEven(num) {\n return (num % 2 == 0);\n}", "function sc_isEven(x) {\n return (x % 2 === 0);\n}", "function evenOrOdd(number) {\n if (!Number.isInteger(number)) {\n console.log('This is not an integer.') \n return; // must return, otherwise continue evaluates next if statement\n }\n if (number % 2 === 0) {\n console.log('even');\n } else {\n console.log('odd');\n } \n }", "function isOdd (number) {\n return number % 2 === 1;\n}", "function isOdd(num) {\n return num % 2 !== 0 ? true: false;\n}", "function isEven(num) {\n return num % 2 == 0\n}", "function isEven(number) {\n if(number%2 ===0) {\n return true \n } else {\n return false;\n }\n}", "function isOdd(number) {\n return number % 2 === 1;\n}", "function isEven( number ) {\n if( number % 2 === 0 ) {\n return true;\n } else {\n return false;\n }\n}", "function isEven(num) {\n if(num%2 === 0){ //if remainder of num is 0 after modulo operator, return true.\n return true;\n }\n else return false;\n}", "function isOdd(numOdd){\n return numOdd % 2 != 0;\n }", "function isOdd(num) {\n return (Math.abs(num) % 2 !== 0);\n}", "function checkEven (number){\n if (number %2 == 0){\n return true;\n } else {\n return false;\n }\n}", "function isEven(num){\n console.log(\"num =\" + num);\n return num%2 ==0;\n }", "function isEven(num) {\n return num % 2 == 0;\n}", "function isOdd(n) {\n return Math.abs(n % 2) == 1;\n}", "function even (data) {\n return number(data) && data % 2 === 0;\n }", "function isEven(num) {\n return num % 2 == 0;\n}", "function isEven(numero) {\n var even= (numero%2)==(0);\n return even;\n\n }", "function isOdd (number) {\nif (number % 2 > 0){\n return true;\n}\nelse {\n return false;\n}\n}", "function sc_isOdd(x) {\n return (x % 2 === 1);\n}", "function isEven(val){\n return val % 2 === 0;\n }", "function isEven(number) {\n if (number %2) {\n console.log(\"This number is Odd\");\n }\n else {\n console.log(\"This number is Even\");\n }\n\n}", "function isEven(number) {\n if (number % 2 === 0) {\n return true;\n }\n else {\n return false;\n }\n}", "function isEven(number) {\n\n}", "function odd(x){\r\n return x % 2 == 1;\r\n}", "function isEven(number) {\n if (number % 2 == 0) {\n return true;\n\n }\n return false;\n \n}", "function IsEven(num) {\n if (num % 2 === 0) {\n return true;\n } else {\n return false;\n }\n}", "function isEvenOrOdd(num) {\n return num % 2 === 0 ? \"even\":\"odd\";\n }", "function isEven(num){\n\tif (num % 2===0){\n\t\treturn true;\n\t}\n\t\t\telse{\n\t\t\t\treturn false\n\t\t\t}\n\t\t}", "function isEven(number) {\n if (number % 2 == 0) {\n return true;\n } else {\n return false;\n }\n}", "function isEven(number) {\n if (number % 2 == 0) {\n return true;\n } else {\n return false;\n }\n}", "function isEven(n) {\n return n % 2 === 0;\n }", "function isOdd(n) {\n\t\treturn Math.abs(n % 2) == 1;\n\t}", "function isEven (value) {\n\treturn value % 2 == 0\n}", "function isOdd(num) {\n return (num % 2 == 1);\n}", "function isEven (num) {\n\tif (num % 2 === 0) {\n\t\treturn num;\n\t}\n}", "function even (data) {\n return typeof data === 'number' && data % 2 === 0;\n }", "function isEven(num) {\n\n}", "function isEven(num) {\n if (num % 2 === 0){\n return true;\n } else {\n return false;\n }\n}", "function isEven(num) {\n if (num % 2 === 0) {\n return true;\n } else {\n return false;\n }\n}", "function oddNumber (x) {\n if (x % 2 === 1) {\n return true;\n } else {\n return false;\n }\n}", "function negativeOrEven(num) {\n return (num % 2 === 0 || num < 0)\n}", "function isEven(num) {\n if (num % 2 === 0) {\n return true;\n }\n return false;\n}", "function isEven(num) {\n if (num % 2 === 0) {\n return true;\n }\n return false;\n}", "function isEven(value) {\n\treturn (value%2 == 0);\n}", "function oddOrEven(num) {\n if ( num % 2 == 0) {\n\tconsole.log('Even');\n} else {\n\tconsole.log('Odd');\n}\n}", "function isEven(n) {\n\treturn (n % 2 == 0);\n}", "function oddorEven(num1) {\n return num1 % 2;\n}" ]
[ "0.84871453", "0.8484009", "0.8453357", "0.84017587", "0.84017587", "0.8394394", "0.8365725", "0.8348935", "0.8285799", "0.8272562", "0.8261641", "0.8251474", "0.82507724", "0.8250133", "0.8243307", "0.8234787", "0.8230105", "0.82252955", "0.82113045", "0.820456", "0.82021", "0.82021", "0.82021", "0.81862545", "0.8186249", "0.81860316", "0.8180469", "0.8178828", "0.8170921", "0.8169492", "0.81521463", "0.81498617", "0.8145813", "0.814163", "0.8133421", "0.8126567", "0.81248564", "0.8123875", "0.8123875", "0.81238216", "0.8123706", "0.81222814", "0.81191653", "0.81191653", "0.81191653", "0.81191653", "0.81179494", "0.8100813", "0.8099567", "0.80974835", "0.8096917", "0.80915153", "0.80881554", "0.8086371", "0.80863386", "0.8076963", "0.80736184", "0.8071464", "0.80697775", "0.80675286", "0.80634505", "0.80633736", "0.8058932", "0.80561215", "0.8051307", "0.80449265", "0.8036886", "0.8033566", "0.8030981", "0.8026562", "0.8021846", "0.80113107", "0.80052114", "0.8002431", "0.80002606", "0.7995177", "0.7985509", "0.79726243", "0.7971318", "0.79593915", "0.7958352", "0.7947738", "0.79466176", "0.79466176", "0.79396236", "0.7939138", "0.79388916", "0.7938079", "0.7937422", "0.79364425", "0.7935364", "0.7932377", "0.792952", "0.79274374", "0.79265743", "0.7921792", "0.7921792", "0.7917528", "0.79161716", "0.79112655", "0.79054916" ]
0.0
-1
given camelCasing string, return with spaces
function solution(string) { let arr = string.split('') let arr2 = [] for (i = 0; i < arr.length; i++) { if (arr[i] === arr[i].toUpperCase()) { arr2.push(' ', arr[i]) } else { arr2.push(arr[i]) } } console.log(arr2.join("")) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function camelCasizza(s) {\r\r\n s = s.toLowerCase()\r\r\n var c = s[0].toUpperCase();\r\r\n return c + s.substring(1, s.length);\r\r\n}", "function camelCase(text){\n let words = text.split(\" \");\n var ans=\"\";\n for(var j=0;j<words.length;j++){\n ans += words[j].substr(0,1).toUpperCase();\n ans += words[j].substr(1,)\n ans += \" \";\n }\n return ans;\n}", "function camel(s) {\n\t\t\t\treturn s.charAt(0).toUpperCase() + s.slice(1);\n\t\t\t}", "function camelCase(str) {\n return str.replace(/\\W+(.)/g, function(str)\n {\n return str.toUpperCase();\n });\n}", "function camelCase(str){return str.replace(/-[a-z]/g,function(str){return str.charAt(1).toUpperCase();});}", "function camelCase(s) {\n return s.toLowerCase().replace(/-(.)/g, function (m, g) {\n return g.toUpperCase();\n });\n }", "function camelCase(string) {\n var stringArr = string.split('');\n var newString = '';\n\n if (stringArr[0] === ' ') {\n stringArr.splice(0, 1);\n } else if (string === '') {\n return string;\n }\n\n for (i = stringArr.length - 1; i > 0; i--) {\n if (/\\s/.test(stringArr[i-1]) === true) {\n newString += stringArr[i].toUpperCase();\n } else if (/\\s/.test(stringArr[i]) === false) {\n newString += stringArr[i];\n }\n }\n newString += stringArr[0].toUpperCase();\n return newString.split('').reverse().join('');\n}", "camelize(s){\n return s.replace (/(?:^|[-_])(\\w)/g, function (_, c) {\n return c ? c.toUpperCase () : '';\n })\n }", "function camelizingStrings ( strInput ){\n var strToArr = strInput.split(' ');\n var firstLetterUpperNoSpaces = strToArr.map( elem => \n elem[0].toUpperCase() + elem.slice(1)\n ).join('');\n return `The camelcase version of ${strInput} is :${firstLetterUpperNoSpaces}`;\n}", "function camelCase(str) {\n return str.replace(/[_.-](\\w|$)/g, function (_, x) { return x.toUpperCase(); });\n}", "function camelCase$2(s) {\n // Convert first character to lowercase\n return s.replace(/^\\w/, function (match) {\n return match.toLowerCase();\n }).replace(/-\\w/g, function (match) {\n return match.charAt(1).toUpperCase();\n });\n}", "function camelCase(s) {\r\n return s.toLowerCase().replace(/-(.)/g, function(m, g) {\r\n return g.toUpperCase()\r\n })\r\n}", "function camelCase(s) {\n return s.replace(/-\\w/g, function (match) {\n return match.charAt(1).toUpperCase();\n });\n }", "function capitalize(str) {}", "function camelCase(s) {\n return s.replace(/-\\w/g, function (match) {\n return match.charAt(1).toUpperCase();\n });\n}", "function camelCase(s) {\n return s.toLowerCase().replace(/-(.)/g, function(m, g) {\n return g.toUpperCase()\n })\n}", "function camelCase(s) {\n return s.toLowerCase().replace(/-(.)/g, function(m, g) {\n return g.toUpperCase()\n })\n}", "function sc_string_capitalize(s) {\n return s.replace(/\\w+/g, function (w) {\n\t return w.charAt(0).toUpperCase() + w.substr(1).toLowerCase();\n });\n}", "function camelCase(string) {\n return string.replace(/\\-(\\w{1})/g, function(full, match) {\n return match.toUpperCase();\n });\n }", "function camelCase(str) {\r\n // Replace special characters with a space\r\n str = str.replace(/[^a-zA-Z0-9 ]/g, ' ');\r\n // put a space before an uppercase letter\r\n str = str.replace(/([a-z](?=[A-Z]))/g, '$1 ');\r\n // Lower case first character and some other stuff\r\n str = str.replace(/([^a-zA-Z0-9 ])|^[0-9]+/g, '').trim().toLowerCase();\r\n // uppercase characters preceded by a space or number\r\n str = str.replace(/([ 0-9]+)([a-zA-Z])/g, function (a, b, c) {\r\n return b.trim() + c.toUpperCase();\r\n });\r\n return str;\r\n}", "function camelCase(string){return string.replace(rmsPrefix,\"ms-\").replace(rdashAlpha,fcamelCase);}", "function camelCase(str) {\n // Replace special characters with a space\n str = str.replace(/[^a-zA-Z0-9 ]/g, ' ');\n // put a space before an uppercase letter\n str = str.replace(/([a-z](?=[A-Z]))/g, '$1 ');\n // Lower case first character and some other stuff\n str = str.replace(/([^a-zA-Z0-9 ])|^[0-9]+/g, '').trim().toLowerCase();\n // uppercase characters preceded by a space or number\n str = str.replace(/([ 0-9]+)([a-zA-Z])/g, function (a, b, c) {\n return b.trim() + c.toUpperCase();\n });\n return str;\n}", "function camelCase(string) {\n var find = /(\\_\\w)/g;\n var convert = function convert(matches) {\n return matches[1].toUpperCase();\n };\n return string.replace(find, convert);\n}", "function camelCase(name){return name.charAt(0).toUpperCase()+name.slice(1).replace(/-(\\w)/g,function(m,n){return n.toUpperCase();});}", "function camelCase(str) {\n return str.replace(/[_.-](\\w|$)/g, (_, x) => x.toUpperCase());\n}", "function camelCase(str) {\n return str.replace(/(^[-_.: ]*|[-_.: ]+)(.)?/g, (match, sep, letter, index) => {\n return letter !== undefined ? index === 0 ? letter.toLowerCase() : letter.toUpperCase() : '';\n });\n}", "function toCamelCase(str) {\n return str.replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (letter, index) {\n return index === 0 ? letter.toLowerCase() : letter.toUpperCase();\n }).replace(/\\s+/g, '');\n}", "function camelCase(str) {\n return str.replace(/[_.-](\\w|$)/g, function (_, x) {\n return x.toUpperCase();\n });\n}", "function camelCase(str){\n\t str = toString(str);\n\t str = replaceAccents(str);\n\t str = removeNonWord(str)\n\t .replace(/[\\-_]/g, ' ') //convert all hyphens and underscores to spaces\n\t .replace(/\\s[a-z]/g, upperCase) //convert first char of each word to UPPERCASE\n\t .replace(/\\s+/g, '') //remove spaces\n\t .replace(/^[A-Z]/g, lowerCase); //convert first char to lowercase\n\t return str;\n\t }", "function camelCase(input) {\n input = splitString(input, ' ');\n for (var i = 0; i < input.length; i++) {\n if (i == 0) {\n input[i] = lowerCase(input[i]);\n }\n else {\n input[i] = capitalizeString(input[i]);\n }\n }\n return joinArray(input, '');\n}", "function camelCase(str){\n str = toString(str);\n str = replaceAccents(str);\n str = removeNonWord(str)\n .replace(/[\\-_]/g, ' ') //convert all hyphens and underscores to spaces\n .replace(/\\s[a-z]/g, upperCase) //convert first char of each word to UPPERCASE\n .replace(/\\s+/g, '') //remove spaces\n .replace(/^[A-Z]/g, lowerCase); //convert first char to lowercase\n return str;\n }", "function camelCase(str){\n str = toString(str);\n str = replaceAccents(str);\n str = removeNonWord(str)\n .replace(/[\\-_]/g, ' ') //convert all hyphens and underscores to spaces\n .replace(/\\s[a-z]/g, upperCase) //convert first char of each word to UPPERCASE\n .replace(/\\s+/g, '') //remove spaces\n .replace(/^[A-Z]/g, lowerCase); //convert first char to lowercase\n return str;\n }", "function camelize(str) {\n\treturn str.replace(/(?:^\\w|[A-Z]|\\b\\w|\\s+)/g, function(match, index) {\n \tif (+match === 0) return ''; // or if (/\\s+/.test(match)) for white spaces\n \treturn index == 0 ? match.toLowerCase() : match.toUpperCase();\n \t});\n}", "function camelize(str) {\n return str.replace(/(?:^\\w|[A-Z]|\\b\\w|\\s+)/g, function(match, index) {\n if (+match === 0) {\n return ''\n }\n return index == 0 ? match.toLowerCase() : match.toUpperCase()\n })\n}", "function camelize(str) {\n return str.replace(/(?:^\\w|[A-Z]|\\b\\w|\\s+)/g, function (match, index) {\n if (+match === 0)\n return '';\n return index == 0 ? match.toLowerCase() : match.toUpperCase();\n });\n}", "function camelCaseCSS(str) {\n return str.replace(/\\-([a-z])/g, \n\t\t function (whole, section) {\n\t\t\t return section.toUpperCase();\n\t\t });\n }", "function fcamelCase(all,letter){return letter.toUpperCase();}// Convert dashed to camelCase; used by the css and data modules", "function toCamelCase(str){\r\n return str.split(/_|-/).map((word, index) => \r\n index === 0 ? word : word.charAt(0).toUpperCase() + word.substring(1)).join('');\r\n }", "function camelCase (userInput) {\n // let shouldCapitalize = true;\n // let result = \"\";\n // for (let i = 0; i < userInput.length; i++) {\n // // Check for the first letter in a word, if it is, then Capitalize\n // if (userInput.charAt(i) === \" \") {\n // result += userInput.charAt(i);\n // shouldCapitalize = true;\n // }\n // else if (shouldCapitalize == true) {\n // result += userInput.charAt(i).toUpperCase();\n // shouldCapitalize = false;\n // } \n // else if (shouldCapitalize == false) {\n // result += userInput.charAt(i);\n // shouldCapitalize = false;\n // } \n // }\n let result = capitalizeWords(userInput);\n let newString = result.replaceAll( \" \", \"\");\n return newString;\n\n}", "function f(str) {\n const words = str.split(' ');\n let capitalizedWords = [];\n for (let i = 0; i < words.length; i++) {\n const capitalizedWord = words[i].charAt(0).toUpperCase() + words[i].slice(1).toLowerCase();\n capitalizedWords.push(capitalizedWord);\n }\n return capitalizedWords.join(' ');\n}", "function camelCase(name) { return name.replace(/-([a-z])/g,camelCase_replace); }", "function _toCamel(s)\n\t{\n\t\treturn String(s).replace(/(\\-[a-z])/g, function($1){\n\t\t\treturn $1.toUpperCase().replace('-','');\n\t\t});\n\t}", "function camelCase(str) {\n // Replace special characters with a space\n // eslint-disable-next-line optimize-regex/optimize-regex\n str = str.replace(/[^a-zA-Z0-9 ]/g, ' ');\n // put a space before an uppercase letter\n str = str.replace(/([a-z](?=[A-Z]))/g, '$1 ');\n // Lower case first character and some other stuff\n str = str\n // eslint-disable-next-line optimize-regex/optimize-regex\n .replace(/([^a-zA-Z0-9 ])|^[0-9]+/g, '')\n .trim()\n .toLowerCase();\n // uppercase characters preceded by a space or number\n str = str.replace(/([\\d ]+)([A-Za-z])/g, function (a, b, c) { return b.trim() + c.toUpperCase(); });\n return str;\n}", "function toCamelCase(str){\n var regExp=/[-_]\\w/ig;\n return str.replace(regExp,function(match){\n return match.charAt(1).toUpperCase();\n });\n}", "function spinalCase(str) {\n var destroyedCamelCase = str\n .replace(/([A-Z])/g, \" $1\")\n .trim()\n .toLowerCase()\n .split(\" \")\n .join(\"-\")\n .split(\"_\")\n .join(\"-\")\n .split(\"--\")\n .join(\"-\");\n // console.log(destroyedCamelCase);\n\n // var splitArr = destroyedCamelCase\n // .toLowerCase()\n // .split(\" \")\n // .join(\"-\")\n // .split(\"_\")\n // .join(\"-\")\n // .split(\"--\")\n // .join(\"-\");\n return destroyedCamelCase;\n}", "function camelCase( string ) {\n\treturn string.replace( rdashAlpha, fcamelCase );\n}", "function camelcase(val) {\n if (!is_1.isValue(val))\n return null;\n var result = val.replace(/[^A-Za-z0-9]/g, ' ').replace(/^\\w|[A-Z]|\\b\\w|\\s+/g, function (m, i) {\n if (+m === 0 || /(\\.|-|_)/.test(m))\n return '';\n return i === 0 ? m.toLowerCase() : m.toUpperCase();\n });\n return result.charAt(0).toLowerCase() + result.slice(1);\n}", "function camelCase(name) {\n var capitalized = name\n .split(/\\s|-|_/)\n // We explicitely don't lowercase the second half - it might already be in camelcase.\n .map(function (word) { return word.substring(0, 1).toUpperCase() + word.substring(1); })\n .join('');\n return lowerCase(capitalized);\n}", "function titlecase(str) {\n return str.split(' ').map((word) => word[0].toUpperCase() + word.slice(1)).join(' ');\n}", "function sentenceToCamelCase(str){\n //const m = /[0-9]*\\.?[0-9]+%\\s/ig;\n //const m2 = /^[a-zA-Z]/;\n // const m2 = /^[a-z]|[A-Z]/g; \n // const m3 = /\\s[a-zA-Z]/g;\n const m3 = /^[a-zA-Z]|\\s[a-zA-Z]/g;\n // let matchArr = str.match(m3);\n return str.replace(m3,(el,idx)=>{\n return el.trim().toUpperCase();\n })\n}", "function toCamelCase(inputStr) {\n if (typeof inputStr === 'string') {\n return inputStr.replace(/(?:^\\w|[A-Z]|\\b\\w|[\\s+\\-_\\/])/g, (match, offset) => {\n // remove white space or hypens or underscores\n if (/[\\s+\\-_\\/]/.test(match)) {\n return '';\n }\n return offset === 0 ? match.toLowerCase() : match.toUpperCase();\n });\n }\n return inputStr;\n}", "function camelize(str) {\n return str.replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function(letter, index) {\n return index == 0 ? letter.toLowerCase() : letter.toUpperCase();\n }).replace(/\\s+/g, '');\n}", "function space(x) {\n return x.replace(/([a-z])([A-Z])/g, \"$1 $2\");\n}", "function camelCaseToSentence(str){\n let str2=str\n const m1 = /[A-Z]/g;\n str2 = str2.replace(m1, (el,idx)=>{\n return ' ' + el;\n })\n return str2;\n}", "function camelize(s) {\n\t return s.replace(/-(\\w)/g, function (strMatch, p1){\n\t return p1.toUpperCase();\n\t });\n\t}", "function camelize(str) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function(word, index) {\n return index == 0 ? word.toLowerCase() : word.toUpperCase();\n })\n .replace(/\\s+/g, \"\");\n}", "function deCamelCase(str) {\n return str.replace(/([A-Z])/g, function (match) { return \" \".concat(match); }).replace(/^./, function (match) { return match.toUpperCase(); });\n}", "function camelToDasherize(string) {\n return string.replace(/([A-Z])/g, function (g) {\n return \"-\" + g.toLowerCase();\n });\n}", "function spinalCase(str) {\n var new_str = str.replace(/([a-z])([A-Z])/g, '$1 $2');\n return new_str.replace(/[\\s_]/gi, \"-\").toLowerCase();\n}", "function camelize(str) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : word.toUpperCase();\n })\n .replace(/\\s+/g, '');\n}", "function spinalCase(str) {\n\t// regex to split the string on non-word characters and spaces\n\tconst regex = /[\\W_]/g;\n\t// regex to target a lowercase letter followed by an uppercase letter\n\tconst capRegex = /([a-z])([A-Z])/g;\n\n\t// use capRegex to replace uppercase letters that don't have spaces\n\tconst temp = str.replace(capRegex, '$1 $2');\n\n\t// ma through temp and use regex to replace spaces and other chars\n\tconst newStr = temp\n\t\t.split(regex)\n\t\t.map(word => word.toLowerCase())\n\t\t.join('-');\n\n\tconsole.log('newStr:', newStr);\n\treturn newStr;\n}", "function toCamelCase(str) {\n function capitalizeFirstLetter(string) {\n return string.charAt(0).toUpperCase() + string.slice(1);\n }\n \n const words = str.split(/[\\s-_]/);\n \n return words.map(function(word) {\n if(words.indexOf(word) === 0) {\n return word;\n } else {\n return capitalizeFirstLetter(word);\n }\n }).join('');\n}", "function uncamel(str) {\n\t return str.replace(/([A-Z])/g, function(letter) { return '-' + letter.toLowerCase(); });\n\t }", "function camelToDashed(str) {\n return str.replace(/\\W+/g, '-').replace(/([a-z\\d])([A-Z])/g, '$1-$2').toLowerCase();\n}", "function uncamel(str) {\r\n\t\tif (!str.indexOf('webkit')) str = 'W' + str.substr(1);\r\n\t\tif (!str.indexOf('moz') || !str.indexOf('ms')) str = 'M' + str.substr(1);\r\n\t\treturn str.replace(/([A-Z])/g, '-$1').toLowerCase();\r\n\t}", "function titleCase(str) {return str.toLowerCase().replace(/^[a-z]|\\s[a-z]/g,\nfunction(m){return m.toUpperCase();\n });\n }", "function camelCase( string ) {\n \treturn string.replace( rmsPrefix, \"ms-\" ).replace( rdashAlpha, fcamelCase );\n }", "function caps(a) {return a.substring(0,1).toUpperCase() + a.substring(1,a.length);}", "function inName(name){\n name = name.trim().split(' ');\n console.log(name);\n name[1] = name[1].toUpperCase();\n name[0] = name[0].slice(0,1).toUpperCase() + name[0].slice(1).toLowerCase();\n return name[0] + ' ' + name[1];\n}", "function camelCase(name){return name.replace(SPECIAL_CHARS_REGEXP,function(_,separator,letter,offset){return offset?letter.toUpperCase():letter;}).replace(MOZ_HACK_REGEXP,'Moz$1');}", "function camelCaseAndCapitalise (string) {\n return capitaliseFirstLetter(camelCase(string))\n }", "function capitalise(s){\n let ns = [];\n for(let w of s.split(\" \")){\n ns.push(w[0].toUpperCase() + w.slice(1));\n }\n return ns.join(\" \");\n}", "function camelCase(str){\n if (str.length === 0 ) return \"\";\n let strLower = str.toLowerCase();\n let strArray = strLower.split(/[\\W_-]/g).filter(e=>e.length !==0);\n return strArray.join(',').replace(/,\\w/g, str => str[1].toUpperCase());\n}", "function titlecase(str){\n return str.replace(/\\w\\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});\n}", "function ucfirst(str,force){\n str=force ? str.toLowerCase() : str;\n return str.replace(/(\\b)([a-zA-Z])/,\n function(firstLetter){\n return firstLetter.toUpperCase();\n });\n }", "function deCamelCase(str) {\r\n return str\r\n .replace(/([A-Z])/g, function (match) { return \" \" + match; })\r\n .replace(/^./, function (match) { return match.toUpperCase(); });\r\n}", "function capital(str) \r\n{\r\n str = str.split(\" \");\r\n\r\n for (var i = 0, x = str.length; i < x; i++) {\r\n str[i] = str[i][0].toUpperCase() + str[i].substr(1);\r\n }\r\n\r\n return str.join(\" \");\r\n}", "function toCamelCase(str){\n // if empty string, return an empty string\n if(str === '') return ''\n // Using Regex it will replace all Non-characters with whitespace to keep the words separate\n str = str.replace(/[^a-zA-Z]+/ig, ' ')\n // split the string into an array of words\n let split = str.split(' ')\n let cap = [];\n // Loop through array and capitalize every first letter of each word\n for(let i = 0; i < split.length; i++) {\n cap.push(split[i][0].toUpperCase()+split[i].slice(1))\n }\n // check if first letter of first work in original str was lowercase and if so make that letter \n // lowercase, otherwise leave it as is\n if(str[0] === str[0].toLowerCase()) {\n cap = cap[0][0].toLowerCase()+cap[0].slice(1)+cap.slice(1)\n return cap.replace(/[^a-zA-Z]+/ig, '')\n } else {\n return cap.join('') \n }\n}", "function spinalCase(str) {\n \n var re = /\\s|_/; \n \n // Replace low-upper case to low-space-uppercase\n str = str.replace(/([a-z])([A-Z])/g, '$1 $2');\n \n str = str.split(re).join('-').toLowerCase();\n \n return str;\n}", "function sentenceCase (str) {\n return str.replace(/[a-z]/i, letter => letter.toUpperCase()).trim()\n }", "function camelCase(str, firstCapital) {\n if (firstCapital === void 0) { firstCapital = false; }\n return str.replace(/^([A-Z])|[\\s-_](\\w)/g, function (match, p1, p2, offset) {\n if (firstCapital === true && offset === 0)\n return p1;\n if (p2)\n return p2.toUpperCase();\n return p1.toLowerCase();\n });\n}", "function inName(name) {\n name = name.trim().split(\" \");\n console.log(name);\n name[1] = name[1].toUpperCase();\n name[0] = name[0].slice(0,1).toUpperCase() + name[0].slice(1).toLowerCase();\n\n return name[0] + \" \" + name[1];\n}", "function inName(name) {\n name = name.trim().split(\" \");\n console.log(name);\n name[1] = name[1].toUpperCase();\n name[0] = name[0].slice(0, 1).toUpperCase() + name[0].slice(1).toLowerCase();\n\n return name[0] + \" \" + name[1];\n}", "function inName(name) {\n name = name.trim().split(\" \");\n console.log(name);\n name[1] = name[1].toUpperCase();\n name[0] = name[0].slice(0, 1).toUpperCase() + name[0].slice(1).toLowerCase();\n\n return name[0] + \" \" + name[1];\n}", "function f(str) {\n let split = str.split('');\n let cap = [];\n cap.push(str.charAt(0).toUpperCase());\n for (l = 1; l < str.length; l++) {\n cap.push(split[l].toLowerCase());\n }\n return(cap.join(''));\n}", "function dasherizeToCamel(string) {\n return string.replace(/-([a-z])/g, function (g) {\n return g[1].toUpperCase();\n });\n}", "function capitalize( str , echo){\n var words = str.toLowerCase().split(\" \");\n for ( var i = 0; i < words.length; i++ ) {\n var j = words[i].charAt(0).toUpperCase();\n words[i] = j + words[i].substr(1);\n }\n if(typeof echo =='undefined')\n return words.join(\" \");\n else\n return str;\n}", "function toCamelCase(snakeCaseString) {\n let arrayOfTerms = snakeCaseString.split(\"_\");\n let result = \"\";\n for (let i = 0; i < arrayOfTerms.length; i++) {\n let currentWord = \"\";\n if (i != 0) {\n currentWord =\n arrayOfTerms[i].charAt(0).toUpperCase() + arrayOfTerms[i].slice(1);\n } else {\n currentWord = arrayOfTerms[i];\n }\n result += currentWord;\n }\n return result;\n}", "function inName(name){\n name = name.trim().split(\" \");\n console.log(name);\n name[1] = name[1].toUpperCase();\n name[0] = name[0].slice(0,1).toUpperCase() + name[0].slice(1).toLowerCase();\n return name[0] + \" \" + name[1];\n\n}", "function capitalize(str) {\n let capArr = [];\n let strArr = str.split(' ');\n for (var i = 0; i < strArr.length; i++) {\n capArr.push(capital(strArr[i]));\n }\n return capArr.join(' ')\n\n\n}", "function reverseThenCamelCase (str) {\n let finalString = reverseString(capitalizeWords(str));\n finalString = finalString.replaceAll(\" \", \"\");\n return finalString;\n}", "function toTitleCase(str) {\n \t\t\t\tstr = str.replace(/_/g, \" \");\n \t\t\t\treturn str.replace(/(?:^|\\s)\\w/g, function(match) {\n\n \t\t\t\t\treturn match = match.toUpperCase();\n \t\t\t\t});\n\n \t\t\t}", "function camelCase() {\n utilitymanager_1.um.utilityManager({\n utilType: utilitymanager_1.um.TIXUtilityType.utInTransform,\n sp: utilitymanager_1.um.TIXSelPolicy.Word,\n pat: /\\b(_*\\w)/g, repl: function (_match, p1) { return p1.toLowerCase(); },\n });\n }", "function toCamelCase(word) {\n return word\n .split('-')\n .map((key, index) =>\n index === 0 ? key : key.replace(/[A-Z]/i, (match) => match.toUpperCase()),\n )\n .join('');\n}", "function camelize(s) {\n return s.replace(/-(.)/g, function(m, m1) {\n return m1.toUpperCase();\n });\n }", "function fcamelCase( all, letter ) {\n return letter.toUpperCase();\n }", "function hc(myString) {\n return myString.replace(\"_\", \" \").replace(/\\b\\w/g, l => l.toUpperCase())\n}", "_camelize(_str) {\n return _str.replace(/((-)([a-z])(\\w))/g, ($0, $1, $2, $3, $4) => {\n return $3.toUpperCase() + $4;\n });\n }", "_camelize(_str) {\n return _str.replace(/((-)([a-z])(\\w))/g, ($0, $1, $2, $3, $4) => {\n return $3.toUpperCase() + $4;\n });\n }", "function snakeCaseToCamelCase(s) {\n return s.toLowerCase().replace(/(\\_\\w)/g, function(m) {return m[1].toUpperCase();});\n}", "function spinalCase(str) {\n return str.split(/\\s|_|(?=[A-Z])/).join('-').toLowerCase()\n \n}" ]
[ "0.7649266", "0.7571316", "0.75013405", "0.73361933", "0.73210734", "0.73018503", "0.7289684", "0.7285795", "0.7251961", "0.72507143", "0.7249815", "0.7240875", "0.7238265", "0.7237325", "0.72169477", "0.7215706", "0.7215706", "0.7200037", "0.7195006", "0.71870553", "0.718505", "0.71736187", "0.7164541", "0.71503043", "0.71430814", "0.71411914", "0.71156996", "0.71149576", "0.710629", "0.7083047", "0.70773673", "0.70773673", "0.70644176", "0.70346457", "0.7031049", "0.70296776", "0.702916", "0.7029159", "0.70257384", "0.7020561", "0.7015041", "0.7014658", "0.70125014", "0.7006686", "0.700159", "0.6991253", "0.6990849", "0.6988498", "0.6987124", "0.69850755", "0.6980379", "0.69784206", "0.6976001", "0.69706845", "0.6970159", "0.69608545", "0.69538814", "0.6952089", "0.6950535", "0.6945296", "0.69425124", "0.69386715", "0.6938033", "0.69299334", "0.69289476", "0.6927244", "0.6925847", "0.6921765", "0.6920466", "0.6920028", "0.69100153", "0.6908644", "0.68850577", "0.6883571", "0.6882667", "0.68778193", "0.68747574", "0.6873691", "0.68719876", "0.6868232", "0.68679285", "0.6859251", "0.6858335", "0.6858335", "0.6852823", "0.68480104", "0.684703", "0.68457866", "0.68430144", "0.68396914", "0.68392247", "0.6838125", "0.6835556", "0.68313026", "0.6831279", "0.6830247", "0.6828078", "0.68267345", "0.68267345", "0.682652", "0.6822281" ]
0.0
-1
return longest string with only 2 unique letters
function string(p1) { let string = p1.split("") let sub = [] let sub2 = [] let count = 0 for (i = 0; i < string.length; i++) { if (!sub.includes(string[i]) && count === 2) { if (sub2.length < sub.length) { sub2 = sub } count = 0 sub = [] let pos = 1 let start = string[i - 1] for (j = i-1; j > 0; j--) { if (string[j] == start) { pos++ } else { break; } } i = i - pos; } else if (sub.includes(string[i])) { sub.push(string[i]) } else if (count < 2) { sub.push(string[i]) count++ } } return sub2 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function longestPossible(s1, s2) {\n const all = (s1 + s2).split('')\n const uniqueSortedLetters = [...new Set(all)].sort()\n return uniqueSortedLetters.join('')\n}", "function longestString(strings) {\n\n}", "function longestString(longStr){\n var mostAmntOfCharacters = longStr.reduce((x,y) => x.length >= y.length ? x : y);\n return mostAmntOfCharacters\n}", "function longestSubstringWithoutRepeatingCharacters(str) {\n\n let max = '';\n\n for (let i = 0; i < str.length; i++) {\n\n let j = i;\n let current = '';\n\n while (current.indexOf(str[j]) == -1 || str[j] == ' ') {\n\n if (j == str.length) break;\n current += str[j];\n j++;\n\n }\n\n if (current.length >= max.length) {\n max = current;\n }\n\n\n }\n\n return max;\n}", "function longestWord_2(sen) {\n const regex = /[!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~]/g;\n const result = sen.replace(regex, \"\");\n let res = result.split(\" \");\n let longestWord = res[0];\n for (let i = 1; i < res.length; i++) {\n if (res[i].length > longestWord.length) {\n longestWord = res[i];\n }\n }\n return longestWord;\n}", "function longestWord(sen) {}", "function longestString (a) {\n var p = a[0];\n var q;\n for (var i = 0; i < a.length; i++) {\n q = a[i];\n if (q.length > p.length) {\n p = q;\n }\n\n }\n return p;\n}", "function find_longest_word(str)\n{\n var array1 = str.match(/\\w[a-z]{0,}/gi);\n var result = array1[0];\n\n for(var x = 1 ; x < array1.length ; x++)\n {\n if(result.length < array1[x].length)\n {\n result = array1[x];\n } \n }\n return result;\n}", "function find_longest_word(str)\n{\n var array1 = str.match(/\\w[a-z]{0,}/gi);\n var result = array1[0];\n\n for(var x = 1 ; x < array1.length ; x++)\n {\n if(result.length < array1[x].length)\n {\n result = array1[x];\n } \n }\n return result;\n}", "function find_longest_word(str)\n {\n var array1 = str.match(/\\w[a-z]{0,}/gi);\n var result = array1[0];\n\n for(var x = 1 ; x < array1.length ; x++)\n {\n if(result.length < array1[x].length)\n {\n result = array1[x];\n }\n }\n return result;\n }", "function findLongestWord2(str) {\n var longestWord = str.split(' ').reduce(function(longest, currentWord) {\n return currentWord.length > longest.length ? currentWord : longest;\n }, \"\");\n return longestWord.length;\n}", "function longestRepetition(s) {\n let count = 0;\n let prevLetter = \"\";\n\n return s\n .toLowerCase()\n .split(\"\")\n .reduce(\n (acc, curr) => {\n if (curr === prevLetter) {\n count++;\n } else {\n count = 1;\n }\n\n if (count > acc[1]) {\n acc[1] = count;\n acc[0] = curr;\n }\n\n prevLetter = curr;\n return acc;\n },\n [\"\", 0]\n );\n}", "function longest(s1, s2) {\n return [...new Set([...s1.split('') ,...s2.split('')])].sort().join().replace(/[^\\w]/g,'');\n}", "function findLongestWord(str_ara) {\n let max = str_ara[0].length;\n str_ara.map(v => max = Math.max(max, v.length));\n result = str_ara.filter(v => v.length == max);\n return result;\n}", "function longestWord(string1) {\n var sliptString = string1.split(\" \");\n return sliptString.reduce(function(prev, next) {\n if (prev.length < next.length) {\n prev = next;\n }\n return prev;\n })\n}", "function solution(S) {\n // write your code in JavaScript (Node.js 8.9.4)\n const words = S.split(\" \");\n let longest = -1;\n for (let word of words) {\n const stripped = word.replace(/[^0-9a-z]/gi, \"\");\n if (word.length === stripped.length) {\n const letters = stripped.replace(/[^a-z]/gi, \"\");\n const numbers = stripped.replace(/[^0-9]/g, \"\");\n if (letters.length % 2 === 0 && numbers.length % 2 === 1) {\n longest = Math.max(longest, letters.length + numbers.length);\n }\n }\n }\n return longest;\n}", "function lengthOfLongestSubstring(s){\n let longest = 0;\n if(s.length <=1){\n return s.length;\n }\n for(let left = 0; left < s.length; left++){\n let seenChars = {}, currentLength = 0;\n for (let right = left; right < s.length; right++) {\n const currentChar = s[right];\n if(!seenChars[currentChar]){\n currentLength++;\n seenChars[currentChar] = true;\n longest = Math.max(longest, currentLength)\n } else {\n break;\n }\n }\n }\n console.log(longest);\n}", "function twoCharaters(s) {\n let maxSize = 0;\n let duppedStr = s.slice(0);\n const chrsSet = new Set();\n\n for (let i = 0; i < s.length; i++) {\n chrsSet.add(duppedStr[i]);\n }\n\n const uniqChrs = Array.from(chrsSet);\n for (let i = 0; i < uniqChrs.length - 1; i++) {\n for (let j = i + 1; j < uniqChrs.length; j++) {\n duppedStr = duppedStr.split(\"\").filter((chr) => (chr === uniqChrs[i] || chr === uniqChrs[j])).join(\"\");\n if (validT(duppedStr)) {\n if (duppedStr.length > maxSize) {\n maxSize = duppedStr.length;\n }\n }\n duppedStr = s.slice(0);\n }\n }\n return maxSize;\n}", "function longestString(arr){\n\tvar result = \"\";\n\tfor(var i=0; i<arr.length; i++){\n\t\tif(arr[i].length >= arr[0].length){\n\t\t\tresult = arr[i];\n\t\t}\n\t}\n\treturn result;\n}", "function longestSubstringWithKdistinctCharacters(str, k) {\n let maxLength = 0;\n let charFreq = new Map();\n let windowStart = 0;\n let rightChar = '';\n let leftChar = '';\n\n for (let windowEnd = 0; windowEnd <= str.length; windowEnd++) {\n rightChar = str[windowEnd];\n\n if (!charFreq.has(rightChar)) {\n charFreq.set(rightChar, 0);\n }\n charFreq.set(rightChar, charFreq.get(rightChar) + 1);\n\n while(charFreq.size > k) {\n leftChar = str[windowStart];\n charFreq.set(leftChar, charFreq.get(leftChar) - 1);\n\n if (charFreq.get(leftChar) === 0) {\n charFreq.delete(leftChar);\n }\n windowStart += 1;\n }\n\n maxLength = Math.max(maxLength, windowEnd - windowStart + 1);\n }\n\n return maxLength;\n}", "function longest_substring_with_k_distinct(str, k){\n let windowStart = 0;\n let maxLength = 0;\n let charFrequency = new Map();\n\n for(let windowEnd = 0; windowEnd < str.length; windowEnd++){\n let rightChar = str[windowEnd];\n if(!rightChar in charFrequency){\n charFrequency[rightChar] = 0;\n }\n charFrequency[rightChar] += 1\n while(Object.keys(charFrequency).length > k){\n let leftChar = str[windowStart]\n charFrequency[leftChar] -= 1;\n if(charFrequency[leftChar] === 0){\n delete charFrequency[leftChar]\n }\n windowStart += 1\n\n }\n maxLength = Math.max(maxLength, windowEnd - windowStart + 1);\n\n }\n return maxLength;\n\n}", "function findLongestWord(str) { \r\n var word = str.split(\" \");\r\n var s = Math.max.apply(null, word.map(function(str){return str.length;}));\r\n return word.filter(function(val){\r\n return val.length == s;\r\n }) \r\n}", "function longestString(strings) {\n let max = 0;\n strings.forEach((val) => {\n if (val.length > max) {\n max = val.length;\n }\n });\n return strings.filter((val) => val.length === max);\n}", "function longestString(strings) {\n let carachters = \"\";\n strings.forEach(string => {\n if (string.length > carachters.length) {\n carachters = string;\n }\n });\n return carachters;\n //\n}", "function longest(s1, s2) {\n \n return Array.from(new Set(s1.split(\"\").concat(s2.split(\"\")).sort())).join(\"\");\n\n}", "function longestPalindrome(str) {\n\tstr = str.toLowerCase().replace(/[\\W_]/g, '');\n\tlet longest = '',\n\t\ti = 0;\n\n\twhile (i < str.length - 1) {\n\t\tlet lp = Math.floor(i - .5),\n\t\t\trp = Math.ceil(i + .5);\n\n\t\tif (!longest) longest = str[i];\n\n\t\twhile (str[lp] === str[rp] && lp >= 0 && rp < str.length) {\n\t\t\tlet pl = str.slice(lp, rp + 1);\n\t\t\tif (longest.length < pl.length) longest = pl;\n\t\t\t--lp;\n\t\t\t++rp;\n\t\t}\n\t\ti += 0.5;\n\n\t}\n\treturn longest;\n}", "function longestword(str)\r\n{\r\n var arr = str.match(/\\w[a-z]{0,}/gi)\r\n document.write(\"Example String: \"+arr+\"<br>\")\r\n var result = arr[0]\r\n for (var i = 1; i < arr.length; i++)\r\n {\r\n if (result.length < arr[i].length)\r\n {\r\n result = arr[i]\r\n }\r\n } \r\n\r\n return result\r\n\r\n}", "function longest_substring_with_k_distinct(str, k) {\n // TODO: Write code here\n\n let windowStart = 0,\n maxLength = 0,\n characterFrequency = {};\n\n if(str.length == 0 || k < 1) return 0;\n\n //extends the window \n for(let windowEnd = 0; windowEnd < str.length; windowEnd++){\n const rightCharacter = str[windowEnd]; //character at the start of the String\n\n if(!(rightCharacter in characterFrequency)) { //checks to see if character has occured\n characterFrequency[rightCharacter] = 0; //add the character type if it hasn't \n }\n\n characterFrequency[rightCharacter]++; //increment the character type\n\n //shrink the sliding window until there are only 2 character types in the frequency dictionary\n while(Object.keys(characterFrequency).length > k) {\n const leftCharacter = str[windowStart]; //character at the start of the window\n\n characterFrequency[leftCharacter]--; //decrement character occurence\n\n if(characterFrequency[leftCharacter] === 0 ) { //check if any occurences of the starting character in the frequency dictionary\n delete characterFrequency[leftCharacter]; //if not, remove character type\n }\n\n windowStart++; //move window up\n }\n maxLength = Math.max(maxLength, windowEnd - windowStart + 1); //determine max length\n }\n return maxLength\n }", "function findLongestWord(str) {\r\n var s = Math.max.apply(null, str.split(\" \").map(function(str){return str.length;}).sort());\r\n return str.split(\" \").filter(function(word){\r\n return word.length == s;\r\n }) \r\n}", "function find_longest_word(str){\r\n var array1 = str.match(/\\w[a-z]{0,}/gi);\r\n var result = array1[0];\r\n for(var x = 1 ; x < array1.length ; x++){\r\n if(result.length < array1[x].length){\r\n result = array1[x];\r\n } \r\n }\r\n document.write(result);\r\n}", "function longestWord(str)\n{\n var array1 = str.match(/\\w[a-z]{0,}/gi); // this regex is looking for spaces\n var result = array1[0];\n\n for(var i = 1 ; i < array1.length ; i++)\n {\n if(result.length < array1[i].length)\n {\n result = array1[i];\n }\n }\n return result;\n}", "function longestWord(sen) {\n // SOLUTION BY @aweebit\n //\n // let maxLetters = 0;\n // let outputArr = [];\n // sen.toLowerCase()\n // .match(/\\w+/g)\n // .forEach(word => {\n // if (!(word.length < maxLetters)) {\n // if (word.length > maxLetters) {\n // maxLetters = word.length;\n // outputArr = [];\n // }\n // outputArr.push(word);\n // }\n // });\n // return outputArr.length > 1 ? outputArr : outputArr[0];\n}", "function longest(s1, s2) {\n s1 = s1.split(\"\");\n s2 = s2.split(\"\");\n var nstring = s1.concat(s2);\n nstring = nstring.sort();\n var result = [];\n for(var i = 0; i<nstring.length; i++){\n if(result.indexOf(nstring[i])===-1){\n result.push(nstring[i]);\n }\n }\n result = result.join(\"\");\n return result; \n }", "function longest(words) {\n\n}", "function longestSub(str){\n \n var substr = \"\";\n var lngsubstr = 0;\n var lng =\"\" ;\n \n for (var i=0; i<str.length; i++){\n \n substr = str.substring(i,i+1);\n \n var j = i+1;\n \n while( substr.indexOf(str[j]) === -1 && j<str.length ){\n substr = str.substring(i,j+1);\n j++;\n }\n \n if(lngsubstr < substr.length){\n lngsubstr = substr.length;\n lng = substr;\n } \n \n }\n \n// console.log(lng);\n// console.log(lngsubstr);\n}", "function longestWord (str) {\n\tvar arr = str.split(' ')\n\tvar a = '';\n\tfor (i=0 ; i<arr.length ; i++) {\n\t\tif (arr[i].length > a.length) {\n\t\t\ta = arr[i] ;\n\t\t}\n\t}\n\treturn a ;\n}", "function lengthOfLongestSubstring(str) {\n let substr = [];\n \n for (let startIdx = 0; startIdx < str.length; startIdx += 1) {\n for (let endIdx = startIdx + 1; endIdx <= str.length; endIdx += 1) {\n substr.push(str.slice(startIdx, endIdx));\n }\n }\n \n let nonRepeat = substr.filter(sub => {\n return sub.split('').every(char => sub.indexOf(char) === sub.lastIndexOf(char));\n });\n \n return nonRepeat.sort((a, b) => b.length - a.length)[0].length;\n}", "function findLongestWordReduce(strs) {\n return strs.reduce((a,b) => a.length < b.length ? b : a, \"\");\n}", "function longestString (str1, str2) {\n if (str1.length < str2.length) {\n return -1;\n }\n if (str1.length > str2.length) {\n return 1;\n }\n // str1 must be equal to str2\n return 0;\n}", "function LongestWord2(sen) { \n\n let result= sen\n .replace(/[^a-z A-Z]/g, ' ')\n .split(' ')\n .reduce((a,b)=> b.length > a.length ? b : a, '');\n return result;\n \n}", "function longestWord(str) {\n const regex = /[a-z]+/gi;\n let words = str.match(regex);\n let lengths = words.map(element => element.length);\n let maxCount = Math.max(...lengths);\n let longestWordsArray = words.filter(element => element.length === maxCount);\n return longestWordsArray;\n}", "function longest_substring_with_k_distinct_characters(s, k) {\n //variables\n let maxLength = 0;\n let len = 0;\n const freq = {};\n\n let left = 0;\n //sliding window\n //loop\n //expand window right\n for(let right = 0; right < s.length; right++) {\n let c = s[right];\n //add char to hashmap\n if (!(c in freq)) {\n freq[c] = 0;\n } \n freq[c]++;\n //check new max length\n len++;\n \n //if more than 3 characters in window, shrink the window from the left\n while(left < s.length && Object.keys(freq).length > k) {\n let c2 = s[left];\n freq[c2]--;\n if (freq[c2] <= 0) \n delete freq[c2];\n\n left ++;\n len--;\n }\n maxLength = Math.max(maxLength, len);\n }\n return maxLength\n}", "function longestWord(str) {\n let array1 = str.match(/\\w[a-z]{0,}/gi); // needs the {0,} to read the length property\n let result = array1[0];\n\n for(let i = 1 ; i < array1.length ; i++) {\n if (result.length < array1[i].length) {\n result = array1[i];\n } \n }\n console.log(result);\n}", "function findLongestWordLength3(str) {\n return Math.max(...str.split(\" \").map(word => word.length));\n}", "function longestWord(string){\n\tvar array= string.split(' ');\n\tvar str1 =[];\n\tvar str = array[0];\n\t\n\tfor (var i=0; i< array.length; i++){\n\t\t\n\t\tif (array[i].length >= str1.length){\n str1= array[i];\n\t\t}\n\t\t\n\t}\n\treturn str1;\n}", "function longestLength(string){\n return string.split(' ').reduce(function(acc, word){\n return Math.max(acc, word.length)\n }, 0);\n}", "function longestString(arra) {\r\n var max_str = arra[0].length;\r\n var ans = arra[0];\r\n for (var i = 1; i < arra.length; i++) {\r\n var maxi = arra[i].length;\r\n if (maxi > max_str) {\r\n ans = arra[i];\r\n max_str = maxi;\r\n }\r\n }\r\n return console.log(ans);\r\n}", "function findLongestWord(string){\n return string.reduce((longStr, string)=> {\n return longStr > string.length ? longStr :string.length\n });\n}", "function getLongest () {\n var longest = '';\n for (var i = 0; i < strings.length; i++) {\n if (strings[i].length > longest.length) {\n longest = strings[i];\n }\n }return longest;\n}", "function findLongestWord(str) {\n return str.split(/\\W+/).reduce(function(item1, item2) {\n return item1.length < item2.length ? item2 : item1;\n }, \"\").length;\n}", "function longestPalindrome(phrase){\r\n}", "function longestPalindrome(s) {\n var max_length = 0;\n maxLen = '';\n for (var i = 0; i < s.length; i++) {\n // we identify the substring and assign to a variable \n var subs = s.substr(i, s.length)\n for (var j = subs.length; j >= 0; j--) {\n var subStr = subs.substr(0, j);\n if (subStr.length <= 1)\n continue;\n if (isPalindrome(subStr)) {\n if (subStr.length > max_length) {\n max_length == subStr\n maxLen = subStr\n }\n }\n\n }\n }\n return maxLen;\n}", "function longestString(strings) {\n return strings.sort(function (a, b) { return b.length - a.length; })[0];\n}", "function distSameLetter(s){\n var uniques = s.split('').filter((a, i) => s.indexOf(a) === i).join('');\n var arr = ['', 0];\n for(var i = 0; i < uniques.length; i++){\n diff = s.lastIndexOf(uniques[i]) - s.indexOf(uniques[i]) + 1;\n if(diff > arr[1]){\n arr = [uniques[i], diff];\n }\n }\n return arr.join('');\n}", "function longestPalindrome(str) {\n\n //it's only a palindrome if the first and last letter are the same and the pattern repeats to the \"center\"\n //check first and last character, if they are different, check first and second-to-last character\n //when you find a match, repeat the process\n\n let leftIndex = 0;\n let longest = \"\";\n\n while (leftIndex < str.length) {\n\n let rightIndex = str.length - 1;\n\n while (rightIndex >= leftIndex) {\n let offset = 0;\n\n while (str[leftIndex + offset] === str[rightIndex - offset] && leftIndex + offset < str.length) {\n offset++;\n }\n\n if (leftIndex + (2 * offset) >= rightIndex) {\n let palindrome = str.substring(leftIndex, rightIndex + 1);\n\n if (palindrome.length === str.length) {\n return str;\n }\n\n if (palindrome.length > longest.length) {\n longest = palindrome;\n }\n\n }\n rightIndex--;\n }\n leftIndex++;\n }\n\n return longest;\n\n // let longest = \"\";\n //\n // let rightIndex = str.length - 1;\n //\n // while (rightIndex >= 0) {\n //\n // let leftIndex = 0;\n //\n // while (leftIndex < rightIndex) {\n //\n // let count = 0;\n //\n // while (str[leftIndex] === str[rightIndex] && rightIndex > leftIndex) {\n // leftIndex++;\n // rightIndex--;\n // count++;\n // }\n //\n // if (rightIndex <= leftIndex) {\n // let palindrome = str.substring(leftIndex - count, rightIndex + count + 1);\n // if (palindrome.length > longest.length) {\n // longest = palindrome;\n // }\n // }\n // leftIndex++;\n // }\n // rightIndex--;\n // }\n //\n // return longest;\n\n //length <= 1 returns self\n //\n // let longestPalindrome = \"\";\n // let leftIndex = 0;\n //\n //\n // //example: badbob popop abacbacba\n //\n //\n // while (leftIndex < str.length) {\n //\n // let rightIndex = str.length - 1;\n //\n // while (rightIndex > leftIndex) {\n //\n // while (str[leftIndex] !== str[rightIndex] && rightIndex > leftIndex) {\n // rightIndex--;\n // }\n //\n // let iterations = (rightIndex - leftIndex) / 2;\n // let count = 0;\n //\n // while (count < iterations) {\n // leftIndex++;\n // rightIndex--;\n //\n // if (str[leftIndex] !== str[rightIndex]) {\n // break;\n // }\n // count++;\n // }\n //\n // if (count === iterations) {\n // let palindrome = str.substring(leftIndex - iterations, rightIndex + iterations + 1);\n // if (palindrome.length > longestPalindrome.length) {\n // longestPalindrome = palindrome;\n // }\n // }\n // rightIndex--;\n // }\n // leftIndex++;\n // }\n //\n // return longestPalindrome;\n}", "function findLongestSubstring(s) {\n let longest = 0;\n let i = 0;\n let j = 0;\n let seen = new Set();\n while (i < s.length && j < s.length) {\n longest = Math.max(longest, j - i);\n if (seen.has(s[j])) {\n seen.delete(s[i]);\n i++;\n } else {\n seen.add(s[j]);\n j++;\n }\n }\n return Math.max(longest, j - i);\n}", "function findLongest(str)\n{\n return str.split(' ')\n .reduce(function (total, val) {\n return Math.max(total, val.length);\n }, 0);\n}", "function longestPalindromicSubstring(string) {\n let longestString = \"\"\n //for each char in string compute all possible substrings\n\tfor(let i = 0; i < string.length; i++) {\n\t\tfor(let j = i + 1; j < string.length + 1; j++) {\n\t\t\tlet stringTest = string.substring(i, j)\n\t\t\t//console.log({stringTest})\n\t\t\tif(isPalindrome(stringTest)) {\n\t\t\tlongestString = longestString.length < stringTest.length ? stringTest : longestString\n\t\t\tconsole.log({longestString});\n\t\t\t}\n\t\t}\n\t}\n\treturn longestString\n}", "function longestWord(string) {\n let array = string.split(\" \")\n let result = array[0];\n for (let i = 0; i < array.length; i++) {\n if (array[i].length > result.length) {\n result = array[i];\n }\n }\n return result;\n}", "function alternate(s) {\n let chars = [...new Set(s)];\n let max = 0;\n for (let i = 0; i < chars.length - 1; i++) {\n for (let j = i + 1; j < chars.length; j++) {\n let reg = new RegExp(`[${chars[i]}|${chars[j]}]`, \"gi\");\n let sub = s.match(reg);\n console.log(\"sub\", sub);\n let isValid = false;\n for (let x = 0; x < sub.length; x++) {\n if (sub[x] !== sub[x + 1]) {\n isValid = true;\n } else {\n console.log(\"not valid\");\n isValid = false;\n break;\n }\n }\n if (isValid) {\n console.log(\"valid\", max);\n if (max < sub.length) {\n max = sub.length;\n console.log(max);\n }\n }\n }\n }\n return max;\n}", "function findLongestWord4(str) {\n var longestWord = str.split(' ').sort(function(a, b) { return b.length - a.length; });\n return longestWord[0].length;\n}", "function lengthOfLongestSubstring(input){\n let currentSubString = new Set()\n let longestSubLength = 0\n for (let i = 0; i < input.length; i++){\n const currentLetter = input[i]\n if (currentSubString.has(currentLetter)) {\n currentSubString = new Set()\n currentSubString.add(currentLetter)\n } else {\n currentSubString.add(currentLetter)\n if (currentSubString.size > longestSubLength) {\n longestSubLength = currentSubString.size\n }\n }\n }\n return longestSubLength\n}", "function largestSubstringWithKDistinctChar(s, k) {\n let currentLargestSubstring = '';\n\n for (let i = 0; i < s.length; i++) {\n for (let j = i+1; j < s.length; j++) {\n let substring = s.slice(i, j);\n if (containsKDistinctChars(substring, k) && currentLargestSubstring.length < substring.length) {\n currentLargestSubstring = substring;\n } \n\n console.log(substring);\n } \n }\n\n return currentLargestSubstring;\n}", "function longestString(strings) {\n return strings.sort(function(a, b) {\n return b.length - a.length;\n })[0];\n}", "function findLongestWordLength2(s) {\n return s.split(' ')\n .reduce(function(longest, currentWord) {\n //returns the length of the longest word\n return Math.max(longest, currentWord.length)\n }, 0); //gives the initial value of x to 0 so that Math.max knows where to start\n}", "function longestSubstring(s) {\n let maxSub = 0,\n visited = {};\n for (let i = 0, j = 0; i < s.length; i++) {\n if (visited.hasOwnProperty(s[i])) {\n j = Math.max(j, visited[s[i]] + 1);\n }\n visited[s[i]] = i;\n let currMax = i - j + 1;\n maxSub = Math.max(maxSub, currMax);\n }\n return maxSub;\n}", "function findLongestSubstring(str){\n let letters = {}\n let max = 0\n let left = 0\n let right = 0\n\n while(right < str.length){\n let x = str[right]\n // console.log('l',left, 'r',right, 'm',max)\n if (letters[x]){\n left = Math.max(left, letters[x])\n }\n max = Math.max(max, right-left+1)\n letters[x] = right + 1\n right++\n }\n return max\n}", "function findLongestWord(str) {\n console.log(str.split(' ').sort((a, b) => { return a.length-b.length; }).pop());\n}", "function lengthOfLongestSubstringB(s){\n let longest = 0;\n //let seen = {};\n let seen = new Map();\n let left = 0;\n\n if(s.length <=1){\n return s.length;\n }\n\n for (let right = 0; right < s.length; right++) {\n const currentChar = s[right];\n //const prevSeenChar = seen[currentChar];\n const prevSeenChar = seen.get(currentChar);\n if(prevSeenChar >= left){\n left = prevSeenChar + 1;\n }\n //seen[currentChar] = right;\n seen.set(currentChar, right);\n longest = Math.max(longest, right - left + 1);\n }\n\n console.log(longest);\n}", "function findLongestWordLength(str) {\n let resAux = 0;\n let regEx = /.*?\\S*/g; //expresion regular que busca cualquier caracter(.), que se repita cero o mas veces(*), lo anterior busca cero o 1 vez(?), todo menos los espacios (\\S), que se repita cero o mas veces\n let palabras = [];\n palabras = str.match(regEx);\n\n for (let i = 0; i < palabras.length; i++) {\n if (i % 2 === 0) {\n let palInf = palabras[i].length;\n if (resAux < palInf) {\n resAux = palInf;\n }\n }\n }\n return resAux\n}", "function longString(){\n var longest = \"\";\n for (i=0; i<strings.length; i++){\n if (strings[i].length > longest.length){\n longest = strings[i];\n }\n} return longest;\n}", "function longestString(strings) {\n strings.sort((a, b) => b - a);\n return strings[0]\n}", "function longestPalindromicSubstring(string) {\n //edge case\n if (string.length === 1 || string.length === 2) return string[0]\n let maxPalindrome = ''\n // Write your code here.\n for ( let i = 0; i < string.length; i++){\n let potentialPalindrome = palindromeicSpreadChecker(string, i);\n if (potentialPalindrome.length > maxPalindrome.length) { maxPalindrome = potentialPalindrome };\n }\n console.log(maxPalindrome);\n return maxPalindrome\n }", "function longestRun (string) {\n\n\n\n\n\n}", "function longestSubstringWithoutDuplication(string) {\n // Write your code here.\n let longest = [0, 1]\n let set = new Set()\n let i = 0;\n let j = 0;\n while(i < string.length && j < string.length) {\n if(!set.has(string[j])) {\n set.add(string[j])\n j++\n if(longest[1]-longest[0] < j - i) {\n longest = [i, j]\n }\n } else {\n set.delete(string[i])\n i++\n }\n }\n return string.slice(longest[0], longest[1])\n }", "function longestWord(sen) {\n // SOLUTION 1 - Return a single longest word\n const wordArr = sen.toLowerCase().match(/[a-z0-9]+/g);\n //console.log(wordArr);\n\n const sorted = wordArr.sort((a, b) => {\n return b.length - a.length;\n });\n //console.log(sorted);\n // SOLUTION 2 - Return an array and include multiple words if they have the same length\n const longestWord = sorted.filter(word => {\n return word.length === sorted[0].length;\n });\n\n //console.log(longestWord);\n // SOLUTION 3 - Only return an array if multiple words, otherwise return a string\n if (longestWord.length === 1) {\n return longestWord[0];\n } else {\n return longestWord;\n }\n}", "function longestSub(string, k) {\n if (!string) return 0;\n let max = -Infinity;\n const helper = (remainString, visited = {}) => {\n if (remainString in visited) {\n return;\n }\n visited[remainString] = true;\n const diffChars = getNumberOfDiffChars(remainString);\n if (diffChars <= k) {\n max = Math.max(max, remainString.length);\n } else if (diffChars > k) {\n helper(remainString.substr(0, remainString.length - 1), visited);\n helper(remainString.substr(1), visited);\n }\n };\n helper(string);\n return max;\n}", "function KUniqueCharacters(str) { \nlet arr = [];\nlet longest = str[0];\n \nfor (let i=1; i<str.length; i++) {\n let table = {}\n let ans = \"\"\n let count = 0\n for (let j=i; j<str.length; j++) {\n if (table[str[j]] === undefined) { \n table[str[j]] = 1\n count++\n }\n if (count <= str[0]) {\n ans += str[j]\n }\n }\n if (ans.length > longest) {\n longest = ans.length\n arr.push(ans)\n }\n}\nreturn arr.sort(function(a,b) {return b.length-a.length})[0]\n}", "function findLongestSubString(string) {\n if (string.length === 0) return 0\n\n let set = new Set()\n let left = 0\n let right = 0\n let maxLen = 1\n\n while (right < string.length) {\n if (!set.has(string[right])) {\n set.add(string[right])\n maxLen = Math.max(maxLen, right - left + 1)\n right++\n } else if (set.has(string[right]) && string[right] === string[left]) {\n left++\n right++\n } else {\n set.delete(string[left])\n left++\n }\n }\n return maxLen\n}", "function longest_str_in_array(arra) {\n\n var max_str = arra[0].length;\n\n var ans = arra[0];\n\n for (var i = 1; i< arra.length; i++) {\n\n var maxi = arra[i].length;\n\n if(maxi > max_str) {\n\n ans = arra[i];\n\n max_str = maxi;\n }\n }\n \n return ans;\n }", "function findLongestSubstring(s) {\n let maxSub = 0;\n for (let i = 0; i < s.length; i++) {\n const seen = new Set();\n for (let j = i; j < s.length; j++) {\n if (!seen.has(s[j])) {\n seen.add(s[j]);\n } else {\n maxSub = Math.max(seen.size, maxSub);\n break;\n }\n }\n }\n console.log(s, maxSub);\n return maxSub;\n}", "function findLongestSubstring (s) {\n let win = s.length;\n while (win > 0) {\n let start = 0;\n while (start + win <= s.length) {\n const seen = new Set(s.slice(start, start + win));\n if (seen.size === win) {\n return win;\n }\n start += 1;\n }\n win -= 1;\n }\n return 0;\n}", "function longestString(arr) {\n function _helper_(arr, longest) {\n if(!arr.length) return longest\n if(head(arr).length > longest.length) {\n return _helper_(rest(arr), head(arr))\n }\n else return _helper_(rest(arr), longest)\n }\n return _helper_(arr, '')\n}", "function lengthOfLongestSubstring(s) {\n let temp = '';\n let count = 0;\n let max = 0;\n for (let i = 0; i < s.length; i++) {\n\n let cha = s[i];\n if (temp.indexOf(cha) == -1) { temp += cha; count++; if (count > max) { max = count; } }\n else {\n let chaIndex = temp.indexOf(cha);\n temp = temp.slice(chaIndex + 1, temp.length) + cha;\n\n count = temp.length;\n }\n }\n return max;\n}", "function longestPalindrome(str) {\n\n let arr = [...Array(128)].map(x => 0);\n\n for (const s of str.split(\"\")) {\n arr[s.charCodeAt(0)]++;\n }\n let length = 0;\n\n for (const chr of arr) {\n length += chr % 2 == 0 ? chr : chr - 1;\n }\n\n if (length < str.length) length++;\n \n return length;\n }", "function longestWord(sen) {\n\tsen = sen.replace(/[^a-zA-Z]/g, ' ');\n\tarr = sen.split(' ');\n\tarr.sort(function (a, b) {\n\t\treturn b.length - a.length;\n\t});\n\treturn arr[0];\n}", "function getLongest(){\n var longest = \"\";\n for (var i = 0; i < strings.length; i ++){\n if (strings[i].length > longest.length){\n longest = strings[i];\n }\n }\n return longest;\n}", "function findLongestWord(str) {\n return str.split(\" \").sort(function(a, b) { return a.length > b.length;}).pop().length;\n}", "function longestWord(str) {\n const findLongestWord = str.split(' ');\n const inArray = findLongestWord.sort(function (a, b) {\n return b.length - a.length;\n });\n return inArray[0];\n //return inArray[0].length; 11\n}", "function longest(s1, s2) {\n let fullStr = s1+s2\n let outputArr = []\n fullStr = fullStr.split(\"\").forEach(el => {\n if(outputArr.indexOf(el) == -1){\n outputArr.push(el)\n }\n })\n \n outputArr.sort((a,b)=>{\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n })\n return outputArr.join(\"\")\n }", "function longestword(sen) {\n const wordArr = sen.toLowerCase().split(' ')\n \n const sorted = wordArr.sort((a, b) => b.length - a.length)\n\n const longestWordArr = sorted.filter((word) => word.length === sorted[0].length)\n\n if(longestWordArr.length === 1) {\n return longestWordArr[0];\n } else {\n return longestWordArr;\n }\n}", "function findLongestWord(str) {\n return str.split(' ').reduce( (max, item) => max < item.length ? item.length : max, 0);\n}", "function longestPalindrome(str) {\n if (!str) { return str; }\n if (str.length <= 1) { return str[0]; }\n let dromes = new Set();\n let maxDrome;\n\n for (let i = 0; i < str.length; i++) {\n handleNewDrome(dromes, i, str);\n dromes.forEach( drome => {\n updateDrome(drome, i, str);\n maxDrome = updateLongestDrome(dromes, drome, maxDrome);\n\n // if not expandable and not longest, delete it\n if (!drome.isExpandable && drome !== maxDrome) {\n dromes.delete(drome);\n }\n });\n }\n\n if (!maxDrome) {\n return str[0];\n }\n let result = str.slice(maxDrome.start, maxDrome.end + 1);\n return result;\n}", "function findLongestWordLength(str) {\n let long=str.split(\" \");\n let palabra=[];\n long.forEach(element =>palabra.push(element.length));\n let max = Math.max(...palabra);\n return max;\n }", "function longestWord(str) {\n //! Accept only letters and numbers and transform in an array\n const newArr = str.toLowerCase().match(/[a-z0-9]+/g);\n\n //! sort by length\n const sorted = newArr.sort((a, b) => {\n return b.length - a.length;\n });\n\n // If multiple words, put into array\n const longestWordArr = sorted.filter((item) => {\n return item.length === sorted[0].length;\n });\n\n //! check if more than one value\n if (longestWordArr.length === 1) return longestWordArr[0];\n if (longestWordArr.length > 1) return longestWordArr;\n}", "function longest(s1, s2) {\n return [...new Set(s1 + s2)].sort().join('');\n}", "function longestWord(sen) {\n\n //breaking words apart\n let words = sen.split(' ');\n\n //replacing non-alphabetic chars\n for(let i = 0; i< words.length; i++) {\n words[i] = words[i].replace(/[^a-zA-Zsd]/g, '');\n }\n\n let result = words[0];\n\n //finding longest word\n for (let i = 1; i < words.length; i++) {\n if (words[i].length > result.length) {\n result = words[i];\n }\n }\n return result;\n\n}", "function longestWord(str) {\n return str.split(\" \").sort((a, b) => b.length - a.length)[0];\n // return str.split(\" \").sort((a, b) => b.length - a.length)[0].length; //longest word length\n}", "function longestSubstringWithKDistinctCharacters(s, k) {\n\n // Map used to keep track of letters\n let map = new Map();\n\n let startWindow = 0;\n let endWindow = 0;\n\n let currentLength = Number.MIN_VALUE;\n\n while (endWindow < s.length) {\n\n if (!map.has(s.charAt(endWindow)) && map.size < k) {\n map.set(s.charAt(endWindow++), 1);\n currentLength = Math.max(currentLength, endWindow-startWindow);\n } else if (!map.has(s.charAt(endWindow)) && map.size === k) {\n // Remove the starting character from the map and then add current character\n // till the map has less than k distinct characters\n while(map.has(s.charAt(startWindow)) && map.size === k) {\n if (map.get(s.charAt(startWindow)) > 1) {\n map.set(s.charAt(startWindow), map.get(startWindow)-1);\n } else {\n map.delete(s.charAt(startWindow));\n }\n startWindow++;\n }\n // Add current character\n if (!map.has(s.charAt(endWindow)) && map.size < k) {\n map.set(s.charAt(endWindow++), 1);\n currentLength = Math.max(currentLength, endWindow-startWindow);\n }\n } else {\n map.set(s.charAt(endWindow), map.get(s.charAt(endWindow))+1);\n endWindow++;\n currentLength = Math.max(currentLength, endWindow-startWindow);\n }\n }\n\n return currentLength;\n}", "function longest(s1, s2) {\n let combined = s1 + s2;\n let uniqueSet = new Set(combined);\n let uniqueArray = [...uniqueSet];\n return uniqueArray.sort().join(\"\");\n\n}", "function longestWord(str) {\n let strArray = str.split(\" \");\n let sortedStrArr = strArray.sort(function (strA, strB) {\n return strB.length - strA.length;\n });\n\n if (sortedStrArr[0] === \"\") {\n return \"\";\n }\n\n if (sortedStrArr[0].length && sortedStrArr[1].length) {\n //I return the first one that matches\n return sortedStrArr[0];\n }\n\n return sortedStrArr[0];\n}" ]
[ "0.7652051", "0.7617659", "0.75543123", "0.7379306", "0.7368392", "0.7354283", "0.73222154", "0.73021054", "0.73021054", "0.7274617", "0.72505206", "0.7194048", "0.71587837", "0.7139319", "0.71073025", "0.71041304", "0.7097804", "0.7094539", "0.7089854", "0.7087168", "0.70838654", "0.7082741", "0.7079546", "0.70635754", "0.7055023", "0.705248", "0.70446324", "0.7020452", "0.70092154", "0.6996492", "0.69948316", "0.6991366", "0.69867194", "0.6968796", "0.69671595", "0.6962552", "0.6959475", "0.69512856", "0.6945112", "0.69426894", "0.6917805", "0.6904386", "0.6898704", "0.6897043", "0.68931854", "0.688317", "0.68740535", "0.68709743", "0.6865295", "0.68596655", "0.6858991", "0.68484515", "0.68428504", "0.6842722", "0.68425983", "0.68425447", "0.6829698", "0.6816484", "0.6810951", "0.68062747", "0.6804488", "0.67997986", "0.6797165", "0.679698", "0.67964935", "0.6794594", "0.67890906", "0.6788179", "0.6786895", "0.67851794", "0.67813677", "0.67782754", "0.6767631", "0.67656714", "0.67624134", "0.67505014", "0.67482686", "0.6747205", "0.6746153", "0.6740772", "0.6739415", "0.67381555", "0.67377824", "0.6727766", "0.67222035", "0.67198503", "0.6714202", "0.6709144", "0.6708755", "0.67000765", "0.66939247", "0.6690447", "0.66878307", "0.6685791", "0.6680936", "0.6679534", "0.6669474", "0.66689414", "0.6664399", "0.6661426", "0.66533947" ]
0.0
-1
solution2("To crop or not to crop", 21) solution2("Codility We test coders", 14)
function solution3(A) { count = 0; for (i = 0; i < A.length; i++) { if (i + 1 > A.length || i + 2 > A.length) { } else if (A[i] - A[i + 1] == A[i + 1] - A[i + 2]) { count += 1; let newA = A.slice(i + 2) let dist = A[i] - A[i + 1] for (j = 0; j < newA.length; j++) { if (j + 1 >= A.length) { console.log("No more new array!") } else if (newA[j] - newA[j + 1] == dist) { count += 1; } } } } // console.log(count) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function C012_AfterClass_Jennifer_ConfiscateCrop() {\n\tPlayerRemoveInventory(\"Crop\", 99);\n\tGameLogAdd(\"HasCrop\");\n\tC012_AfterClass_Jennifer_SetPose();\n\tC012_AfterClass_Jennifer_AllowLeave();\n}", "function image_clipping(){\n\tvar top \t= (man_settings.man_cropper.offsetTop<=0) ? (-1*man_settings.man_crop_cliped_img.offsetTop) : (man_settings.man_cropper.offsetTop+(-1*man_settings.man_crop_cliped_img.offsetTop)),\n\t\tleft \t= (man_settings.man_cropper.offsetLeft<=0) ? (-1*man_settings.man_crop_cliped_img.offsetLeft) : (man_settings.man_cropper.offsetLeft+(-1*man_settings.man_crop_cliped_img.offsetLeft)),\n\t\twidth \t= (man_settings.man_cropper.offsetWidth+left),\n\t\theight \t= (man_settings.man_cropper.offsetHeight+top);\n\tman_settings.man_crop_cliped_img.style.cssText = `clip: rect(${top}px, ${width}px, ${height}px, ${left}px)`;\n\n\t/*left boundary set start*/\n\tif(man_settings.man_cropper.offsetLeft){\n\t\tman_settings.man_crop_cliped_img.style.cssText = `clip: rect(${top}px, ${width}px, ${height}px, ${left}px)`;\n\t}\n\t/*left boundary set end*/\n\n\t/*top boundary set start*/\n\tif(man_settings.man_cropper.offsetTop){\n\t\tman_settings.man_crop_cliped_img.style.cssText = `clip: rect(${top}px, ${width}px, ${height}px, ${left}px)`;\n\t}\n\t/*top boundary set end*/\n\n\t/*bottom boundary set start*/\n\tif((height+man_settings.man_crop_cliped_img.offsetTop)>=man_settings.man_crop_box.offsetHeight){\n\t\theight = (man_settings.man_crop_box.offsetHeight-man_settings.man_crop_cliped_img.offsetTop);\n\t\ttop = (height-man_settings.man_cropper.offsetHeight);\n\t\tman_settings.man_crop_cliped_img.style.cssText = `clip: rect(${top}px, ${width}px, ${height}px, ${left}px)`;\n\t}\n\t/*bottom boundary set end*/\n\n\t/*right boundary set start*/\n\tif((width+man_settings.man_crop_cliped_img.offsetLeft)>=man_settings.man_crop_box.offsetWidth){\n\t\twidth = (man_settings.man_crop_box.offsetWidth-man_settings.man_crop_cliped_img.offsetLeft);\n\t\tleft = (width-man_settings.man_cropper.offsetWidth);\n\t\tman_settings.man_crop_cliped_img.style.cssText = `clip: rect(${top}px, ${width}px, ${height}px, ${left}px)`;\n\t}\n\t/*right boundary set end*/\n}", "function checkCase(y,x){\n\n var northWest = false;\n var northEast = false;\n var southWest = false;\n var southEast = false;\n var result = [];\n //check northWest Block\n\n if(x == 0 || y == 0){\n northWest = true;\n }else{\n if($scope.cell[y- 1][x - 1].isObstacle){\n northWest = true;\n }\n }\n\n //check northEast Block\n if(y == 0 || x == 30){\n northEast = true;\n }else{\n if($scope.cell[y -1][x].isObstacle){\n northEast = true;\n }\n }\n\n //check southWest Block\n if(x == 0 || y == 20){\n southWest = true;\n }else{\n if($scope.cell[y][x - 1].isObstacle){\n southWest = true;\n }\n }\n //check southEast Block\n if(x == 30 || y == 20){\n southEast = true;\n }else{\n if($scope.cell[y][x].isObstacle){\n southEast = true;\n }\n }\n\n if(!northWest && !northEast && !southWest && !southEast){\n result[0] = 0;\n result[1] = [];\n result[1] = [1,1,1,1];\n return result; // all way normal\n }\n\n //three way normal\n if(northWest && !northEast && !southWest && !southEast){\n result[0] = 0;\n result[1] = [];\n result[1] = [0,1,1,1];\n return result; //except northwest\n }\n\n if(!northWest && northEast && !southWest && !southEast){\n result[0] = 0;\n result[1] = [];\n result[1] = [1,0,1,1];\n return result; //except northeast\n }\n if (!northWest && !northEast && southWest && !southEast){\n result[0] = 0;\n result[1] = [];\n result[1] = [1,1,1,0];\n return result; //except southwest\n }\n if(!northWest && !northEast && !southWest && southEast){\n result[0] = 0;\n result[1] = [];\n result[1] = [1,1,0,1];\n return result; //except southeast\n }\n\n\n //two way normal\n if(northWest && northEast && !southWest && !southEast){\n result[0] = 0;\n result[1] = [];\n result[1] = [0,0,1,1];\n return result; //except northwest and east\n }\n if(!northWest && northEast && !southWest && southEast){\n result[0] = 0;\n result[1] = [];\n result[1] = [1,0,0,1];\n return result; //except northeast and southeast\n }\n if(!northWest && !northEast && southWest && southEast){\n result[0] = 0;\n result[1] = [];\n result[1] = [1,1,0,0];\n return result; //except southwest and southeast\n }\n\n if(northWest && !northEast && southWest && !southEast){\n result[0] = 0;\n result[1] = [];\n result[1] = [0,1,1,0];\n return result; //except southwest and northwest\n }\n\n\n //one corner\n if(northWest && northEast && southWest && !southEast){\n result[0] = 1; // one corner\n result[1] = [];\n result[1] = [0,0,1,0];\n return result;\n }\n if (northWest && northEast && !southWest && southEast){\n result[0] = 1; // one corner\n result[1] = [];\n result[1] = [0,0,0,1];\n return result;\n }\n if(!northWest && northEast && southWest && southEast){\n result[0] = 1; // one corner\n result[1] = [];\n result[1] = [1,0,0,0];\n return result;\n }\n if (northWest && !northEast && southWest && southEast){\n result[0] = 1; // one corner\n result[1] = [];\n result[1] = [0,1,0,0];\n return result;\n }\n\n\n //two corners\n if(!northWest && northEast && southWest && !southEast){\n result[0] = 2; // two corners\n result[1] = [];\n result[1] = [1,0,1,0];\n return result;\n }\n if(northWest && !northEast && !southWest && southEast){\n result[0] = 2; // two corners\n result[1] = [];\n result[1] = [0,1,0,1];\n return result;\n }\n\n }", "function challenge2() {\n\n}", "test(){\r\n\r\n const __quickSolver = (sudoku) =>{\r\n while(sudoku.simpleDeletion().status){}\r\n for(let i=1; i<=9; i++){\r\n for(let j=1; j<=9; j++){\r\n if(sudoku.getNumber(i, j)==0){\r\n if(sudoku.hasContradiction(false).status==true){\r\n return sudoku;\r\n }\r\n const candidates = sudoku.getCandidateInArray(i, j);\r\n if(candidates.length==0){\r\n sudoku.__hasContradiction = 1;\r\n return sudoku;\r\n }\r\n let count_contradiction = 0;\r\n let count_solved = 0;\r\n let n_copy;\r\n let solved_sudoku;\r\n for(const candidate of candidates){\r\n // 試しに代入して解く\r\n const sudoku_clone = sudoku.clone();\r\n sudoku_clone.setNumber(i, j, candidate);\r\n const result = __quickSolver(sudoku_clone);\r\n \r\n if(result.no_unique_solution==true){\r\n return result;\r\n }\r\n\r\n if(result.isSolved()==true){\r\n return result;\r\n }\r\n\r\n if(result.hasContradiction(false).status==true){\r\n sudoku.deleteCandidate(i, j, candidate)\r\n count_contradiction ++;\r\n continue;\r\n }\r\n }\r\n\r\n if(count_solved==1){\r\n sudoku.setNumber(i, j, n_copy);\r\n continue;\r\n }\r\n \r\n if(count_contradiction==candidates.length){\r\n sudoku.no_solution = true;\r\n sudoku.__hasContradiction = 1;\r\n return sudoku;\r\n }\r\n }\r\n }\r\n }\r\n \r\n return sudoku;\r\n };\r\n \r\n return __quickSolver(this.clone());\r\n }", "function solution(arr){\n\n}", "function makeBricks(small ,big, goal) {\n possible = false;\n if (big * 5 === goal || small * 1 === goal || small * 1 + big * 5 === goal)\n {possible = true;}\n console.log(possible);\n return big * 5 === goal || small * 1 === goal || small * 1 + big * 5 === goal\n}", "function ok2(){ \n if(j-avain2<0){\n \n r=29-avain2+j;\n \n \n }\n else{\n r=(j-avain2);\n \n }\n}", "function checkSoftConstSix()\n{\n const shifts = nurseShifts[0].length;\n const nurses = nurseShifts.length; \n var numberOfBrokenConstraints = 0;\n //console.log('+------------------------------------------Ograniczenie miękkie nr. 6------------------------------------------+')\n for(var nurse = 0; nurse < nurses; nurse++)\n {\n //zmiana 0 oznacza zmianę dzienną, \n for(var shift = 0; shift < shifts; shift += 4)\n {\n //Jeśli zmiana dzienna jest zajeta i zmiana wczesna dnia następnego przez tę samą pielęgniarke to ograniczenie zostaje złamane.\n if((nurseShifts[nurse][shift] === 1) && (nurseShifts[nurse][shift + 5] === 1))\n {\n //cconsole.log('* Pielęgniarka nr.: ' + nurse + ', ogarniczenie nr. 6 złamne w miejscu zmiany nr.: ' + shift); \n //for(var i = shift; i <= (shift + 5); ++i) console.log('**Zmiana nr.: '+ i + ' | ' + nurseShifts[nurse][i]);\n //cconsole.log('#################################################################');\n numberOfBrokenConstraints++;\n }\n }\n \n }\n\n //console.log('+--------------------------------------------------------------------------------------------------------------+')\n return numberOfBrokenConstraints;\n}", "conjectureP2(x, y) {\n return 0;\n }", "function challenge3() {\n\n}", "function C012_AfterClass_Amanda_ConfiscateCrop() {\n\tPlayerRemoveInventory(\"Crop\", 99);\n\tGameLogAdd(\"HasCrop\");\n\tC012_AfterClass_Amanda_AllowLeave();\n}", "function get2x2optscramble(mn) {\n var e = [15, 16, 16, 21, 21, 15, 13, 9, 9, 17, 17, 13, 14, 20, 20, 4, 4, 14, 12, 5, 5, 8, 8, 12, 3, 23, 23, 18, 18, 3, 1, 19, 19, 11, 11, 1, 2, 6, 6, 22, 22, 2, 0, 10, 10, 7, 7, 0], d = [\n [],\n [],\n [],\n [],\n [],\n []\n ], v = [\n [0, 2, 3, 1, 23, 19, 10, 6, 22, 18, 11, 7],\n [4, 6, 7, 5, 12, 20, 2, 10, 14, 22, 0, 8],\n [8, 10, 11, 9, 12, 7, 1, 17, 13, 5, 0, 19],\n [12, 13, 15, 14, 8, 17, 21, 4, 9, 16, 20, 5],\n [16, 17, 19, 18, 15, 9, 1, 23, 13, 11, 3, 21],\n [20, 21, 23, 22, 14, 16, 3, 6, 15, 18, 2, 4]\n ], r = [], a = [], b = [], c = [], f = [], s = [];\n\n function t() {\n s = [1, 1, 1, 1, 2, 2, 2, 2, 5, 5, 5, 5, 4, 4, 4, 4, 3, 3, 3, 3, 0, 0, 0, 0]\n }\n\n t();\n function mx() {\n t();\n for (var i = 0; i < 500; i++)dm(Math.floor(Math.random() * 3 + 3) + 16 * Math.floor(Math.random() * 3))\n }\n\n function cj() {\n var i, j;\n for (i = 0; i < 6; i++)for (j = 0; j < 6; j++)d[i][j] = 0;\n for (i = 0; i < 48; i += 2)if (s[e[i]] <= 5 && s[e[i + 1]] <= 5)d[s[e[i]]][s[e[i + 1]]]++\n }\n\n function dm(m) {\n var j = 1 + (m >> 4), k = m & 15, i;\n while (j) {\n for (i = 0; i < v[k].length; i += 4)y(s, v[k][i], v[k][i + 3], v[k][i + 2], v[k][i + 1]);\n j--\n }\n }\n\n function sv() {\n cj();\n var h = [], w = [], i = 0, j, k, m;\n for (j = 0; j < 7; j++) {\n m = 0;\n for (k = i; k < i + 6; k += 2) {\n if (s[e[k]] == s[e[42]])m += 4;\n if (s[e[k]] == s[e[44]])m += 1;\n if (s[e[k]] == s[e[46]])m += 2\n }\n h[j] = m;\n if (s[e[i]] == s[e[42]] || s[e[i]] == 5 - s[e[42]])w[j] = 0; else if (s[e[i + 2]] == s[e[42]] || s[e[i + 2]] == 5 - s[e[42]])w[j] = 1; else w[j] = 2;\n i += 6\n }\n m = 0;\n for (i = 0; i < 7; i++) {\n j = 0;\n for (k = 0; k < 7; k++) {\n if (h[k] == i)break;\n if (h[k] > i)j++\n }\n m = m * (7 - i) + j\n }\n j = 0;\n for (i = 5; i >= 0; i--)j = j * 3 + w[i] - 3 * Math.floor(w[i] / 3);\n if (m != 0 || j != 0) {\n r.length = 0;\n for (k = mn; k < 99; k++)if (se(0, m, j, k, -1))break;\n j = \"\";\n for (m = 0; m < r.length; m++)j = \"URF\".charAt(r[m] / 10) + \"\\'2 \".charAt(r[m] % 10) + \" \" + j;\n return j\n }\n }\n\n function se(i, j, k, l, m) {\n if (l != 0) {\n if (a[j] > l || b[k] > l)return false;\n var o, p, q, n;\n for (n = 0; n < 3; n++)if (n != m) {\n o = j;\n p = k;\n for (q = 0; q < 3; q++) {\n o = c[o][n];\n p = f[p][n];\n r[i] = 10 * n + q;\n if (se(i + 1, o, p, l - 1, n))return true\n }\n }\n } else if (j == 0 && k == 0)return true;\n return false\n }\n\n function z() {\n var i, j, k, m, n;\n for (i = 0; i < 5040; i++) {\n a[i] = -1;\n c[i] = [];\n for (j = 0; j < 3; j++)c[i][j] = g(i, j)\n }\n a[0] = 0;\n for (i = 0; i <= 6; i++)for (j = 0; j < 5040; j++)if (a[j] == i)for (k = 0; k < 3; k++) {\n m = j;\n for (n = 0; n < 3; n++) {\n var m = c[m][k];\n if (a[m] == -1)a[m] = i + 1\n }\n }\n for (i = 0; i < 729; i++) {\n b[i] = -1;\n f[i] = [];\n for (j = 0; j < 3; j++)f[i][j] = w(i, j)\n }\n b[0] = 0;\n for (i = 0; i <= 5; i++)for (j = 0; j < 729; j++)if (b[j] == i)for (k = 0; k < 3; k++) {\n m = j;\n for (n = 0; n < 3; n++) {\n var m = f[m][k];\n if (b[m] == -1)b[m] = i + 1\n }\n }\n }\n\n function g(i, j) {\n var k, m, n, o = i, h = [];\n for (k = 1; k <= 7; k++) {\n m = o % k;\n o = (o - m) / k;\n for (n = k - 1; n >= m; n--)h[n + 1] = h[n];\n h[m] = 7 - k\n }\n if (j == 0)y(h, 0, 1, 3, 2); else if (j == 1)y(h, 0, 4, 5, 1); else if (j == 2)y(h, 0, 2, 6, 4);\n o = 0;\n for (k = 0; k < 7; k++) {\n m = 0;\n for (n = 0; n < 7; n++) {\n if (h[n] == k)break;\n if (h[n] > k)m++\n }\n o = o * (7 - k) + m\n }\n return o\n }\n\n function w(i, j) {\n var k, m, n, o = 0, p = i, h = [];\n for (k = 0; k <= 5; k++) {\n n = Math.floor(p / 3);\n m = p - 3 * n;\n p = n;\n h[k] = m;\n o -= m;\n if (o < 0)o += 3\n }\n h[6] = o;\n if (j == 0)y(h, 0, 1, 3, 2); else if (j == 1) {\n y(h, 0, 4, 5, 1);\n h[0] += 2;\n h[1]++;\n h[5] += 2;\n h[4]++\n } else if (j == 2) {\n y(h, 0, 2, 6, 4);\n h[2] += 2;\n h[0]++;\n h[4] += 2;\n h[6]++\n }\n p = 0;\n for (k = 5; k >= 0; k--)p = p * 3 + (h[k] % 3);\n return p\n }\n\n function y(i, j, k, m, n) {\n var o = i[j];\n i[j] = i[k];\n i[k] = i[m];\n i[m] = i[n];\n i[n] = o\n }\n\n z();\n for (var i = 0; i < num; i++) {\n mx();\n ss[i] += sv();\n }\n}", "function solution(s) {\n\n}", "function solution(A) {\n\n}", "function passcodeDerivation(answers) {\n var minCode = [];\n var min = ''; //indication of no answer yet\n var code = []; //code of the current search path\n \n var data = _.map(answers, function(answer) {\n return { \n answer: answer,\n currentPos: 0\n }; \n }); \n var numAnswers = 0;\n var numPrune1s = 0;\n var numPrune2s = 0;\n \n var searchR = function(data) {\n //remove code that are already covered\n var arr = _.filter(data, function(row) {\n return (row.currentPos < row.answer.length);\n });\n if(arr.length === 0) {\n //termination condition: all digits are covered\n if(min === '' || code.length < min) {\n min = code.length;\n //clone the code\n minCode = [];\n _.each(code, function(num) {\n minCode.push(num); \n });\n //console.log('found a better solution: ', min);\n //console.log(minCode);\n }\n numAnswers++;\n return;\n }\n if(min!== '' && code.length >= min) {\n //prune, already worse than current best solution\n numPrune1s++;\n return;\n }\n //group by the current head of all answers\n var group = _.groupBy(arr, function(row){\n return row.answer[row.currentPos];\n });\n //start search from the most numerous number\n group = _.sortBy(group, function(rows, num) {\n return -rows.length;\n });\n if(min !== '' && code.length + group.length >= min) {\n //prune, total expected length cannot beat the current best solution\n numPrune2s++;\n return;\n }\n \n //recursively search all numbers presented in the group\n _.each(group, function(rows) {\n var row0, num;\n row0 = rows[0];\n var num = row0.answer[row0.currentPos];\n code.push(num);\n _.each(rows, function(row) {\n row.currentPos++; \n }); \n searchR(data);\n //clean up, ready to switch to search another branch\n code.pop();\n _.each(rows, function(row) {\n row.currentPos--; \n }); \n });\n };\n \n searchR(data);\n //console.log(\"number of answers \", numAnswers);\n //console.log(\"number of type 1 prunes\", numPrune1s);\n //console.log(\"number of type 2 prunes\", numPrune2s);\n \n return {\n min: min,\n minCode: minCode\n };\n}", "function cornerAlgorithm(){\n\t\t\t\tR(); \n\t\t\t\tUPrime(); \n\t\t\t\tRPrime();\n\t\t\t\tUPrime();\n\t\t\t\tR();\n\t\t\t\tU();\n\t\t\t\tRPrime();\n\t\t\t\tFPrime();\n\t\t\t\tR();\n\t\t\t\tU();\n\t\t\t\tRPrime();\n\t\t\t\tUPrime();\n\t\t\t\tRPrime();\n\t\t\t\tF();\n\t\t\t\tR();\n\n\t\t\t}", "function determineTrials()\n{\n\n\t//if you want 2 trials of each condition, use the array, [lengths, efficacies, crossed, lengths, efficacies, crossed]\n\tvar conditions = [lengths, efficacies, crossed, crossed, crossed, crossed];\n\n\tconditions = shuffle(conditions);\n\n\treturn conditions\n}", "function cut2(){\n\tbiggestslice.start = biggestslice.start + (((biggestslice.end-biggestslice.start))/(100/z))\n\tif (biggest == 1){\n\t\tsliceA.start = biggestslice.start;\n\t}else{\n\t\tif(biggest == 2){\n\t\t\tsliceB.start = biggestslice.start;\n\t\t}else{\n\t\t\tsliceC.start = biggestslice.start;\n\t\t}\n\t} \n\tdiv = document.getElementById('hide3');\n\tdiv.style.display = \"block\";\n\t\n\tvar c=document.getElementById(\"3choice\");\n var ctx=c.getContext(\"2d\");\n\tctx.drawImage(img,0,0, c.width, c.height);\n\t\n ctx.rect(0,0,sliceA.start*3,c.height);\n\tctx.lineWidth = 0;\n ctx.fillStyle = '#FFFFFF';\n ctx.fill();\n ctx.stroke();\n\t\n\tctx.rect(sliceA.end*3,0,c.width,c.height);\n\tctx.lineWidth = 0;\n ctx.fillStyle = '#FFFFFF';\n ctx.fill();\n ctx.stroke();\n\t\n\tvar d=document.getElementById(\"3choice2\");\n var ctx=d.getContext(\"2d\");\n\tctx.drawImage(img,0,0, c.width, c.height);\n\tctx.rect(0,0,sliceB.start*3,c.height);\n\tctx.lineWidth = 0;\n ctx.fillStyle = '#FFFFFF';\n ctx.fill();\n ctx.stroke();\n\t\n\tctx.rect(sliceB.end*3,0,c.width,c.height);\n\tctx.lineWidth = 0;\n ctx.fillStyle = '#FFFFFF';\n ctx.fill();\n ctx.stroke();\n\t\n\tvar e=document.getElementById(\"3choice3\");\n var ctx=e.getContext(\"2d\");\n\tctx.drawImage(img,0,0, c.width, c.height);\n\tctx.rect(0,0,sliceC.start*3,c.height);\n\tctx.lineWidth = 0;\n ctx.fillStyle = '#FFFFFF';\n ctx.fill();\n ctx.stroke();\n\t\n\tctx.rect(sliceC.end*3,0,c.width,c.height);\n\tctx.lineWidth = 0;\n ctx.fillStyle = '#FFFFFF';\n ctx.fill();\n ctx.stroke();\n}", "function challenge1() {\n\n}", "function challenge1() {\n\n}", "function checkPuzzle(){\n var re =1;\n if(solv ==0){\n for(var id in tl_p){\n if(id !=tl_p[id].ord){ re =0; break;}\n }\n }\n if(re ==1){\n cnt.drawImage(img, 0, 0, width, height);\n \n //if solved manually (-1 is auto) calls solved()\n if(solv ==0){\n solv =1;\n me.solved();\n }\n }\n }", "function puzzleStringContainsSufficientClues(str)\n{\n return (countPuzzleStringClues(str) >= 17);\n}", "function testPAA()\n{\nvar capt = permuteAnArray([[1],[2],[3],[4],[5],[6],[7]])\nvar bbb=1;\n\n}", "function solve() {\r\n\t// run test if the puzzle is shuffled\r\n\tif(SHUFFLE) {\r\n\t\t// initially good\r\n\t\tvar good = true;\r\n\t\t// test all the pieces\r\n\t\tfor(var i = 0; i < PIECES.length; i++) {\r\n\t\t\t// expected position for each piece\r\n\t\t\tvar left = i%PUZZLESIZE*TILESIZE;\r\n\t\t\tvar top = Math.floor(i/PUZZLESIZE)*TILESIZE;\r\n\t\t\t// if the position is not expected, it is no more good\r\n\t\t\tif(!(PIECES[i].style.left == left+\"px\" && PIECES[i].style.top == top+\"px\")) {\r\n\t\t\t\tgood = false;\r\n\t\t\t}\r\n\t\t}\r\n\t\t// if still good, call victory to show notification\r\n\t\tif(good) {\r\n\t\t\tvictory();\r\n\t\t}\r\n\t}\r\n}", "function burning_crop_residues(){\n a_FAO_i='burning_crop_residues';\n initializing_change();\n change();\n}", "function little_check1(count,count2){\n\n\n\t \t for (var x = count; x <= (count+2); x++) {\n\t\t\tfor (var y = count2; y <= (count2+2); y++) {\n\n\t\t\t\tif ((matrix[x][(count2+0)]) === \"p2\" && (matrix[x][(count2+1)]) === \"p2\" && (matrix[x][(count2+2)]) === \"p2\") {\n\t\t\t\t\n\t\t\t\t//console.log(player1)\n\n\t\t\t\tif (player1== false) {\n\t\t\t\t\tconsole.log(\"horizontal victory\")\n\t\t\t\t\tconsole.log(\"player2 wins\")\n\t\t\t\t\twinner_show(BR,BC)\n\t\t\t\t\tlittlematrix[(BR-1)][(BC-1)]=\"p2\";\n\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\telse if\t((matrix[(count+0)][y]) === \"p2\" && (matrix[(count+1)][y]) === \"p2\" && (matrix[(count+2)][y]) === \"p2\") {\n\t\t\t\tif (player1== false) {\n\t\t\t\t\tconsole.log(\"vertical victory\")\n\t\t\t\t\tconsole.log(\"player2 wins\")\n\t\t\t\t\twinner_show(BR,BC)\n\t\t\t\t\tlittlematrix[(BR-1)][(BC-1)]=\"p2\";\n\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if ((matrix[(count+0)][(count2+0)]) === \"p2\" && (matrix[(count+1)][(count2+1)]) === \"p2\" && (matrix[(count+2)][(count2+2)]) === \"p2\") {\n\t\t\t\tif (player1== false) {\t\n\t\t\t\t\tconsole.log(\"LtopRdown diagonal\")\n\t\t\t\t\tconsole.log(\"player2 wins\")\n\t\t\t\t\twinner_show(BR,BC)\n\t\t\t\t\tlittlematrix[(BR-1)][(BC-1)]=\"p2\";\n\t\t\t\t\treturn;\n\t\t\t\t\t}\t\n\t\t\t\t}\n\t\t\t\n\t\t\t\telse if\t((matrix[(count+0)][(count2+2)]) === \"p2\" && (matrix[(count+1)][(count2+1)]) === \"p2\" && (matrix[(count+2)][(count2+0)]) === \"p2\") {\t\n\t\t\t\t\tif (player1== false) {\n\t\t\t\t\tconsole.log(\"Rtop Ldown diagonal\")\n\t\t\t\t\tconsole.log(\"player2 wins\")\n\t\t\t\t\twinner_show(BR,BC)\n\t\t\t\t\tlittlematrix[(BR-1)][(BC-1)]=\"p2\";\n\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t}\n\t\n\t\t}\n\t\t}", "calcTroops(villageId,buildings)\n {\n let barrackList =[]\n let barrackQ;\n let barrack = this.troopres['club'].split(',');\n let res = m.villageData[villageId][\"res\"];\n console.log(barrack)\n \n barrackList.push(parseInt(res.wood/barrack[0]))\n barrackList.push(parseInt(res.clay/barrack[1]))\n barrackList.push(parseInt(res.iron/barrack[2]))\n barrackList.push(parseInt(res.crop/barrack[3]))\n barrackQ = Math.min.apply(null, barrackList);\n console.log(barrackQ)\n let rcrop = parseInt(res.crop) - barrackQ*barrack[3]; \n if(rcrop>200)\n {\n \n return barrackQ;\n }\n else\n {\n return 0;\n }\n }", "function solve(arr) {\n if (arr[0][0] === 'O' && arr[0][1] === 'O' && arr[0][2] === 'O'){\n console.log('O wins - top row');\n } else if (arr[0][0] === 'O' && arr[1][0] === 'O' && arr[2][0] === 'O') {\n console.log('0 wins - left side')\n } else if (arr[2][0] === 'O' && arr[2][1] === 'O' && arr[2][2] === 'O') {\n console.log('0 wins - bottom row')\n } else if (arr[0][2] === 'O' && arr[1][2] === 'O' && arr[2][2] === 'O') {\n console.log('0 wins - right side')\n } else if (arr[1][0] === 'O' && arr[1][1] === 'O' && arr[1][2] === 'O') {\n console.log('0 wins - middle/left to right')\n } else if (arr[0][1] === 'O' && arr[1][1] === 'O' && arr[2][1] === 'O') {\n console.log('0 wins - middle top/bottom')\n } else if (arr[0][0] === 'O' && arr[1][1] === 'O' && arr[2][2] === 'O') {\n console.log('0 wins - diagonal topleft/bottomright')\n } else if (arr[0][2] === 'O' && arr[1][1] === 'O' && arr[2][0] === 'O') {\n console.log('0 wins - diagonal topright/bottomleft') \n } else if (arr[0][0] === 'x' && arr[0][1] === 'x' && arr[0][2] === 'x') {\n console.log('x wins - top row')\n } else if (arr[0][0] === 'x' && arr[1][0] === 'x' && arr[2][0] === 'x') {\n console.log('x wins - left side')\n } else if (arr[2][0] === 'x' && arr[2][1] === 'x' && arr[2][2] === 'x') {\n console.log('x wins - bottom row')\n } else if (arr[0][2] === 'x' && arr[1][2] === 'x' && arr[2][2] === 'x') {\n console.log('x wins - right side')\n } else if (arr[1][0] === 'x' && arr[1][1] === 'x' && arr[1][2] === 'x') {\n console.log('x wins - middle/left to right')\n } else if (arr[0][1] === 'x' && arr[1][1] === 'x' && arr[2][1] === 'x') {\n console.log('x wins - middle top/bottom')\n } else if (arr[0][1] === 'x' && arr[1][1] === 'x' && arr[2][2] === 'x') {\n console.log('x wins - diagonal topleft/bottomright')\n } else if (arr[0][2] === 'x' && arr[1][1] === 'x' && arr[2][0] === 'x') {\n console.log('x wins - diagonal topright/bottomleft')\n } else {\n console.log('null wins');\n }\n}", "function folding(dis) {\n let paper = 0.0001\n let folds = 0\n if(dis <= 0){\n return null;\n }\n else while(paper <= dist){\n paper *= 2\n folds++\n }\n return folds\n }", "static getScrambledPuzzle() {\n const board = [\n [0, 1, 2],\n [3, 4, 5],\n [6, 7, 8],\n ];\n\n // Randomly choose 1 out of 9 squares as the initial blank square.\n // x and y represent the position of this blank square on the board.\n const blank = randInt(9);\n let x = blank % 3;\n let y = Math.floor(blank / 3);\n\n // Starting with the solved image, scramble it by swapping the blank square\n // with one of its neighbors. Each swap is recorded so that the image\n // can be solved later simply by reversing the steps.\n const steps = [];\n let excludedFn;\n\n // Each one of these functions moves the blank square in a direction,\n // swapping it with its neighbor in said direction.\n // HAX: Each function currently returns its opposite to\n // signal the caller not to go back and forth.\n const up = () => {\n board[y][x] = board[--y][x];\n board[y][x] = blank;\n steps.unshift('down');\n return down;\n };\n const down = () => {\n board[y][x] = board[++y][x];\n board[y][x] = blank;\n steps.unshift('up');\n return up;\n };\n const left = () => {\n board[y][x] = board[y][--x];\n board[y][x] = blank;\n steps.unshift('right');\n return right;\n };\n const right = () => {\n board[y][x] = board[y][++x];\n board[y][x] = blank;\n steps.unshift('left');\n return left;\n };\n const execRandFn = (fns) => {\n const i = fns.indexOf(excludedFn);\n if (i !== -1) fns.splice(i, 1);\n const fn = fns[randInt(fns.length)];\n excludedFn = fn();\n };\n\n // Randomly move the blank square around, taking care to not go out of bounds.\n const move = () => {\n switch (x) {\n case 0:\n if (y === 0) execRandFn([right, down]);\n else if (y === 2) execRandFn([right, up]);\n else execRandFn([right, up, down]);\n break;\n case 2:\n if (y === 0) execRandFn([left, down]);\n else if (y === 2) execRandFn([left, up]);\n else execRandFn([left, up, down]);\n break;\n default:\n if (y === 0) execRandFn([left, right, down]);\n else if (y === 2) execRandFn([left, right, up]);\n else execRandFn([left, right, up, down]);\n }\n };\n [...Array(10).keys()].map(move); // Trigger the random move 10 times\n\n return { blank, board, steps };\n }", "function cornerElim(tmp){\n // console.log('cornerElim is running with: '+tmp);\n //adjacent to 1\n if(tmp[0]===3&&tmp[1]===7){\n if(gamestate[2]===playerIdent){\n tmp=[7];\n }\n }\n //adjacent to 3\n if(tmp[0]===1&&tmp[1]===9){\n //console.log(gamestate[2])\n if(gamestate[2]===playerIdent){\n tmp=[9];\n }\n }\n //adjacent to 7\n if(tmp[0]===9&&tmp[1]===1){\n if(gamestate[8]===playerIdent){\n tmp=[1];\n }\n }\n //adjascent to 9\n if(tmp[0]===7&&tmp[1]===3){\n if(gamestate[8]===playerIdent){\n tmp=[3];\n }\n }\n // bug fix for when the AI is attempting 3 corners and chooses the incorrect corner.\n // choosing between 3 and 9\n if(tmp[0]===3&&tmp[1]===9){\n // console.log('clever player has tricked me into check 1');\n if(gamestate[2]===playerIdent){\n tmp=[9];\n }\n }\n // choosing between 1 and 7\n if(tmp[0]===1&&tmp[1]===7){\n // console.log('clever player has tricked me into check 2');\n if(gamestate[2]===playerIdent){\n tmp=[7];\n }\n }\n // choosing between 1 and 3\n if(tmp[0]===1&&tmp[1]===3){\n \n // console.log('clever player has tricked me into check 3');\n if(gamestate[4]===playerIdent){\n tmp=[3];\n }\n }\n // choosing between 7 and 9\n if(tmp[0]===7&&tmp[1]===9){\n \n //console.log('clever player has tricked me into check 4');\n if(gamestate[4]===playerIdent){\n tmp=[9];\n }\n }\n return tmp;\n }", "gomoryCut() {\n\t\tvar bbb = 0;\n\t\tvar ind, rest;\n\t\tfor (let i=0; i<this.n; i++) {\n\t\t\trest = this.b_numerator[i] % this.b_denominator[i];\n\t\t\tif (rest < 0) rest += this.b_denominator[i];\n\t\t\trest = rest / this.b_denominator[i];\n\t\t\tif (rest > bbb) {\n\t\t\t\tind = i;\n\t\t\t\tbbb = rest;\n\t\t\t}\n\t\t}\n\t\trest = this.b_numerator[ind] % this.b_denominator[ind];\n\t\tif (rest < 0) rest += this.b_denominator[ind];\n\t\tthis.b_numerator[this.n] = -rest;\n\t\tthis.b_denominator[this.n] = this.b_denominator[ind];\n\n\t\tvar arr_n = new Array(this.m);\n\t\tvar arr_d = new Array(this.m);\n\t\tfor (let i=0; i<this.m; i++) {\n\t\t\trest = this.numerator[ind][i] % this.denominator[ind][i];\n\t\t\tif (rest < 0) rest += this.denominator[ind][i];\n\t\t\tif (rest === 0) {\n\t\t\t\tarr_n[i] = 0;\n\t\t\t\tarr_d[i] = 1;\n\t\t\t} else {\n\t\t\t\tarr_n[i] = -rest;\n\t\t\t\tarr_d[i] = this.denominator[ind][i];\n\t\t\t}\n\t\t}\n\t\tthis.numerator[this.n] = arr_n;\n\t\tthis.denominator[this.n] = arr_d;\n\t\tthis.basis[this.n] = this.n + this.m + 1;\n\t\tthis.n += 1; \n\t}", "function genPswd() {\n userLength = parseInt(window.prompt(\"Please enter a number between 8 - 128 for the length of your password:\"));\n // IF condition 8 - 128 FALSE (no entry)\n if (!userLength) {\n // THEN DISPLAY alert \"requires input\"\n parseInt(window.alert(\"Your input was empty, this criteria is required!\"));\n // RECURSION\n return genPswd();\n // IF condition 8 - 128 FALSE (outside parameters)\n } else if (!(userLength >= 8 && userLength <= 128)) {\n // THEN DISPLAY alert \"number must be between 8 - 128\"\n parseInt(window.alert(\"Number chosen MUST be between 8 and 128.\"));\n // RECURSION\n return genPswd();\n // ELSE condition 8 - 128 is TRUE (using operators and logic)\n } else {\n //DISPLAY character-type confirmations\n yesSpec = window.confirm(\"Do you want to include special characters?\");\n yesNum = window.confirm(\"Do you want to include numbers?\");\n yesLo = window.confirm(\"Do you want to include lower-case characters?\");\n yesUp = window.confirm(\"Do you want to include upper-case characters?\");\n };\n\n // CONDITIONAL functions\n\n // 4 character-types: use concat for results\n if (yesSpec && yesNum && yesLo && yesUp) {\n userCriteria = special.concat(numbers, lowerCase, upperCase);\n }\n // 3 character-types\n // special + number + lo\n else if (yesSpec && yesNum && yesLo) {\n userCriteria = special.concat(numbers, lowerCase);\n }\n // special + number + up\n else if (yesSpec && yesNum && yesUp) {\n userCriteria = special.concat(numbers, upperCase);\n }\n // number + lo + up\n else if (yesNum && yesLo && yesUp) {\n userCriteria = numbers.concat(lowerCase, upperCase);\n }\n // 2 character-types\n // special + number\n else if (yesSpec && yesNum) {\n userCriteria = special.concat(numbers);\n }\n // special + lo\n else if (yesSpec && yesLo) {\n userCriteria = special.concat(lowerCase);\n }\n // special + up\n else if (yesSpec && yesUp) {\n userCriteria = special.concat(upperCase);\n }\n // number + lo\n else if (yesNum && yesLo) {\n userCriteria = numbers.concat(lowerCase);\n }\n // number + up\n else if (yesNum && yesUp) {\n userCriteria = numbers.concat(upperCase);\n }\n // lo + up\n else if (yesLo && yesUp) {\n userCriteria = lowerCase.concat(upperCase);\n }\n // 1 character-type\n // special only\n else if (yesSpec) {\n userCriteria = special;\n }\n // number only\n else if (yesNum) {\n userCriteria = numbers;\n }\n // lowercase only\n else if (yesLo) {\n userCriteria = lowerCase;\n }\n // uppercase only\n else if (yesUp) {\n userCriteria = upperCase;\n }\n // none ==> ALERT \"Must choose at least one character-type criteria.\"\"\n else if (!yesSpec && !yesNum && !yesLo && !yesUp) {\n window.alert(\"You MUST choose at least one character-type.\");\n };\n\n // Random selection for user chosen variables\n // variable to be declared locally so password results will not append *GOOD PRACTICE WHEN USING VAR\n var userPassword = []\n\n for (var i = 0; i < userLength; i++) {\n var randomArr = userCriteria[Math.floor(Math.random() * userCriteria.length)];\n userPassword.push(randomArr);\n }\n \n var e = userPassword.join(\"\");\n inputPassword(e);\n return e;\n}", "function solution()\n{\n\t// initialize correct-piece counter\n\tvar wincounter = piecenumber;\t\n\t\n\t// check each puzzle piece row by row\n\tfor (i = 0; i < piecerows; i++)\n\t{\n\t\tfor (j = 0; j < piececols; j++)\n\t\t{\n\t\t\t// get current position\n\t\t\tvar xcurr = $(\"#piece\" + i + j).position().left;\n\t\t\tvar ycurr = $(\"#piece\" + i + j).position().top;\n\t\t\t\n\t\t\t// get desired position\n\t\t\tvar ywin = i * piecesize;\n\t\t\tvar xwin = j * piecesize;\n\t\t\t\n\t\t\t// compare and score\n\t\t\tif ((Math.abs(xcurr - xwin) <= 10) && (Math.abs(ycurr - ywin) <= 10))\n\t\t\t\twincounter--;\n\t\t}\n\t}\n\t\n\t// debug\n\t// alert(\"Incorrect Pieces Remaining: \" + wincounter);\n\n\t// you win! maybe.\n\tif (wincounter == 0)\n\t{\n\t\t// freeze pieces\n\t\t$(\".piece\").draggable({disabled: true});\n\n\t\t// freeze solution checking\n\t\t$(\".piece\").unbind(\"mouseup\");\n\t\t\n\t\t// alert user\n\t\tyouwin();\n\t}\n\n}", "function victoriadiag2(casella,x,y) {\n var pj = casella.jugador;\n var int = 0;\n while (x < 7 && y >= 0) {\n x++; y--;\n }\n while (true) {\n x--; y++;\n if (x >= 0 && y < 6) {\n casella = array[y][x];\n if (casella.jugador == pj) {\n int++;\n } else {\n int = 0;\n }\n } else {\n break;\n }\n }\n if (int >= 4) {\n win = pj;\n }\n}", "function Vertical_Claiming(j,l)\r\n\t{\r\n\t\t//alert(\"Vertical\");\r\n\t\tvar Claim_Array = new Array(\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\");\r\n\t\tvar Claim_Index;\r\n\t\tvar Value_Length;\r\n\t\tvar Value;\r\n\t\tvar Claim_Array_Number = new Array(0,0,0,0,0,0,0,0,0);\r\n\t\t\r\n\t\tfor(var i=0; i<3; i++)\r\n\t\t{\r\n\t\t\tfor(var k=0; k<3; k++)\r\n\t\t\t{\r\n\t\t\t\tValue = Sudoku_Solution[i][j][k][l] + \"\";\r\n\t\t\t\tValue_Length = Value.length;\r\n\t\t\t\t//alert(Value + \" < Value Length > \" + Value_Length);\r\n\t\t\t\t//if(Value_Length > 1)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor(var v=0; v<Value_Length; v++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tClaim_Index = parseInt(i*3+k+1);\r\n\t\t\t\t\t\tClaim_Array[Value[v]-1] += Claim_Index;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t//alert(Claim_Array);\r\n\t\t\r\n\t\tfor(var s=0; s<9; s++)\r\n\t\t{\r\n\t\t\tClaim_Array_Number[s] = parseInt(Claim_Array[s]);\r\n\t\t}\r\n\t\r\n\t\tvar Values = Claim_Group_Elimination(Claim_Array_Number);\r\n\t\tif(Values == 0)\r\n\t\t\treturn true;\r\n\r\n\t\t//alert(\"Before : > \" + Claim_Array_Number);\r\n\t\t\t\r\n\t\tfor(var i=0; i<3; i++)\r\n\t\t{\r\n\t\t\tfor(var k=0; k<3; k++)\r\n\t\t\t{\r\n\t\t\t\tSudoku_Solution[i][j][k][l] = \"\";\r\n\t\t\t}\r\n\t\t}\r\n\t\tvar First_Index = 0;\r\n\t\tvar\tSecond_Index = 0;\r\n\t\t\r\n\t\tfor(var s=0; s<9; s++)\r\n\t\t{\r\n\t\t\tfor(var z=0; z<Values[s].length; z++)\r\n\t\t\t{\r\n\t\t\t\tValue = (Values[s][z]-1);\r\n\t\t\t\tFirst_Index = parseInt(Value/3);\r\n\t\t\t\tSecond_Index = Value%3;\r\n\t\t\t\ttry{\r\n\t\t\t\t\tSudoku_Solution[First_Index][j][Second_Index][l] += (s+1);\r\n\t\t\t\t}\r\n\t\t\t\tcatch(e)\r\n\t\t\t\t{\r\n\t\t\t\t\t// alert(Value + \" < Value, Indexs >\" + First_Index + \",\" + Second_Index);\r\n\t\t\t\t\tUser_Message = \"The Problem seems Very Incorrect.\";\r\n\t\t\t\t\tdocument.getElementById(\"User_Message\").innerHTML = User_Message;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t//alert(\"After : \" + Values);\r\n\t\t\t\r\n\t\treturn false;\r\n\t}", "function getpyraoptscramble(mn) {\n var j = 1, b = [], g = [], f = [], d = [], e = [], k = [], h = [], i = [];\n\n function u() {\n var c, p, q, l, m;\n for (p = 0; p < 720; p++) {\n g[p] = -1;\n d[p] = [];\n for (m = 0; m < 4; m++)d[p][m] = w(p, m)\n }\n g[0] = 0;\n for (l = 0; l <= 6; l++)for (p = 0; p < 720; p++)if (g[p] == l)for (m = 0; m < 4; m++) {\n q = p;\n for (c = 0; c < 2; c++) {\n q = d[q][m];\n if (g[q] == -1)g[q] = l + 1\n }\n }\n for (p = 0; p < 2592; p++) {\n f[p] = -1;\n e[p] = [];\n for (m = 0; m < 4; m++)e[p][m] = x(p, m)\n }\n f[0] = 0;\n for (l = 0; l <= 5; l++)for (p = 0; p < 2592; p++)if (f[p] == l)for (m = 0; m < 4; m++) {\n q = p;\n for (c = 0; c < 2; c++) {\n q = e[q][m];\n if (f[q] == -1)f[q] = l + 1\n }\n }\n for (c = 0; c < j; c++) {\n k = [];\n var t = 0, s = 0;\n q = 0;\n h = [0, 1, 2, 3, 4, 5];\n for (m = 0; m < 4; m++) {\n p = m + n(6 - m);\n l = h[m];\n h[m] = h[p];\n h[p] = l;\n if (m != p)s++\n }\n if (s % 2 == 1) {\n l = h[4];\n h[4] = h[5];\n h[5] = l\n }\n s = 0;\n i = [];\n for (m = 0; m < 5; m++) {\n i[m] = n(2);\n s += i[m]\n }\n i[5] = s % 2;\n for (m = 6; m < 10; m++) {\n i[m] = n(3)\n }\n for (m = 0; m < 6; m++) {\n l = 0;\n for (p = 0; p < 6; p++) {\n if (h[p] == m)break;\n if (h[p] > m)l++\n }\n q = q * (6 - m) + l\n }\n for (m = 9; m >= 6; m--)t = t * 3 + i[m];\n for (m = 4; m >= 0; m--)t = t * 2 + i[m];\n if (q != 0 || t != 0)for (m = mn; m < 99; m++)if (v(q, t, m, -1))break;\n b[c] = \"\";\n for (p = 0; p < k.length; p++)b[c] += [\"U\", \"L\", \"R\", \"B\"][k[p] & 7] + [\"\", \"'\"][(k[p] & 8) / 8] + \" \";\n var a = [\"l\", \"r\", \"b\", \"u\"];\n for (p = 0; p < 4; p++) {\n q = n(3);\n if (q < 2)b[c] += a[p] + [\"\", \"'\"][q] + \" \"\n }\n }\n }\n\n function v(q, t, l, c) {\n if (l == 0) {\n if (q == 0 && t == 0)return true\n } else {\n if (g[q] > l || f[t] > l)return false;\n var p, s, a, m;\n for (m = 0; m < 4; m++)if (m != c) {\n p = q;\n s = t;\n for (a = 0; a < 2; a++) {\n p = d[p][m];\n s = e[s][m];\n k[k.length] = m + 8 * a;\n if (v(p, s, l - 1, m))return true;\n k.length--\n }\n }\n }\n return false\n }\n\n function w(p, m) {\n var a, l, c, s = [], q = p;\n for (a = 1; a <= 6; a++) {\n c = Math.floor(q / a);\n l = q - a * c;\n q = c;\n for (c = a - 1; c >= l; c--)s[c + 1] = s[c];\n s[l] = 6 - a\n }\n if (m == 0)y(s, 0, 3, 1);\n if (m == 1)y(s, 1, 5, 2);\n if (m == 2)y(s, 0, 2, 4);\n if (m == 3)y(s, 3, 4, 5);\n q = 0;\n for (a = 0; a < 6; a++) {\n l = 0;\n for (c = 0; c < 6; c++) {\n if (s[c] == a)break;\n if (s[c] > a)l++\n }\n q = q * (6 - a) + l\n }\n return q\n }\n\n function x(p, m) {\n var a, l, c, t = 0, s = [], q = p;\n for (a = 0; a <= 4; a++) {\n s[a] = q & 1;\n q >>= 1;\n t ^= s[a]\n }\n s[5] = t;\n for (a = 6; a <= 9; a++) {\n c = Math.floor(q / 3);\n l = q - 3 * c;\n q = c;\n s[a] = l\n }\n if (m == 0) {\n s[6]++;\n if (s[6] == 3)s[6] = 0;\n y(s, 0, 3, 1);\n s[1] ^= 1;\n s[3] ^= 1\n }\n if (m == 1) {\n s[7]++;\n if (s[7] == 3)s[7] = 0;\n y(s, 1, 5, 2);\n s[2] ^= 1;\n s[5] ^= 1\n }\n if (m == 2) {\n s[8]++;\n if (s[8] == 3)s[8] = 0;\n y(s, 0, 2, 4);\n s[0] ^= 1;\n s[2] ^= 1\n }\n if (m == 3) {\n s[9]++;\n if (s[9] == 3)s[9] = 0;\n y(s, 3, 4, 5);\n s[3] ^= 1;\n s[4] ^= 1\n }\n q = 0;\n for (a = 9; a >= 6; a--)q = q * 3 + s[a];\n for (a = 4; a >= 0; a--)q = q * 2 + s[a];\n return q\n }\n\n function y(p, a, c, t) {\n var s = p[a];\n p[a] = p[c];\n p[c] = p[t];\n p[t] = s\n }\n\n function n(c) {\n return Math.floor(Math.random() * c)\n }\n\n u();\n ss[0] += b[0];\n}", "function finalImage() {\n if (totalCorrect < allQuestions.length && totalCorrect >= (allQuestions.length * .7)) {\n optionFinal = 1;\n } else if (totalCorrect <= (allQuestions.length * .6) && totalCorrect >= (allQuestions.length * .2)) {\n optionFinal = 2;\n } else if (totalCorrect !== allQuestions.length) {\n optionFinal = 3;\n }\n}", "function solution(juice, capacity) {\n // write your code in JavaScript (Node.js 8.9.4)\n\n let newCapacity = capacity;\n newCapacity.sort((a, b) => {\n return b - a;\n });\n let sumJuice = juice.reduce((a, b) => a + b, 0);\n\n if (newCapacity[0] >= sumJuice) {\n return juice.length;\n }\n\n let combine = juice.map((val, index) => {\n let spaceLeftInGlass = capacity[index] - val;\n let arr = [val, capacity[index], spaceLeftInGlass];\n return arr;\n });\n\n combine.sort((a, b) => {\n return b[2] - a[2] || b[1] - a[1];\n });\n\n let biggestSpace = combine[0][2];\n\n combine.splice(0, 1);\n combine.sort((a, b) => {\n return a[0] - b[0];\n });\n\n let maxMix = 1;\n\n for (let i = 0; i < combine.length; i++) {\n biggestSpace -= combine[i][0];\n\n if (biggestSpace < 0) {\n return maxMix;\n }\n maxMix++;\n }\n}", "function problem5(){\n var sN = 0;\n c=false;\n while(c===false){\n sN+=380;\n for(var x=3; x<=18;x++){\n if(sN%x!==0){\n break;\n }\n if(sN%x==0 && x===18){\n c=true;\n return sN;\n }\n }\n }\n}", "function cohenSutherlandClip(x1, y1, x2, y2,color){\n //calcular regiões P1, P2\n let dots = [];\n let code1 = computeCode(x1, y1);\n let code2 = computeCode(x2, y2);\n let accept = false;\n\n while(true){\n if((code1 == 0) && (code2 == 0)){\n accept = true;\n break;\n }\n else if(code1 & code2){\n break;\n }\n else {\n //Linha precisa de recorte\n //Pelo menos um dos pontos está fora\n let x, y, code_out;\n\n if (code1 != 0)\n code_out = code1;\n else\n code_out = code2;\n\n if (code_out & TOP) {\n x = x1 + (x2 - x1) * (y_max - y1) / (y2 - y1);\n y = y_max;\n } else if (code_out & BOTTOM) {\n x = x1 + (x2 - x1) * (y_min - y1) / (y2 - y1);\n y = y_min;\n } else if (code_out & RIGHT) {\n y = y1 + (y2 - y1) * (x_max - x1) / (x2 - x1);\n x = x_max;\n } else if (code_out & LEFT) {\n y = y1 + (y2 - y1) * (x_min - x1) / (x2 - x1);\n x = x_min;\n }\n\n if (code_out == code1) {\n x1 = x;\n y1 = y;\n code1 = computeCode(x1, y1);\n } else {\n x2 = x;\n y2 = y;\n code2 = computeCode(x2, y2);\n }\n }\n }\n console.log(accept);\n if (accept){\n desenha_linha(Math.round(x1), Math.round(y1),Math.round(x2),Math.round(y2),'black');\n\n return dots;\n\n }\n else{\n console.log('Line rejected');\n }\n\n}", "function test_countTransitiveClosurePossibilities2() {\n\tit('Test functions in CountTransitiveClosurePossibilities class', () => {\n\n\t\tallLegalLinePlacementsExpectedAnswer = [\n\t\t\t[2, 3, 4, 5],\n\t\t\t[4, 5],\n\t\t\t[1, 2, 3],\n\t\t\t[2, 3, 4],\n\t\t\t[0, 1, 2, 3],\n\t\t\t[0, 1]\n\t\t];\n\n\t\tlet graphClosure = new app._test.GraphClosure(6);\n\t\tlet transitiveClosureMatrix = graphClosure.transitiveClosure(mediumMatrix);\n\t\tlet countTransitiveClosurePossibilities = new app._test.CountTransitiveClosurePossibilities(transitiveClosureMatrix);\n\n\t\tlet allLegalLinePlacements = countTransitiveClosurePossibilities.legalLinePlacements;\n\t\tlet emptyArray = new Array(6);\n\t\tfor (let i = 0; i < emptyArray.length; i++) {\n\t\t\temptyArray[i] = -1;\n\t\t}\n\t\tlet expectedAnswer = [\n\t\t\t[5, 2, 0, 4, 3, 1],\n\t\t\t[4, 5, 0, 2, 3, 1],\n\t\t\t[5, 4, 0, 2, 3, 1],\n\t\t\t[5, 2, 4, 0, 3, 1],\n\t\t\t[4, 5, 2, 0, 3, 1],\n\t\t\t[5, 4, 2, 0, 3, 1],\n\t\t\t[5, 2, 3, 4, 0, 1],\n\t\t\t[5, 2, 4, 3, 0, 1],\n\t\t\t[4, 5, 2, 3, 0, 1],\n\t\t\t[5, 4, 2, 3, 0, 1],\n\t\t\t[4, 5, 3, 2, 0, 1],\n\t\t\t[5, 4, 3, 2, 0, 1],\n\t\t\t[5, 2, 3, 4, 1, 0],\n\t\t\t[5, 2, 4, 3, 1, 0],\n\t\t\t[4, 5, 2, 3, 1, 0],\n\t\t\t[5, 4, 2, 3, 1, 0],\n\t\t\t[4, 5, 3, 2, 1, 0],\n\t\t\t[5, 4, 3, 2, 1, 0]\n\t\t];\n\n\t\tassert.equal(allLegalLinePlacements.length, 6);\n\t\tassert.equal(allLegalLinePlacements.toString(), allLegalLinePlacementsExpectedAnswer.toString());\n\t\tassert.equal(expectedAnswer.toString(), countTransitiveClosurePossibilities.getAllAnswers().toString());\n\t});\n}", "function evaluate(b)\n{\n // Checking for Rows for X or O victory.\n for(let row = 0; row < 3; row++)\n {\n if (b[row][0] === b[row][1] &&\n b[row][1] === b[row][2])\n {\n if (b[row][0] === player)\n return +10;\n \n else if (b[row][0] === opponent)\n return -10;\n }\n }\n \n // Checking for Columns for X or O victory.\n for(let col = 0; col < 3; col++)\n {\n if (b[0][col] === b[1][col] &&\n b[1][col] === b[2][col])\n {\n if (b[0][col] === player)\n return +10;\n \n else if (b[0][col] === opponent)\n return -10;\n }\n }\n \n // Checking for Diagonals for X or O victory.\n if (b[0][0] === b[1][1] && b[1][1] === b[2][2])\n {\n if (b[0][0] === player)\n return +10;\n \n else if (b[0][0] === opponent)\n return -10;\n }\n \n if (b[0][2] === b[1][1] &&\n b[1][1] === b[2][0])\n {\n if (b[0][2] === player)\n return +10;\n \n else if (b[0][2] === opponent)\n return -10;\n }\n \n // Else if none of them have\n // won then return 0\n return 0;\n}", "function clean_cut(_layer_, pr_second_side_bool) {\n if (there_is_at_least_one_cut) {\n var bounds, www, hhh;\n var parsed_offset = parseFloat(offset);\n for (var j = 0; j < configuration_object[i].sides.length; j++) {\n var t_obj = configuration_object[i].sides[j];\n if (t_obj.type == finishings[0]) { // is 'cut | dociecie'\n app.activeDocument.activeLayer = _layer_;\n switch (t_obj.side) {\n case \"top\":\n bounds = app.activeDocument.activeLayer.bounds;\n www = bounds[2].value - bounds[0].value;\n hhh = bounds[3].value - bounds[1].value;\n resize_layer(app.activeDocument.activeLayer, www, hhh + parsed_offset,\n AnchorPosition.BOTTOMCENTER);\n if (pr_second_side_bool) {\n sec_side_resize(AnchorPosition.BOTTOMCENTER, 'VERTICAL');\n }\n break;\n case \"left\":\n bounds = app.activeDocument.activeLayer.bounds;\n www = bounds[2].value - bounds[0].value;\n hhh = bounds[3].value - bounds[1].value;\n resize_layer(app.activeDocument.activeLayer, www + parsed_offset, hhh,\n AnchorPosition.MIDDLERIGHT);\n if (pr_second_side_bool) {\n sec_side_resize(AnchorPosition.MIDDLELEFT, 'HORIZONTAL');\n }\n break;\n case \"right\":\n bounds = app.activeDocument.activeLayer.bounds;\n www = bounds[2].value - bounds[0].value;\n hhh = bounds[3].value - bounds[1].value;\n resize_layer(app.activeDocument.activeLayer, www + parsed_offset, hhh,\n AnchorPosition.MIDDLELEFT);\n if (pr_second_side_bool) {\n sec_side_resize(AnchorPosition.MIDDLERIGHT, 'HORIZONTAL');\n }\n break;\n case \"bottom\":\n bounds = app.activeDocument.activeLayer.bounds;\n www = bounds[2].value - bounds[0].value;\n hhh = bounds[3].value - bounds[1].value;\n resize_layer(app.activeDocument.activeLayer, www, hhh + parsed_offset,\n AnchorPosition.TOPCENTER);\n if (pr_second_side_bool) {\n sec_side_resize(AnchorPosition.TOPCENTER, 'VERTICAL');\n }\n break;\n }\n }\n }\n }\n }", "function scoreSolution(solution) {\n\n}", "function main() {\n var T = parseInt(readLine());\n \n for(var a0 = 0; a0 < T; a0++){\n \n \n var n = parseInt(readLine());\n q = readLine().split(' ');\n q = q.map(Number);\n \n \n q = [0].concat(q);\n \n var working =[0];\n \n var pending =[];\n \n for(var i =1;i<=n;i++){\n working.push(i);\n }\n \n var solution =0;\n \n //console.log('\\n',q,'\\n');\n \n for(var i=1;i<=n;i++){\n \n //console.log('ITERATION::',i)\n \n //console.log(working);\n\n \n //console.log('Q: ',q[i],' WORKING: ',working[i]);\n \n if(q[i]!= working[i] ){\n \n var index = working.indexOf(q[i]);\n \n var target =i;\n \n //console.log('TARGET: ',target,'INDEX: ',index);\n \n if( (index - target) > 2 || (target>index) ){\n pending.push({index:index,target:target,element:q[i]})\n }\n else{\n \n var element = working.splice(index,1);\n \n var rest = working.splice(target);\n \n var working = working.concat(element,rest);\n \n solution += index-target;\n }\n \n //console.log('SOLUTION: ',solution);\n \n }\n \n //console.log(working);\n\n \n var stopCondition =true;\n \n for(var j=1;j<n;j++){\n if(q[j]!== working[j]){\n stopCondition =false;\n break;\n }\n }\n \n if(stopCondition){\n console.log(solution);\n break;\n }\n \n }\n \n \n if(pending.length>0){\n console.log('Too chaotic')\n }\n \n \n \n \n }\n\n}", "function cutFruitPieces(fruit) {\r\n return fruit * 4;\r\n}", "function crop(fileName, newName) {\r\n let input = `examples/${fileName}.gif`,\r\n output = \"build/img/\";\r\n\r\n c(input, output, {compress_force: false, statistic: true, autoupdate: true}, false,\r\n {jpg: {engine: false, command: false}},\r\n {png: {engine: false, command: false}},\r\n {svg: {engine: false, command: false}},\r\n {gif: {engine: \"gifsicle\", command: [\"--colors=256\", \"--crop=0,0+-110x-0\", \"--lossy=100\"]}},\r\n // {gif: {engine: \"gifsicle\", command: [\"--colors\", \"256\", \"--crop\", \"516,0+-0x-0\"]}},\r\n\r\n function (error, completed, statistic) {\r\n console.log(\"-------------\");\r\n console.log(error);\r\n console.log(completed);\r\n console.log(statistic);\r\n console.log(\"-------------\");\r\n\r\n if (completed) {\r\n fs.rename(path.resolve(statistic.path_out_new), path.resolve(`build/img/${newName}.gif`), function (err) {\r\n if (err) console.log('ERROR: ' + err);\r\n });\r\n }\r\n }\r\n );\r\n}", "function hideChars(m)\n{\n var counter = m;\n var random;\n \n //Blanking the numbers in the solution array\n while(counter>0)\n {\n for(i=0;i<4;i++)\n {\n for(j=0;j<4;j++)\n {\n random = Math.random();\n\n if(random>0.5)\n {\n if(counter>0)\n {\n if(hiddenSolution[i][j]!='X')\n {\n hiddenSolution[i][j]='X';\n counter--;\n }\n else\n {\n continue;\n }\n }\n else if( i*j <= 9)\n {\n hiddenSolution[i][j] = theSolution[i][j];\n }\n else\n {\n continue;\n }\n }\n else\n {\n hiddenSolution[i][j] = theSolution[i][j];\n }\n }\n } \n } \n}", "solutionCheck() {\n for (let row = 0; row < HEIGHT; row++) {\n for (let col = 0; col < WIDTH; col++) {\n let num = this._puzzle[row][col];\n this._puzzle[row][col] = 0;\n if (num === 0 || !this.isSafe(this._puzzle, row, col, num)) {\n this._puzzle[row][col] = num;\n return false;\n }\n this._puzzle[row][col] = num;\n }\n }\n return true;\n }", "function kangaroo(x1, v1, x2, v2) {\n\n // limiting condition:\n // if a kroo begins further from another AND hops faster than the other,\n // then there is no way the other can catch up. So print NO.\n if ((x1 > x2 && v1 > v2) || (x2 > x1 && v2 > v1)){\n return \"NO\"\n }\n\n // if they are jumping equally from the same point thent it's always a YES\n if (x1 == x2 && v1 == v2) {\n return 'YES'\n }\n // if they are starting from the same place and one of them hops higher than the other then its a NO\n if (x1 == x2 && (v1 != v2)) {\n return 'NO'\n }\n\n\n //// THIS IS BRUTEFORCE. EXPECT LARGE TEST CASES TO TIMEOUT/////\n // let found = false;\n // let steps = 0;\n // while (!found) {\n // console.log('not found yet.');\n // x1 += v1;\n // console.log('x1+v1: ', x1);\n // x2 += v2;\n // console.log('x2+v2: ', x2);\n // ++steps;\n // if (x1 == x2) {\n // found = true;\n // console.log('found something after steps: ', steps)\n // return \"YES\"\n // }\n // }\n //////////////////////////////////////////////////////////////\n\n // for YES, x2 - x1 and v2 - v1 must be positive\n if ((x2 - x1) % (v2 - v1) == 0) {\n return 'YES'\n }\n else return 'NO'\n\n\n}", "function doneOrNot(board) {\r\n let sliceStart = 0;\r\n let sliceEnd = 3;\r\n let index = 0;\r\n let result = \"Finished!\";\r\n let arr = board;\r\n\r\n function checkHorizontalAndVertical(arr) {\r\n for (let i = 0; i < arr.length; ++i) {\r\n let horizontal = new Set(arr[i]);\r\n if (horizontal.size < 9) result = \"Try again!\";\r\n let vertical = [];\r\n let verticalSet;\r\n for (let j = 0; j < arr.length; ++j) {\r\n vertical.push(arr[j][i]);\r\n verticalSet = new Set(vertical);\r\n }\r\n if (verticalSet.size < 9) result = \"Try again!\";\r\n }\r\n }\r\n\r\n function sectionCheck(arr, sliceStart, sliceEnd, index) {\r\n if (sliceStart > 6) {\r\n index = index + 3;\r\n sliceStart = 0;\r\n sliceEnd = 3;\r\n }\r\n if (index == 9) return result;\r\n let section = [\r\n arr[index].slice(sliceStart, sliceEnd),\r\n arr[index + 1].slice(sliceStart, sliceEnd),\r\n arr[index + 2].slice(sliceStart, sliceEnd),\r\n ];\r\n let flattened = [];\r\n section = section.map((array) => array.map((num) => flattened.push(num)));\r\n let set = new Set(flattened);\r\n\r\n if (set.size < 9) result = \"Try again!\";\r\n\r\n sliceStart = sliceStart + 3;\r\n sliceEnd = sliceEnd + 3;\r\n\r\n sectionCheck(arr, sliceStart, sliceEnd, index);\r\n }\r\n\r\n checkHorizontalAndVertical(arr);\r\n sectionCheck(arr, sliceStart, sliceEnd, index);\r\n return result;\r\n}", "function destCount()\n{\n var status=false;\n var b = document.getElementById(\"boat1\");\n var saints1 = b.querySelectorAll(\"img.saint\");\n var canni1 = b.querySelectorAll(\"img.canni\");\n\n\n var dest = document.getElementById(\"dest\");\n var saints = dest.querySelectorAll(\"img.saint\");\n var canni = dest.querySelectorAll(\"img.canni\");\n\n\n // alert(saints.length+\"\"+saints1.length +\" and\" +canni.length+\":\"+canni1.length);\n //alert(saints.length+saints1.length+canni.length+canni1.length);\n if(saints.length+saints1.length==canni.length+canni1.length){\n //alert(\"con1\");\n if(saints.length==1 && canni.length==2){\n // alert(\"con4\")\n status=false;\n }else\n status=true;\n }\n else if(saints.length+saints1.length==0){\n // alert(\"con2\");\n status=true;\n }\n else if (saints.length+saints1.length>canni.length+canni1.length) {\n // alert(\"con3\");\n status = true;\n }\n else\n {\n //alert(\"con5\");\n status=false;\n }\n\n\n if ((saints.length+saints1.length+canni.length+canni1.length)==6) {\n win();\n }\n return status;\n}", "function makeSolution(p)\n{\n for(var i = 0;i<4;i++)\n {\n for(var j = 0;j<4;j++)\n {\n for(var m = 0;m<4;m++)\n {\n var potentialSolution = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]];\n potentialSolution = permutePuzzle(puzzle,i,j,m);\n if(checkAllColumns(potentialSolution) && checkAllGrids(potentialSolution))\n {\n theSolution = potentialSolution;\n return theSolution;\n }\n\n }\n }\n\n }\n\n}", "function branchingProcess() {\n var implicantsPowerSet = powerSet(remainingImplicants);\n validSolutions = filterPowerSet(implicantsPowerSet); //array contains valid cominations\n var currentValidSolutions = validSolutions.slice();\n minimalSolutions = filterPossibleSolutions(currentValidSolutions); //array contains valid combainations with least cost\n}", "function dvakrat(cislo) {\r\n return cislo * 2;\r\n}", "function ninthProblem(){\n\tconsole.log('\\nProblem 9\\nIs the given point P(x, y) within a circle K({0, 0}, 5) and outside a rectangle'+\n\t'R(top = 1, left = -1, width = 6, height = 2)');\n\tvar circle = {\n\t\t1: {x: 1, y: 4, r: 3},\n\t\t2: {x: 3, y: 2, r: 3},\n\t\t3: {x: 0, y: 1, r: 3},\n\t\t4: {x: 4, y: 1, r: 3},\n\t\t5: {x: 2, y: 0, r: 3},\n\t\t6: {x: 4, y: 0, r: 3},\n\t\t7: {x: 2.5, y: 1.5, r: 3},\n\t\t8: {x: 3.5, y: 1.5, r: 3},\n\t\t9: {x: -100, y: -100, r: 3},\n\t\tc: 1\n\t},\n\t\trectangle = {top: 1, left: -1, width: 6, height: 2};\n\tfor(var item in circle) {\n\t\tvar insideCircle = (((circle[item].x - circle.c) * (circle[item].x - circle.c)) + \n\t\t\t\t\t\t\t((circle[item].y - circle.c) * (circle[item].y - circle.c))) <=\n\t\t\t\t\t\t\tcircle[item].r * circle[item].r;\n\t\tvar insideRect = (circle[item].x <= rectangle.left + rectangle.width) && (circle[item].x >= rectangle.left)\t&&\n\t\t\t\t\t\t(circle[item].y <= rectangle.top) && (circle[item].y >= rectangle.top - rectangle.height);\n\t\tif(insideCircle === true && insideRect !== true) {\n\t\t\tconsole.log('\\tPoint P(' + circle[item].x +', ' + circle[item].y + '): yes');\n\t\t} else {\n\t\t\tconsole.log('\\tPoint P(' + circle[item].x +', ' + circle[item].y + '): no');\n\t\t}\n\t}\n}", "function little_check(count,count2){\n\t\t\t\n\t\t\t//console.log(\"count \"+ count+\"count2 \"+count2);\t\t\t\n \t \t\tfor ( var x=count; x <= (count+2); x++) { // cycle the matrix rows...\n \t \t\t\tfor (var y=count2; y <= (count2+2); y++) { // ...and cycle the matrix cells\n\t\t\t\t\t//var BR=1;\n\n\t\t\t\t\t//console.log(\"matrx[x] \"+ x+\"martix[y] \"+y);\n\t\t\t\t\tif ((matrix[x][(count2+0)]) === \"p1\" && (matrix[x][(count2+1)]) === \"p1\" && (matrix[x][(count2+2)]) === \"p1\") { // If our cell has been 'tagged' p1 given x is (e.g 0) then: x0y0, x0y1, x0y2 would mean player one has 3 horizontal cells in a line = victory!\n\t\t\t\t\t\tif (player1 === true){\n\t\t\t\t\t\t//console.log(\"horizontal victory\")\n\t\t\t\t\t\t//console.log(\"player1 wins square row \"+BR+ \"column \"+BC )\n\t\t\t\t\t\twinner_show(BR,BC)\n\t\t\t\t\t\tlittlematrix[(BR-1)][(BC-1)]=\"p1\";\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\t\t}\n\t\t\t\t\t} \n\t\t\t\t\telse if\t( (matrix[(count+0)][y]) === \"p1\" && (matrix[(count+1)][y]) === \"p1\" && (matrix[(count+2)][y]) === \"p1\") { // Repeated for other conditions\n\t\t\t\t\t\tif (player1 === true){\n\t\t\t\t\t\t//console.log(\"vertical victory\")\n\t\t\t\t\t\t//console.log(\"player1 wins\")\n\t\t\t\t\t\twinner_show(BR,BC)\n\t\t\t\t\t\tlittlematrix[(BR-1)][(BC-1)]=\"p1\";\n\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if ((matrix[(count+0)][(count2+0)]) === \"p1\" && (matrix[(count+1)][(count2+1)]) === \"p1\" && (matrix[(count+2)][(count2+2)]) === \"p1\") {\n\t\t\t\t\t\tif (player1 === true){\n\t\t\t\t\t\tconsole.log(\"LtopRdown diagonal\")\n\t\t\t\t\t\tconsole.log(\"player1 wins\")\n\t\t\t\t\t\twinner_show(BR,BC)\n\t\t\t\t\t\tlittlematrix[(BR-1)][(BC-1)]=\"p1\";\n\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t} \n\t\t\t\t\telse if\t( (matrix[(count+0)][(count2+2)]) === \"p1\" && (matrix[(count+1)][(count2+1)]) === \"p1\" && (matrix[(count+2)][(count2+0)]) === \"p1\") {\t\n\t\t\t\t\t\tif (player1 === true){\n\t\t\t\t\t\tconsole.log(\"Rtop Ldown diagonal\")\n\t\t\t\t\t\tconsole.log(\"player1 wins\")\n\t\t\t\t\t\twinner_show(BR,BC)\n\t\t\t\t\t\tlittlematrix[(BR-1)][(BC-1)]=\"p1\";\n\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\n\t \t}", "function snip(contour,u,v,w,n,verts){var p;var ax,ay,bx,by;var cx,cy,px,py;ax=contour[verts[u]].x;ay=contour[verts[u]].y;bx=contour[verts[v]].x;by=contour[verts[v]].y;cx=contour[verts[w]].x;cy=contour[verts[w]].y;if(Number.EPSILON>(bx-ax)*(cy-ay)-(by-ay)*(cx-ax))return false;var aX,aY,bX,bY,cX,cY;var apx,apy,bpx,bpy,cpx,cpy;var cCROSSap,bCROSScp,aCROSSbp;aX=cx-bx;aY=cy-by;bX=ax-cx;bY=ay-cy;cX=bx-ax;cY=by-ay;for(p=0;p<n;p++){px=contour[verts[p]].x;py=contour[verts[p]].y;if(px===ax&&py===ay||px===bx&&py===by||px===cx&&py===cy)continue;apx=px-ax;apy=py-ay;bpx=px-bx;bpy=py-by;cpx=px-cx;cpy=py-cy;// see if p is inside triangle abc\naCROSSbp=aX*bpy-aY*bpx;cCROSSap=cX*apy-cY*apx;bCROSScp=bX*cpy-bY*cpx;if(aCROSSbp>=-Number.EPSILON&&bCROSScp>=-Number.EPSILON&&cCROSSap>=-Number.EPSILON)return false;}return true;}// takes in an contour array and returns", "function exercise07() {}", "HighlightCandidates (nn, ccs)\r\n { if (nn<0) { this.ExecCommands('',1); return; }\r\n let ii0=nn%8;\r\n let jj0=7-(nn-ii0)/8;\r\n let pp=this.Board[ii0][jj0];\r\n let cc=Math.sign(pp);\r\n let tt=(1-cc)/2;\r\n let dd, ddi, ddj, bb, jj, aa=new Array();\r\n let nna=0, ddA=0;\r\n if (ccs.charAt(0)==\"A\") ddA=1;\r\n\r\n if (Math.abs(pp)==6)\r\n { this.Board[ii0][jj0]=0;\r\n if (this.IsOnBoard(ii0, jj0+cc))\r\n { bb=this.Board[ii0][jj0+cc];\r\n if (bb==0)\r\n { this.Board[ii0][jj0+cc]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n aa[nna++]=String.fromCharCode(ii0+97)+(jj0+cc+1);\r\n this.Board[ii0][jj0+cc]=bb;\r\n if (2*jj0+5*cc==7)\r\n { bb=this.Board[ii0][jj0+2*cc];\r\n if (bb==0)\r\n { this.Board[ii0][jj0+2*cc]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n { nna-=ddA;\r\n aa[nna++]=String.fromCharCode(ii0+97)+(jj0+2*cc+1);\r\n }\r\n this.Board[ii0][jj0+2*cc]=bb;\r\n }\r\n }\r\n }\r\n }\r\n for (ddi=-1; ddi<=1; ddi+=2)\r\n { if (this.IsOnBoard(ii0+ddi, jj0+cc))\r\n { bb=this.Board[ii0+ddi][jj0+cc];\r\n if (bb*cc<0)\r\n { this.Board[ii0+ddi][jj0+cc]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n aa[nna++]=String.fromCharCode(ii0+ddi+97)+(jj0+cc+1);\r\n this.Board[ii0+ddi][jj0+cc]=bb;\r\n }\r\n }\r\n if (2*jj0-cc==7)\r\n { if (this.IsOnBoard(ii0+ddi, jj0))\r\n { if (this.Board[ii0+ddi][jj0]==-cc*6)\r\n { bb=this.Board[ii0+ddi][jj0+cc];\r\n if (bb==0)\r\n { if (this.MoveCount>this.StartMove)\r\n { this.CanPass=-1;\r\n dd=this.HistPiece[0][this.MoveCount-this.StartMove-1];\r\n if ((this.HistType[0][this.MoveCount-this.StartMove-1]==5)&&(Math.abs(this.HistPosY[0][this.MoveCount-this.StartMove-1]-this.Piece[1-this.MoveType][dd].Pos.Y)==2))\r\n this.CanPass=this.Piece[1-this.MoveType][dd].Pos.X;\r\n }\r\n else\r\n this.CanPass=this.EnPass;\r\n if (this.CanPass==ii0+ddi)\r\n { this.Board[ii0+ddi][jj0+cc]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n aa[nna++]=String.fromCharCode(ii0+ddi+97)+(jj0+cc+1);\r\n this.Board[ii0+ddi][jj0+cc]=bb;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n this.Board[ii0][jj0]=pp;\r\n }\r\n\r\n if (Math.abs(pp)==5)\r\n { this.Board[ii0][jj0]=0;\r\n for (ddi=-2; ddi<=2; ddi+=4)\r\n { for (ddj=-1; ddj<=1; ddj+=2)\r\n { if (this.IsOnBoard(ii0+ddi, jj0+ddj))\r\n { bb=this.Board[ii0+ddi][jj0+ddj];\r\n if (bb*cc<=0)\r\n { this.Board[ii0+ddi][jj0+ddj]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n aa[nna++]=String.fromCharCode(ii0+ddi+97)+(jj0+ddj+1);\r\n this.Board[ii0+ddi][jj0+ddj]=bb;\r\n }\r\n }\r\n }\r\n }\r\n for (ddi=-1; ddi<=1; ddi+=2)\r\n { for (ddj=-2; ddj<=2; ddj+=4)\r\n { if (this.IsOnBoard(ii0+ddi, jj0+ddj))\r\n { bb=this.Board[ii0+ddi][jj0+ddj];\r\n if (bb*cc<=0)\r\n { this.Board[ii0+ddi][jj0+ddj]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n aa[nna++]=String.fromCharCode(ii0+ddi+97)+(jj0+ddj+1);\r\n this.Board[ii0+ddi][jj0+ddj]=bb;\r\n }\r\n }\r\n }\r\n }\r\n this.Board[ii0][jj0]=pp;\r\n }\r\n\r\n if ((Math.abs(pp)==2)||(Math.abs(pp)==4))\r\n { this.Board[ii0][jj0]=0;\r\n dd=1;\r\n bb=0;\r\n while ((this.IsOnBoard(ii0+dd,jj0+dd))&&(bb==0))\r\n { bb=this.Board[ii0+dd][jj0+dd];\r\n if (bb*cc<=0)\r\n { this.Board[ii0+dd][jj0+dd]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n { aa[nna++]=String.fromCharCode(ii0+dd+97)+(jj0+dd+1);\r\n nna-=ddA;\r\n }\r\n this.Board[ii0+dd][jj0+dd]=bb;\r\n }\r\n dd++;\r\n }\r\n if (dd>1) nna+=ddA;\r\n dd=-1;\r\n bb=0;\r\n while ((this.IsOnBoard(ii0+dd,jj0+dd))&&(bb==0))\r\n { bb=this.Board[ii0+dd][jj0+dd];\r\n if (bb*cc<=0)\r\n { this.Board[ii0+dd][jj0+dd]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n { aa[nna++]=String.fromCharCode(ii0+dd+97)+(jj0+dd+1);\r\n nna-=ddA;\r\n }\r\n this.Board[ii0+dd][jj0+dd]=bb;\r\n }\r\n dd--;\r\n }\r\n if (dd<-1) nna+=ddA;\r\n dd=1;\r\n bb=0;\r\n while ((this.IsOnBoard(ii0+dd,jj0-dd))&&(bb==0))\r\n { bb=this.Board[ii0+dd][jj0-dd];\r\n if (bb*cc<=0)\r\n { this.Board[ii0+dd][jj0-dd]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n { aa[nna++]=String.fromCharCode(ii0+dd+97)+(jj0-dd+1);\r\n nna-=ddA;\r\n }\r\n this.Board[ii0+dd][jj0-dd]=bb;\r\n }\r\n dd++;\r\n }\r\n if (dd>1) nna+=ddA;\r\n dd=-1;\r\n bb=0;\r\n while ((this.IsOnBoard(ii0+dd,jj0-dd))&&(bb==0))\r\n { bb=this.Board[ii0+dd][jj0-dd];\r\n if (bb*cc<=0)\r\n { this.Board[ii0+dd][jj0-dd]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n { aa[nna++]=String.fromCharCode(ii0+dd+97)+(jj0-dd+1);\r\n nna-=ddA;\r\n }\r\n this.Board[ii0+dd][jj0-dd]=bb;\r\n }\r\n dd--;\r\n }\r\n if (dd<-1) nna+=ddA;\r\n this.Board[ii0][jj0]=pp;\r\n }\r\n\r\n\r\n if ((Math.abs(pp)==2)||(Math.abs(pp)==3))\r\n { this.Board[ii0][jj0]=0;\r\n dd=1;\r\n bb=0;\r\n while ((this.IsOnBoard(ii0+dd,jj0))&&(bb==0))\r\n { bb=this.Board[ii0+dd][jj0];\r\n if (bb*cc<=0)\r\n { this.Board[ii0+dd][jj0]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n { aa[nna++]=String.fromCharCode(ii0+dd+97)+(jj0+1);\r\n nna-=ddA;\r\n }\r\n this.Board[ii0+dd][jj0]=bb;\r\n }\r\n dd++;\r\n }\r\n if (dd>1) nna+=ddA;\r\n dd=-1;\r\n bb=0;\r\n while ((this.IsOnBoard(ii0+dd,jj0))&&(bb==0))\r\n { bb=this.Board[ii0+dd][jj0];\r\n if (bb*cc<=0)\r\n { this.Board[ii0+dd][jj0]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n { aa[nna++]=String.fromCharCode(ii0+dd+97)+(jj0+1);\r\n nna-=ddA;\r\n }\r\n this.Board[ii0+dd][jj0]=bb;\r\n }\r\n dd--;\r\n }\r\n if (dd<-1) nna+=ddA;\r\n dd=1;\r\n bb=0;\r\n while ((this.IsOnBoard(ii0,jj0+dd))&&(bb==0))\r\n { bb=this.Board[ii0][jj0+dd];\r\n if (bb*cc<=0)\r\n { this.Board[ii0][jj0+dd]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n { aa[nna++]=String.fromCharCode(ii0+97)+(jj0+dd+1);\r\n nna-=ddA;\r\n }\r\n this.Board[ii0][jj0+dd]=bb;\r\n }\r\n dd++;\r\n }\r\n if (dd>1) nna+=ddA;\r\n dd=-1;\r\n bb=0;\r\n while ((this.IsOnBoard(ii0,jj0+dd))&&(bb==0))\r\n { bb=this.Board[ii0][jj0+dd];\r\n if (bb*cc<=0)\r\n { this.Board[ii0][jj0+dd]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n { aa[nna++]=String.fromCharCode(ii0+97)+(jj0+dd+1);\r\n nna-=ddA;\r\n }\r\n this.Board[ii0][jj0+dd]=bb;\r\n }\r\n dd--;\r\n }\r\n if (dd<-1) nna+=ddA;\r\n this.Board[ii0][jj0]=pp;\r\n }\r\n\r\n if (Math.abs(pp)==1)\r\n { this.Board[ii0][jj0]=0;\r\n for (ddi=-1; ddi<=1; ddi++)\r\n { for (ddj=-1; ddj<=1; ddj++)\r\n { if (((ddi!=0)||(ddj!=0))&&(this.IsOnBoard(ii0+ddi, jj0+ddj)))\r\n { bb=this.Board[ii0+ddi][jj0+ddj];\r\n if (bb*cc<=0)\r\n { this.Board[ii0+ddi][jj0+ddj]=pp;\r\n if (!this.IsCheck(ii0+ddi, jj0+ddj, tt))\r\n aa[nna++]=String.fromCharCode(ii0+ddi+97)+(jj0+ddj+1);\r\n this.Board[ii0+ddi][jj0+ddj]=bb;\r\n }\r\n }\r\n }\r\n }\r\n this.Board[ii0][jj0]=pp;\r\n jj=this.CanCastleLong();//O-O-O with Chess960 rules\r\n if (jj>=0)\r\n { this.Board[ii0][jj0]=0;\r\n this.Board[this.Piece[this.MoveType][jj].Pos.X][this.Piece[this.MoveType][jj].Pos.Y]=0;\r\n this.Board[2][tt*7]=1-2*tt;\r\n this.Board[3][tt*7]=3*(1-2*tt);\r\n ddi=ii0;\r\n bb=0;\r\n { while (ddi>2)\r\n { bb+=this.IsCheck(ddi, tt*7, tt);\r\n ddi--;\r\n }\r\n while (ddi<2)\r\n { bb+=this.IsCheck(ddi, tt*7, tt);\r\n ddi++;\r\n }\r\n }\r\n bb+=this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, this.MoveType);\r\n if (bb==0) aa[nna++]=String.fromCharCode(2+97)+(tt*7+1);\r\n this.Board[2][tt*7]=0;\r\n this.Board[3][tt*7]=0;\r\n this.Board[ii0][jj0]=pp;\r\n this.Board[this.Piece[tt][jj].Pos.X][this.Piece[tt][jj].Pos.Y]=cc*3;\r\n }\r\n jj=this.CanCastleShort();//O-O with Chess960 rules\r\n if (jj>=0)\r\n { this.Board[ii0][jj0]=0;\r\n this.Board[this.Piece[this.MoveType][jj].Pos.X][this.Piece[this.MoveType][jj].Pos.Y]=0;\r\n this.Board[6][tt*7]=1-2*tt;\r\n this.Board[5][tt*7]=3*(1-2*tt);\r\n ddi=ii0;\r\n bb=0;\r\n { while (ddi>2)\r\n { bb+=this.IsCheck(ddi, tt*7, tt);\r\n ddi--;\r\n }\r\n while (ddi<2)\r\n { bb+=this.IsCheck(ddi, tt*7, tt);\r\n ddi++;\r\n }\r\n }\r\n bb+=this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, this.MoveType);\r\n if (bb==0) aa[nna++]=String.fromCharCode(6+97)+(tt*7+1);\r\n this.Board[6][tt*7]=0;\r\n this.Board[5][tt*7]=0;\r\n this.Board[ii0][jj0]=pp;\r\n this.Board[this.Piece[tt][jj].Pos.X][this.Piece[tt][jj].Pos.Y]=cc*3;\r\n }\r\n }\r\n\r\n if ((nna>0)&&(ccs!=\" \"))\r\n { tt=ccs.charAt(0);\r\n cc=ccs.substr(1,6);\r\n if (tt==\"A\")\r\n { bb=tt+String.fromCharCode(ii0+97)+(jj0+1)+aa[0]+cc;\r\n for (jj=1; jj<nna; jj++) bb+=\",\"+tt+String.fromCharCode(ii0+97)+(jj0+1)+aa[jj]+cc;\r\n }\r\n else\r\n { bb=tt+aa[0]+cc;\r\n for (jj=1; jj<nna; jj++) bb+=\",\"+tt+aa[jj]+cc;\r\n }\r\n this.ExecCommands(bb,1);\r\n }\r\n else return(aa);\r\n }", "function genSides(x){\r\n ro = [];\r\n co = [];\r\n for(var i = 0; i < x; i++){\r\n var c = 0;\r\n var cStr = \"\";\r\n var cBoo = false;\r\n\r\n var r = 0;\r\n var rStr = \"\";\r\n var rBoo = false;\r\n for(var k = 0; k < x; k++){\r\n if((cBoo == true && puz[i][k] == 0)|| (cBoo == true && puz[i][k] == 2)){\r\n cStr += c;\r\n c = 0;\r\n cBoo = false;\r\n cStr += \"<br>\";\r\n }\r\n\r\n if(puz[i][k] == 1){\r\n c++;\r\n cBoo = true;\r\n }\r\n\r\n if(k == (x-1) && puz[i][k] == 1){\r\n cStr += c;\r\n c = 0;\r\n cBoo = false;\r\n cStr += \" \";\r\n }\r\n\r\n if((rBoo == true && puz[k][i] == 0) || (rBoo == true && puz[k][i] == 2)){\r\n rStr += r;\r\n r = 0;\r\n rBoo = false;\r\n rStr += \" \";\r\n }\r\n\r\n if(puz[k][i] == 1){\r\n r++;\r\n rBoo = true;\r\n }\r\n\r\n if(k == (x-1) && puz[k][i] == 1){\r\n rStr += r;\r\n r = 0;\r\n rBoo = false;\r\n rStr += \" \";\r\n }\r\n }\r\n co.push(cStr);\r\n ro.push(rStr);\r\n }\r\n}", "canBeSet(row,col,bNum,vert1ORhorz2){\n\n let code=0\n if(vert1ORhorz2===1){\n let up=true;\n // let down=true;\n \n // if(row-bNum<0){\n // down=false;\n // }\n if(row+bNum>8){\n up=false;\n }\n for(let upn=row; upn<row+bNum; upn++){\n if(this.boatOnBoard[upn][col]!=0){\n up=false;\n }\n\n }\n\n // for(let downn=row; downn>row-bNum ; downn--){\n // if(this.boatOnBoard[downn][col]!=0){\n // down = false;\n // }\n // }\n\n if(up===true){\n code=8;\n }\n // if(down===true){\n // code =2;\n // }\n\n }\n else{\n let left=true;\n let right=true;\n\n if(col-bNum<0){\n left=false;\n }\n if(col+bNum>8){\n right=false;\n }\n\n for(let leftn=col; leftn>col-bNum; leftn--){\n if(this.boatOnBoard[row][leftn]!=0){\n left = false;\n }\n }\n for(let rightn=col; rightn<col+bNum; rightn++){\n if(this.boatOnBoard[row][rightn]!=0){\n right=false;\n }\n }\n if(left===true){\n code=4;\n }\n if(right===true){\n code=6;\n }\n }\n\n return code;\n\n }", "function trimmed(number){\n\tdiv = document.getElementById('hide4')\n div.style.display = \"block\";\n if (number == 1){\n\t\tvar c=document.getElementById(\"2choice\");\n\t\tvar ctx=c.getContext(\"2d\");\n\t\tctx.drawImage(img,0,0, c.width, c.height);\n\t\t\t\n\t ctx.rect(0,0,sliceB.start*4,c.height);\n\t\tctx.lineWidth = 0;\n\t\tctx.fillStyle = '#FFFFFF';\n\t\tctx.fill();\n\t\tctx.stroke();\n\t\t\t\n\t\tctx.rect(sliceB.end*4,0,c.width,c.height);\n\t\tctx.lineWidth = 0;\n\t\tctx.fillStyle = '#FFFFFF';\n\t\tctx.fill();\n\t\tctx.stroke();\n\t\t\t\n\t\tvar d=document.getElementById(\"2choice2\");\n\t\tvar ctx=d.getContext(\"2d\");\n\t\tctx.drawImage(img,0,0, c.width, c.height);\n\t\t\t\n\t\tctx.rect(0,0,sliceC.start*4,c.height);\n\t\tctx.lineWidth = 0;\n\t\tctx.fillStyle = '#FFFFFF';\n\t\tctx.fill();\n\t\tctx.stroke();\n\t\t\t\n\t\tctx.rect(sliceC.end*4,0,c.width,c.height);\n\t\tctx.lineWidth = 0;\n\t\tctx.fillStyle = '#FFFFFF';\n\t\tctx.fill();\n\t\tctx.stroke();\n\t}else{\n\t\tif (number == 2){\n\t\t\tvar c=document.getElementById(\"2choice\");\n\t\t\tvar ctx=c.getContext(\"2d\");\n\t\t\tctx.drawImage(img,0,0, c.width, c.height);\n\t\t\t\n\t\t\tctx.rect(0,0,sliceA.start*4,c.height);\n\t\t\tctx.lineWidth = 0;\n\t\t\tctx.fillStyle = '#FFFFFF';\n\t\t\tctx.fill();\n\t\t\tctx.stroke();\n\t\t\t\t\n\t\t\tctx.rect(sliceA.end*4,0,c.width,c.height);\n\t\t\tctx.lineWidth = 0;\n\t\t\tctx.fillStyle = '#FFFFFF';\n\t\t\tctx.fill();\n\t\t\tctx.stroke();\n\t\t\t\t\n\t\t\tvar d=document.getElementById(\"2choice2\");\n\t\t\tvar ctx=d.getContext(\"2d\");\n\t\t\tctx.drawImage(img,0,0, c.width, c.height);\n\t\t\t\t\n\t\t\tctx.rect(0,0,sliceC.start*4,c.height);\n\t\t\tctx.lineWidth = 0;\n\t\t\tctx.fillStyle = '#FFFFFF';\n\t\t\tctx.fill();\n \tctx.stroke();\n\t\t\t\t\n\t\t\tctx.rect(sliceC.end*4,0,c.width,c.height);\n\t\t\tctx.lineWidth = 0;\n\t\t\tctx.fillStyle = '#FFFFFF';\n\t\t\tctx.fill();\n\t\t\tctx.stroke();\n\t\t\t\t\n\t\t}else{\n\t\t\tvar c=document.getElementById(\"2choice\");\n\t\t\tvar ctx=c.getContext(\"2d\");\n\t\t\tctx.drawImage(img,0,0, c.width, c.height);\n\t\t\t\t\n\t\t\tctx.rect(0,0,sliceA.start*4,c.height);\n\t\t\tctx.lineWidth = 0;\n\t\t\tctx.fillStyle = '#FFFFFF';\n\t\t\tctx.fill();\n\t\t\tctx.stroke();\n\t\t\t\t\n\t\t\tctx.rect(sliceA.end*4,0,c.width,c.height);\n\t\t\tctx.lineWidth = 0;\n\t\t\tctx.fillStyle = '#FFFFFF';\n\t\t\tctx.fill();\n\t\t\tctx.stroke();\n\t\t\t\t\n\t\t\tvar d=document.getElementById(\"2choice2\");\n\t\t\tvar ctx=d.getContext(\"2d\");\n\t\t\tctx.drawImage(img,0,0, c.width, c.height);\n\t\t\t\t\n\t\t\tctx.rect(0,0,sliceB.start*4,c.height);\n\t\t\tctx.lineWidth = 0;\n\t\t\tctx.fillStyle = '#FFFFFF';\n\t\t\tctx.fill();\n\t\t\tctx.stroke();\n\t\t\t\t\n\t\t\tctx.rect(sliceB.end*4,0,c.width,c.height);\n\t\t\tctx.lineWidth = 0;\n\t\t\tctx.fillStyle = '#FFFFFF';\n\t\t\tctx.fill();\n\t\t\tctx.stroke();\n\t\t}\n\t}\n}", "function solve(args) { // много добро решение за 100 точки\n var dimensions = args[0].split(' ').map(Number);\n\n var matrix = new Array(dimensions[0]);\n for (var i = 0; i < dimensions[0]; i += 1) {\n matrix[i] = args[i + 1].split(' ').map(Number);\n\n for (var j = 0; j < dimensions[1]; j += 1) {\n matrix[i][j] = getBin(matrix[i][j]);\n }\n }\n\n var startRow = dimensions[0] / 2 | 0,\n startCol = dimensions[1] / 2 | 0;\n\n while (true) {\n var storedRow = startRow,\n storedCol = startCol;\n\n if (matrix[startRow][startCol][3] === '1' && matrix[startRow - 1][startCol] !== '0') {\n startRow -= 1;\n } else if (matrix[startRow][startCol][2] === '1' && matrix[startRow][startCol + 1] !== '0') {\n startCol += 1\n } else if (matrix[startRow][startCol][1] === '1' && matrix[startRow + 1][startCol] !== '0') {\n startRow += 1;\n } else if (matrix[startRow][startCol][0] === '1' && matrix[startRow][startCol - 1] !== '0') {\n startCol -= 1\n } else {\n console.log('No JavaScript, only rakiya ' + storedRow + ' ' + storedCol)\n break;\n }\n\n if (startCol === 0 || startCol === dimensions[1] - 1 || startRow === 0 || startRow === dimensions[0] - 1) {\n console.log('No rakiya, only JavaScript ' + startRow + ' ' + startCol);\n break;\n }\n matrix[storedRow][storedCol] = '0'; // маркираме си с нула клетките, в който вече сме били!!!\n }\n\n function getBin(number) {\n var bin = '000' + number.toString(2);\n return bin.substr(bin.length - 4, 4)\n }\n}", "function cornerSolve(position){\n\t\t\t\tswitch(position){\n\t\t\t\t\tcase 'A':\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\tcase 'B':\n\t\t\t\t\t\tR(); DPrime();\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\t\tD(); RPrime()\n\t\t\t\t\t\t;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'C':\n\t\t\t\t\t\tF();\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\t\tFPrime();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'D':\n\t\t\t\t\t\tF(); RPrime();\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\t\tR(); FPrime();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'E':\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\tcase 'F':\n\t\t\t\t\t\tF2();\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\t\tF2();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'G':\n\t\t\t\t\t\tD2(); R();\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\t\tRPrime(); D2();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'H':\n\t\t\t\t\t\tD2();\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\t\tD2();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'I':\n\t\t\t\t\t\tFPrime(); D();\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\t\tDPrime(); F();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'J':\n\t\t\t\t\t\tF2(); D();\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\t\tDPrime(); F2();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'K':\n\t\t\t\t\t\tF(); D();\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\t\tDPrime(); FPrime();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'L':\n\t\t\t\t\t\tD();\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\t\tDPrime();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'M':\n\t\t\t\t\t\tRPrime();\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\t\tR();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'N':\n\t\t\t\t\t\tR2();\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\t\tR2();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'O':\n\t\t\t\t\t\tR();\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\t\tRPrime();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'P':\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'Q':\n\t\t\t\t\t\tRPrime(); F();\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\t\tFPrime(); R();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'R':\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\tcase 'S':\n\t\t\t\t\t\tDPrime(); R();\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\t\tRPrime(); D();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'T':\n\t\t\t\t\t\tDPrime(); \n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\t\tD();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'U':\n\t\t\t\t\t\tFPrime();\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\t\tF();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'V':\n\t\t\t\t\t\tDPrime(); FPrime();\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\t\tF(); D();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'W':\n\t\t\t\t\t\tD2(); FPrime();\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\t\tF(); D2();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'X':\n\t\t\t\t\t\tD(); FPrime();\n\t\t\t\t\t\tcornerAlgorithm();\n\t\t\t\t\t\tF(); DPrime();\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t} \n\n\t\t\t}", "function solve() {\n board = Board();\n previous = Board();\n var u = unknowns();\n for (;;) {\n var v = u;\n if (show()) {\n put(\"The board is inconsistent.\");\n board = null;\n return true;\n }\n if (u == dim2 * dim2)\n break;\n uniqall();\n u = unknowns();\n if (u < v) {\n put(\"By known value must be unique in row, column, and square.\");\n continue;\n }\n uniqsqr();\n u = unknowns();\n if (u < v) {\n put(\"By only one place for value in square.\");\n continue;\n }\n uniqrow();\n u = unknowns();\n if (u < v) {\n put(\"By only one place for value in row.\");\n continue;\n }\n uniqcol();\n u = unknowns();\n if (u < v) {\n put(\"By only one place for value in column.\");\n continue;\n }\n uniqrowline();\n u = unknowns();\n if (u < v) {\n put(\"By values in square preclude others in a row.\");\n continue;\n }\n uniqcolline();\n u = unknowns();\n if (u < v) {\n put(\"By values in square preclude others in a column.\");\n continue;\n }\n uniqcolsqr();\n u = unknowns();\n if (u < v) {\n put(\"By only one columm value in square.\");\n continue;\n }\n uniqrowsqr();\n u = unknowns();\n if (u < v) {\n put(\"By only one row for value in square.\");\n continue;\n }\n pairsqr();\n u = unknowns();\n if (u < v) {\n put(\"By pair has only two places in square.\");\n continue;\n }\n pairrow();\n u = unknowns();\n if (u < v) {\n put(\"By pair has only two places in row.\");\n continue;\n }\n paircol();\n u = unknowns();\n if (u < v) {\n put(\"By pair has only two places in column.\");\n continue;\n }\n triplesqr();\n u = unknowns();\n if (u < v) {\n put(\"By triple has only three places in square.\");\n continue;\n }\n triplerow();\n u = unknowns();\n if (u < v) {\n put(\"By triple has only three places in row.\");\n continue;\n }\n triplecol();\n u = unknowns();\n if (u < v) {\n put(\"By triple has only three places in column.\");\n continue;\n }\n quadsqr();\n u = unknowns();\n if (u < v) {\n put(\"By quad has only four places in square.\");\n continue;\n }\n quadrow();\n u = unknowns();\n if (u < v) {\n put(\"By quad has only four places in row.\");\n continue;\n }\n quadcol();\n u = unknowns();\n if (u < v) {\n put(\"By quad has only four places in column.\");\n continue;\n }\n break;\n }\n put(\"Final board.\");\n if (show()) {\n put(\"The board is inconsistent.\");\n board = null;\n return true;\n }\n if (u > dim2 * dim2)\n put(\"The board is unfinished.\");\n board = null;\n return true;\n}", "function slicepuzzle()\n{\n\t// get number of pieces from input form\n\tpiecenumber = $(\"input[name=piecenumber]:checked\").val();\n\t\n\t// total number of pixels in the photo\n\ttotalpixels = photox * photoy;\n\t\n\t// total number of pixels in each puzzle piece\n\tpiecepixels = totalpixels / piecenumber;\n\t\n\t// x and y dimension of square piece\n\tpiecesize = Math.sqrt(piecepixels);\n\n\t// number of rows and columns of pieces inside photo\n\tpiecerows = photoy / piecesize;\n\tpiececols = photox / piecesize;\n\t\t\n\t// create puzzle pieces row by row\n\tfor (i = 0; i < piecerows; i++)\n\t{\n\t\tfor (j = 0; j < piececols; j++)\n\t\t{\n\t\t\t// create piece and number it by id\n\t\t\t$(\"#puzzlec\").append(\"<div class='piece' id='piece\" + i + j + \"'></div>\");\n\t\t\t\n\t\t\t// set user-selected (or default) background-image of each piece and resize\n\t\t\t$(\"#piece\" + i + j).css(\"background-image\", pic);\n\t\t\t$(\"#piece\" + i + j).css(\"background-size\", bgsize);\n\t\t\t\n\t\t\t// set position of imaage inside of piece\n\t\t\tvar xpos = (-1 * piecesize) * j;\n\t\t\tvar ypos = (-1 * piecesize) * i;\n\t\t\tvar bgpos = xpos + \"px \" + ypos + \"px\";\n\t\t\t$(\"#piece\" + i + j).css(\"background-position\", bgpos);\n\t\t\t\n\t\t\t// here's that amazing jQuery magic for dragging DIV's and snapping to grid\n\t\t\t$(\"#piece\" + i + j).draggable({containment: \"#puzzlec\"});\n\t\t\t$(\"#piece\" + i + j).draggable({snap: \"#puzzlec\"});\n\t\t\t$(\"#piece\" + i + j).draggable({snap: \".piece\"});\t\t\n\t\t}\n\t}\n\t\n\t// set the width and height for all pieces in the css class, including 1px border on each edge\n\t$(\".piece\").css(\"width\", piecesize-2);\n\t$(\".piece\").css(\"height\", piecesize-2);\n\t\n\t// fade in completed puzzle\n\t$(\"#puzzlec\").animate({opacity: \"1\"},500,\"linear\");\n\n\t// randomize piece placement!\n\tshakepuzzle();\n\n\t// start checking for solutions\n\t$(\".piece\").mouseup(function(){solution();});\n}", "function getfilter(possmov){ \n var lim_pos={};\n var empt=document.getElementById(\"empty\").children;\n for(arre in possmov){\n var source_j=arre%10,source_i=(arre-source_j)/10,inc=0;\n lim_pos[arre]=[];\n for(values in possmov[arre]){\n var dest_j=possmov[arre][values]%10,dest_i=(possmov[arre][values]-dest_j)/10;\n var temp=board[dest_i][dest_j]; \n board[dest_i][dest_j]=board[source_i][source_j];\n board[source_i][source_j]=empt;\n swapuser();\n if(!ifCheck()){\n lim_pos[arre][inc++]=possmov[arre][values];\n }\n swapuser();\n board[source_i][source_j]=board[dest_i][dest_j];\n board[dest_i][dest_j]=temp;\n }\n }\n /*if(!checkbit){\n if(capable_castling[user][\"left\"]){\n var color=capable_castling[user][\"i\"];\n if( board[color][2].length==0 && board[color][1].length==0 && lim_pos[color+\"4\"].includes(color+\"3\")){\n swapuser();\n var cas_pos=autocalculate();\n var bit=true;\n for(arre in cas_pos){\n if(cas_pos[arre].includes(color+\"2\")){\n bit= false;\n break;\n }\n }\n swapuser();\n if(bit){\n lim_pos[color+\"4\"].push(color+\"2\");\n }\n } \n }\n if(capable_castling[user][\"right\"]){\n var color=capable_castling[user][\"i\"];\n \n if( board[color][6].length==0 && lim_pos[color+\"4\"].includes(color+\"5\")){\n swapuser();\n var cas_pos=autocalculate();\n var bit=true;\n for(arre in cas_pos){\n if(cas_pos[arre].includes(color+\"6\")){\n bit= false;\n break;\n }\n }\n swapuser();\n if(bit){\n lim_pos[color+\"4\"].push(color+\"6\");\n }\n } \n }\n }*/\n\n return lim_pos;\n}", "function cutFruitPieces(fruit){\n return fruit * 4;\n}", "function winConditions() {\n\t\tif (($scope.squares[0] == 1 && $scope.squares[1] == 1 && $scope.squares[2] == 1) || \n\t\t($scope.squares[3] == 1 && $scope.squares[4] == 1 && $scope.squares[5] == 1) ||\n\t\t($scope.squares[6] == 1 && $scope.squares[7] == 1 && $scope.squares[8] == 1) ||\n\t\t($scope.squares[0] == 1 && $scope.squares[3] == 1 && $scope.squares[6] == 1) ||\n\t\t($scope.squares[1] == 1 && $scope.squares[4] == 1 && $scope.squares[7] == 1) ||\n\t\t($scope.squares[2] == 1 && $scope.squares[5] == 1 && $scope.squares[8] == 1) ||\n\t\t($scope.squares[0] == 1 && $scope.squares[4] == 1 && $scope.squares[8] == 1) ||\n\t\t($scope.squares[2] == 1 && $scope.squares[4] == 1 && $scope.squares[6] == 1)) {\n\t\t\t$scope.booya=true;\n\t\t} else if (\n\t\t\t($scope.squares[0] == -1 && $scope.squares[1] == -1 && $scope.squares[2] == -1) || \n\t\t\t($scope.squares[3] == -1 && $scope.squares[4] == -1 && $scope.squares[5] == -1) ||\n\t\t\t($scope.squares[6] == -1 && $scope.squares[7] == -1 && $scope.squares[8] == -1) ||\n\t\t\t($scope.squares[0] == -1 && $scope.squares[3] == -1 && $scope.squares[6] == -1) ||\n\t\t\t($scope.squares[1] == -1 && $scope.squares[4] == -1 && $scope.squares[7] == -1) ||\n\t\t\t($scope.squares[2] == -1 && $scope.squares[5] == -1 && $scope.squares[8] == -1) ||\n\t\t\t($scope.squares[0] == -1 && $scope.squares[4] == -1 && $scope.squares[8] == -1) ||\n\t\t\t($scope.squares[2] == -1 && $scope.squares[4] == -1 && $scope.squares[6] == -1)) {\n\t\t\t\t$scope.iRanOutofWordsHere=true;\n\t\t// add reset game\n\t\t} else if (\n\t\t\t($scope.squares[0] == 1 || $scope.squares[0] == -1) && ($scope.squares[1] == 1 || $scope.squares[1] == -1) && \n\t\t \t($scope.squares[2] == 1 || $scope.squares[2] == -1) && ($scope.squares[3] == 1 || $scope.squares[3] == -1) && \n\t\t \t($scope.squares[4] == 1 || $scope.squares[4] == -1) && ($scope.squares[5] == 1 || $scope.squares[5] == -1) &&\n\t\t \t($scope.squares[6] == 1 || $scope.squares[6] == -1) && ($scope.squares[7] == 1 || $scope.squares[7] == -1) &&\n\t\t \t($scope.squares[8] == 1 || $scope.squares[8] == -1)) {\n\t\t \t\t$scope.itsatie=true;\n\t\t }\n\t\t\n\n\t\t\tif (playerOne == true) {\n\t\t\t\tplayerOne = false; \n\t\t\t}\n\t\t\telse {\n\t\t\t\tplayerOne = true;// =assigns; ==evaluates\n\t\t\t\t}\n\t}", "function special_cases() {\n //Inserts a zero into index 1 of equation array if the first input is an operation\n if (is_operator(equation_array[0])) {\n equation_array.unshift(\"0\");\n }\n ;\n var store_i = [];\n for (var i = 0; i < equation_array.length; i++) {\n //Checks for a divid by zero case\n if (equation_array[i] == \"/\" && equation_array[i + 1] == 0) {\n display_val = \"Cannot Divid By Zero!\"\n divid_by_zero = true;\n }\n //Checks for a percentage and inserts 100 to divid with\n if (equation_array[i] == \"%\") {\n equation_array.splice(i + 1, 0, \"100\");\n }\n\n }\n ;\n\n //Checks if an equation ends with an operation, if true duplicates last input\n if (is_operator(equation_array[equation_array.length - 1])) {\n equation_array.push(equation_array[equation_array.length - 2]);\n }\n ;\n\n\n}", "function exercise11() {}", "function findMaxCut(h, w, horizontalCuts, verticalCuts) {\n \n let hor = [];\n hor[0] = 1;\n hor[h] = 1;\n for (let index of horizontalCuts) {\n hor[index] = 1;\n }\n let ver = [];\n ver[0] = 1;\n ver[w] = 1;\n for (let index of verticalCuts) {\n ver[index] = 1;\n }\n \n // console.log(hor, ver)\n let horMax = 0;\n let lastIndex = 0;\n for (let i = 1; i <= h; i++) {\n if (hor[i] == 1) {\n // console.log('test');\n horMax = Math.max(horMax, i - lastIndex);\n lastIndex = i;\n } \n }\n let vermax = 0;\n lastIndex = 0;\n for (let i = 1; i <= w; i++) {\n if (ver[i] == 1) {\n vermax = Math.max(vermax, i - lastIndex);\n lastIndex = i;\n }\n }\n \n return horMax * vermax;\n}", "function cruzamiento(poblacion,seleccion,ciudades,elite)\n\t\t\t{\n\t\t\t\tvar numPobla = poblacion.length;\n\t\t\t\tvar indice1,indice2;\n\t\t\t\tvar k = 0;\n\t\t\t\tvar new_poblation = new Array();\n\t\t\t\t/*Genero nueva poblacion*/\n\t\t\t\twhile(k < parseInt(numPobla / 2))\n\t\t\t\t{\n\t\t\t\t\t//Escogo el metodo de seleccion para tener dos PADRES\n\t\t\t\t\tswitch(seleccion)\n\t\t\t\t\t{\n\t\t\t\t\t\t//Torneo\n\t\t\t\t\t\tcase 0:\n\t\t\t\t\t\t\tdo{\n\t\t\t\t\t\t\t\tindice1 = torneo(poblacion,elite);\n\t\t\t\t\t\t\t\tindice2 = torneo(poblacion,elite);\n\t\t\t\t\t\t\t}while(indice1 == indice2);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t//Ranking\n\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t//Aleatorio\n\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\tdo{\n\t\t\t\t\t\t\t\tindice1 = parseInt( Math.random() * numPobla*elite);\n\t\t\t\t\t\t\t\tindice2 = parseInt( Math.random() * numPobla*elite);\n\t\t\t\t\t\t\t}while(indice1 == indice2);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t//console.log(indice1);\n\t\t\t\t\t//console.log(indice2);\n\t\t\t\t\t/*Padres*/\n\t\t\t\t\tvar dad = poblacion[indice1].recorrido; \n\t\t\t\t\tvar mom = poblacion[indice2].recorrido;\n\t\t\t\t\t/*Camino para Hijos*/\n\t\t\t\t\tvar camino1 = new Array();\n\t\t\t\t\tvar camino2 = new Array();\n\t\t\t\t\t/*Numero entre 0 y numero de ciudades menos 1*/\n\t\t\t\t\tbp = parseInt( Math.random() * ciudades ); /*Punto de roptura*/\n\n\t\t\t\t/*-----------Genero 2 nuevos caminos-----------*/\n\t\t\t\t\t//Respaldo caminos de papa y mama hasta bp\n\t\t\t\t\tfor(var i = 0; i < bp; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tcamino1.push(dad[i]);\n\t\t\t\t\t\tcamino2.push(mom[i]);\n\t\t\t\t\t}\n\t\t\t\t\tfor(var i = 0; i < ciudades; i++)\n\t\t\t\t\t{\t\n\t\t\t\t\t\t//Tomo el elemento a buscar en el segundo vector\n\t\t\t\t\t\tvar busca1 = mom[i];\n\t\t\t\t\t\tvar busca2 = dad[i];\n\t\t\t\t\t\tfor(var j = bp; j < ciudades; j++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(busca1 == dad[j])\n\t\t\t\t\t\t\t\tcamino1.push(busca1);\n\t\t\t\t\t\t\tif(busca2 == mom[j])\n\t\t\t\t\t\t\t\tcamino2.push(busca2); \n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t/*Hijos generados*/\n\t\t\t\t\tvar hijo1 = {recorrido: camino1, distancia: aptitud(camino1,region)}\n\t\t\t\t\tvar hijo2 = {recorrido: camino2,distancia : aptitud(camino2,region)}\n\n\t\t\t\t\tnew_poblation.push(hijo1);\n\t\t\t\t\tnew_poblation.push(hijo2);\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t\treturn new_poblation;\n\t\t\t}", "function cutFruitPieces(fruit) {\n return fruit * 4;\n}", "function Claim()\r\n\t{\r\n\t\t//Show_Solution(Sudoku_Solution);\r\n\t\tfor(var i=0; i<3; i++)\r\n\t\t{\r\n\t\t\tfor(var j=0; j<3; j++)\r\n\t\t\t{\r\n\t\t\t\tif(Claiming(i,j))\r\n\t\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false;\r\n\t}", "function main() {\n var s = readLine();\n var t = readLine();\n var k = parseInt(readLine());\n\n // case 1\n\n if(s.length + t.length <= k){\n console.log(\"Yes\");\n } else{\n // keep iterating until we reach different character\n var commonLength = 0;\n while(commonLength < s.length && commonLength < t.length && s[commonLength] == t[commonLength]){\n commonLength++;\n }\n\n // Diff is the total length of each word minus the common length of each word\n var diff = s.length + t.length - 2*commonLength;\n\n // If the difference is less than k there should be enough moves; however if the diff is odd and the k is even then there are not enough moves\n // you need diff and even and k of even or diff of odd and k of odd. Testing even is easier\n if(diff <= k && diff%2 === k%2){\n console.log(\"Yes\");\n } else {\n console.log(\"No\");\n }\n\n }\n\n}", "function isValidLength(solution) {\n return solution.length === 81;\n}", "function optimal_compos_golden(adr)//mam sklad 7, szukam czy ktos na lawce sie nadaje//szukanie lepszego perfo-nie roz problem\n{\n if(adr==1)\n {\n \ttea = team1;//z tempo odczyt, a do tempz zapisuje;\n }\n else \n {\n \ttea = team2;//z tempo odczyt, a do tempz zapisuje;\n }\n//console.log(changes);\n var all_lawka = [];\n var item1 = [];\n var item2 = [];\n var item3 = [];\n var item4 = [];\n for(var i=1;i<=6;i++)//mam gwaracje, że przejdzie przez każdego R na ławce, ale dalej zawsze wybierze najlepszego\n {\t\n tea[0]=Array(0,0,0,0,0,0,0,0,0,0,0,0);\n item1 = [];item2 = [];item3 = [];item4 = [];\n\t\t\tfor(var j=8;j<=12;j++)\n\t\t\t{\n\t\t\t //item = [];\n if(tea[j][4]==\"R\" && i == 1)// i = 1 - sprawdzam każdego z ławki konkretnie za R\n\t\t\t {\n\t\t\t \tif(tea[j][11] > (tea[i][11]+1))\n {\n nadwyzka = tea[j][11] - tea[i][11];nadwyzka = zaokr(nadwyzka); \n item1 = [j, i, nadwyzka];\n all_lawka.unshift(item1);// \n }\n\t\t\t }\n if(tea[j][4]==\"A\" && i == 4)// i = 4\t\n\t\t\t {\n\t\t\t \tif(tea[j][6] > (tea[i][6]+1))\n {\n nadwyzka = tea[j][6] - tea[i][6];nadwyzka = zaokr(nadwyzka);\n item2 = [j, i, nadwyzka];\n all_lawka.unshift(item2);// \n }\n\t\t\t }\n item3 =[];\n if(tea[j][4]==\"P\" && (i == 2 || i == 5))// i = 2; i =5;\n\t\t\t {\n\t\t\t \tif( (tea[j][6]+tea[j][7])/2 > ((tea[i][6]+tea[i][7])/2)+1)\n {\n nadwyzka = (tea[j][6]+tea[j][7])/2 - ((tea[i][6]+tea[i][7])/2);nadwyzka = zaokr(nadwyzka);\n item3=[];\n item3 = [j, i, nadwyzka];\n test = all_lawka.unshift(item3);//\n //alert(\"test-length: \"+test+\" item: \"+item3);\n }\n\t\t\t }\n if(tea[j][4]==\"S\" && (i == 3 || i == 6))// i = 3; i =6;\n\t\t\t {\n\t\t\t \tif( (tea[j][6]+tea[j][9])/2 > ((tea[i][6]+tea[i][9])/2)+1)\n {\n nadwyzka = (tea[j][6]+tea[j][9])/2 - ((tea[i][6]+tea[i][9])/2);nadwyzka = zaokr(nadwyzka);\n item4 = [j, i, nadwyzka];\n all_lawka.unshift(item4);// \n }\n\t\t\t }\n } //end of for j=8..12\n //console.log(all_lawka);\n }//end of for i=1..6\n //sortowanie\n for(u=0; u<all_lawka.length; u++)\n {\n for(w=1; w<all_lawka.length; w++)\n {\n if(all_lawka[w][2] > all_lawka[w-1][2])\n {\n temp = all_lawka[w-1];\n all_lawka[w-1] = all_lawka[w];\n all_lawka[w] = temp;\n }\n }\n }\n //próba wykoanania zmiany\n for(u=0; u<all_lawka.length; u++)\n {\n out_id = all_lawka[u][1];\n in_id = all_lawka[u][0];\n out_nr = tea[out_id][3]; //na indeksie 1 mam wyznaczonego do zejścia - nr dla funkcji possible_change\n in_nr = tea[in_id][3]; //\n if(adr == 1)\n {\n if(possible_change(adr, out_nr, in_nr) < 6)\n {\nvar fffv = document.getElementById(\"screen3\").innerHTML;\ndocument.getElementById(\"screen3\").innerHTML=fffv+\"<br>(\"+pkt1+\":\"+pkt2+\") \"+tea[in_id][5]+\" za: \"+tea[out_id][5]+\" (stan: \"+mm1+\" : \"+mm2+\") \";\n//2021-01-13: nowy screen do zapisu zmian na czas seta\nvar fffv = document.getElementById(\"change_info1\").innerHTML;\ndocument.getElementById(\"change_info1\").innerHTML=fffv+\"<br>(\"+pkt1+\":\"+pkt2+\") \"+tea[in_id][5]+\" za \"+tea[out_id][5];\n change1(out_id,in_id); flag_golden1 = 1; return 0;\n }\n }\n else\n {\n if(possible_change(adr, out_nr, in_nr) < 6)\n {\nvar fffv = document.getElementById(\"screen6\").innerHTML;\ndocument.getElementById(\"screen6\").innerHTML=fffv+\"<br>(\"+pkt1+\":\"+pkt2+\") \"+tea[in_id][5]+\" za: \"+tea[out_id][5]+\" (stan: \"+mm1+\" : \"+mm2+\") \";\n//2021-01-13: nowy screen do zapisu zmian na czas seta\nvar fffv = document.getElementById(\"change_info2\").innerHTML;\ndocument.getElementById(\"change_info2\").innerHTML=fffv+\"<br>(\"+pkt1+\":\"+pkt2+\") \"+tea[in_id][5]+\" za \"+tea[out_id][5];\n change2(out_id,in_id); flag_golden2 = 1; return 0;\n }\n }\n }\n\n\n if(adr==1)\n {\n team1 = tea;\n }\n else \n {\n team2 = tea;\n }\n\n banch_ins();\n return 1;\n}", "function getBestAndWorstCase1(cp) {\n //console.log(board_config);\n //debugger;\n if (cp == 1){\n var probabilites = [];\n for (var i = 1;i <= 9;i++){\n if (board_config[i] == ''){\n board_config[i] = player_choices[1];\n if (checkGameOver(i, cp)){\n board_config[i] = '';\n return [{'id' : i, 'chance' : 0},{'id' : i, 'chance' : 0}];\n } else if (gameTie()){\n probabilites.push([{'id' : i, 'chance' : 0.5},{'id' : i, 'chance' : 0.5}]);\n } else {\n probabilites.push(getBestAndWorstCase(2));\n }\n board_config[i] = '';\n }\n }\n //console.log('player 1', probabilites);\n if (probabilites.length == 1){\n return [probabilites[0][1], probabilites[0][1]];\n }\n probabilites.sort(function (p1, p2) {\n if (p1[1].chance < p2[1].chance){\n return -1;\n } else if(p1[1].chance == p2[1].chance){\n if (p1[0].chance < p2[0].chance){\n return -1;\n } else{\n return 1;\n }\n } else {\n return 1;\n }\n });\n return [probabilites[1][1], probabilites[0][1]];\n } else {\n var probabilites = [];\n for (var i = 1;i <= 9;i++){\n if (board_config[i] == ''){\n board_config[i] = player_choices[2];\n if (checkGameOver(i, cp)){\n board_config[i] = '';\n return [{'id': i, 'chance' : 1},{'id': i, 'chance' : 1}];\n } else if (gameTie()){\n probabilites.push([{'id' : i, 'chance' : 0.5},{'id' : i, 'chance' : 0.5}]);\n } else {\n probabilites.push(getBestAndWorstCase(1));\n probabilites[probabilites.length - 1][0].id = i;\n probabilites[probabilites.length - 1][1].id = i;\n }\n board_config[i] = '';\n }\n }\n //console.log('player 2', probabilites);\n if (probabilites.length == 1){\n return [probabilites[0][1], probabilites[0][1]];\n }\n probabilites.sort(function(p1, p2){\n //console.log(p1, p2);\n\n if (p1[1].chance > p2[1].chance){\n return -1;\n } else if(p1[1].chance == p2[1].chance){\n if (p1[0].chance > p2[0].chance){\n return -1;\n } else {\n return 1;\n }\n } else {\n return 1;\n }\n });\n\n return [probabilites[1][1], probabilites[0][1]];\n }\n}", "function unconstrained(board) {\n var bits = figurebits(board);\n var results = [];\n for (var freedom = 0; freedom < 10; freedom++) {\n results.push([]);\n }\n for (var pos = 0; pos < 81; pos++) {\n if (board[pos] === null) {\n results[listbits(bits.allowed[pos]).length].push(pos);\n }\n }\n var result = [];\n for (freedom = results.length - 1; freedom >= 0; --freedom) {\n shuffle(results[freedom]);\n result.push.apply(result, results[freedom]);\n }\n return result;\n}", "function victoriadiag(casella,x,y) {\n var pj = casella.jugador;\n var int = 0;\n while (x >= 0 && y >= 0) {\n x--; y--;\n }\n while (true) {\n x++; y++;\n if (x < 7 && y < 6) {\n casella = array[y][x];\n if (casella.jugador == pj) {\n int++;\n } else {\n int = 0;\n }\n } else {\n break;\n }\n }\n if (int >= 4) {\n win = pj;\n }\n}", "function check_block() {\n var moved = false;\n reset_counts();\n check_counts(\"X\");\n\n if (countdiag1 == 2 && !moved) {\n for (i = 0; i < 3; i++) {\n moved = take_space(i * 3 + i);\n }\n }\n if (countdiag2 == 2 && !moved) {\n for (i = 0; i < 3; i++) {\n moved = take_space(i * 2 + 2);\n }\n }\n if (countrow0 == 2) {\n for (i = 0; i < 3; i++) {\n moved = take_space(i);\n }\n }\n if (countrow1 == 2 && !moved) {\n for (i = 0; i < 3; i++) {\n moved = take_space(3 + i);\n }\n }\n if (countrow2 == 2 && !moved) {\n for (i = 0; i < 3; i++) {\n moved = take_space(6 + i);\n }\n }\n if (countcol0 == 2 && !moved) {\n for (i = 0; i < 3; i++) {\n moved = take_space(i * 3);\n }\n }\n if (countcol1 == 2 && !moved) {\n for (i = 0; i < 3; i++) {\n moved = take_space(i * 3 + 1);\n }\n }\n if (countcol2 == 2 && !moved) {\n for (i = 0; i < 3; i++) {\n moved = take_space(i * 3 + 2);\n }\n }\n return moved;\n}", "function baillie_psw(candidate){\n \n var known_primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47];\n //console.log(\"Testing candidate ... \"+candidate);\n for(var i=0;i<known_primes.length;i++){\n var known_prime = new BigInteger(known_primes[i]);\n if(candidate.compare(known_prime)==0){\n return true;\n } else if(candidate.remainder(known_prime).compare(BigInteger.ZERO) ==0){\n return false;\n }\n }\n // console.log(\"Testing Miller Rabin candidate ... \"+candidate);\n if(!miller_rabin_base_2(candidate)){\n // console.log(\"Testing Miller Rabin candidate ... \"+candidate+\"iscomposite\");\n return false;\n }\n // console.log(\"Testing lucas pp candidate ... \"+candidate);\n // console.log(\"D_chooser begin candidate \"+candidate.toString());\n//lucas strong pseudoprimes\n/*5459, 5777, 10877, 16109, 18971, 22499, 24569, 25199, 40309, 58519, 75077, 97439, 100127, 113573, 115639, 130139, 155819, 158399, 161027, 162133, 176399, 176471*/\n\n if(perfect_sq(candidate)){\n\t return false;\n\t}\n var D = D_chooser(candidate);\n if(D.isZero()){\n return false;\n }\n //console.log(\"D_chooser =\"+D.toString());\n var Q = BigInteger.ONE.subtract(D).divide(BigInteger.small[4]);\n var P = BigInteger.ONE;\n if(Q.compare(BigInteger.ONE)==0){\n Q = P.add(Q).next();\n\t P = P.next().next();\n } else if(Q.compare(new BigInteger(-1))==0){\n P = Q = BigInteger.small[5];\n }\n if(!lucas_pp(candidate,D,P,Q)){\n\t //console.log(\"Lucas returing false\");\n return false;\n }\n // console.log(\"baillie_psw returing true\");\n return true;\n}", "function check_win() {\n var moved = false;\n check_counts(\"O\"); //gets the counts of O's to see if can win\n\n if (countdiag1 == 2 && !moved) {\n for (i = 0; i < 3; i++) {\n moved = take_space(i * 3 + i);\n }\n }\n if (countdiag2 == 2 && !moved) {\n for (i = 0; i < 3; i++) {\n moved = take_space(i * 2 + 2);\n }\n }\n\n if (countcol0 == 2) {\n for (i = 0; i < 3; i++) {\n moved = take_space(i * 3);\n }\n }\n if (countcol1 == 2 && !moved) {\n for (i = 0; i < 3; i++) {\n moved = take_space(i * 3 + 1);\n }\n }\n if (countcol2 == 2 && !moved) {\n for (i = 0; i < 3; i++) {\n moved = take_space(i * 3 + 2);\n }\n }\n if (countrow0 == 2 && !moved) {\n for (i = 0; i < 3; i++) {\n moved = take_space(i);\n }\n }\n if (countrow1 == 2 && !moved) {\n for (i = 0; i < 3; i++) {\n moved = take_space(3 + i);\n }\n }\n if (countrow2 == 2 && !moved) {\n for (i = 0; i < 3; i++) {\n moved = take_space(6 + i);\n }\n }\n return moved;\n}", "function solution(w,h){\n return w*h -(w+h -gcd(w,h));\n}", "function canShow(plusMinus, slideNum){\n \n /**\n * Could be cleaned up with using an array for the counter instead\n * of 3 individual variabels but this is how my brain solved the problem first\n */\n switch(slideNum){\n case 1:\n //decrement or increment counter\n counter1 += plusMinus\n\n if(counter1 == 6){\n //if at end send it back to start\n counter1 = 0\n }\n else if(counter1 == -1){\n //if at beginning send it back to end\n counter1 = 5\n }\n //set the source of the image\n $(\"#img1\").attr(\"src\", \"../pix/\" + candidatePix[counter1])\n break\n\n case 2:\n\n counter2 += plusMinus\n if(counter2 == 14){\n counter2 = 6\n }\n else if(counter2 == 5){\n \n counter2 = 13\n }\n //set the source of the image\n $(\"#img2\").attr(\"src\", \"../pix/\" + candidatePix[counter2])\n break\n\n case 3:\n\n counter3 += plusMinus\n if(counter3 == 21){\n counter3 = 14\n }\n else if(counter3 == 13){\n \n counter3 = 20\n }\n //set the source of the image\n $(\"#img3\").attr(\"src\", \"../pix/\" + candidatePix[counter3])\n break\n\n }\n \n}", "function minimumBribes(q) {\n // Write your code here\n let bribes = 0;\nlet chaotic = false\n for(let i =0; i<q.length; i++){\n if(q[i]-(i+1) > 2){\n chaotic = true\n }\n for(let j = q[i]-2; j<i; j++){\n if(q[j]>q[i]){\n bribes++\n }\n } \n }\n if(chaotic === true){console.log(\"Too chaotic\")\n }\n else{ console.log(bribes)\n}}", "function checkHugo(){\n \n\tif ($(\"#cover-0\").is(\":checked\") && $(\"#sim-0\").is(\":checked\") && $(\"#pass-0\").is(\":checked\") && $(\"#cancel-0\").is(\":checked\")){\n\t\t\n\t\thideHugoFunc(\".hugo-1111\");\t// all - 1111\n\n\t//Three Active\t\n\n\t} else if ($(\"#cover-0\").is(\":checked\") && $(\"#sim-0\").is(\":checked\") && $(\"#pass-0\").is(\":checked\")) {\n\t\t\n\t\thideHugoFunc(\".hugo-1110\");\t// 1110\n\n\t} else if ($(\"#cover-0\").is(\":checked\") && $(\"#sim-0\").is(\":checked\") && $(\"#cancel-0\").is(\":checked\")) {\n\t\t\n\t\thideHugoFunc(\".hugo-1101\");\t// 1101\n\n\t} else if ($(\"#cover-0\").is(\":checked\") && $(\"#pass-0\").is(\":checked\") && $(\"#cancel-0\").is(\":checked\")) {\n\t\t\n\t\thideHugoFunc(\".hugo-1011\");\t// 1011\n\n\t} else if ($(\"#sim-0\").is(\":checked\") && $(\"#pass-0\").is(\":checked\") && $(\"#cancel-0\").is(\":checked\")) {\n\t\t\n\t\thideHugoFunc(\".hugo-0111\");\t// 0111\t\n\n\t//Two Active\t\n\n\t} else if ($(\"#cover-0\").is(\":checked\") && $(\"#sim-0\").is(\":checked\")) {\n\t\t\n\t\thideHugoFunc(\".hugo-1100\");\t// 1100\t\n\n\t} else if ($(\"#cover-0\").is(\":checked\") && $(\"#pass-0\").is(\":checked\")) {\n\t\t\n\t\thideHugoFunc(\".hugo-1010\");\t// 1010\t\t\n\n\t} else if ($(\"#cover-0\").is(\":checked\") && $(\"#cancel-0\").is(\":checked\")) {\n\t\t\n\t\thideHugoFunc(\".hugo-1001\");\t// 1001\n\n\t} else if ($(\"#sim-0\").is(\":checked\") && $(\"#cancel-0\").is(\":checked\")) {\n\t\t\n\t\thideHugoFunc(\".hugo-0101\");\t// 0101\n\n\t} else if ($(\"#sim-0\").is(\":checked\") && $(\"#pass-0\").is(\":checked\")) {\n\t\t\n\t\thideHugoFunc(\".hugo-0110\");\t// 0110\n\n\t} else if ($(\"#pass-0\").is(\":checked\") && $(\"#cancel-0\").is(\":checked\")) {\n\t\t\n\t\thideHugoFunc(\".hugo-0011\");\t// 0011\t\t\n\n\t//One Active\n\n\t} else if ($(\"#cover-0\").is(\":checked\")) {\n\t\t\n\t\thideHugoFunc(\".hugo-1000\");\t// 1000\t\n\n\t} else if ($(\"#sim-0\").is(\":checked\")) {\n\t\t\n\t\thideHugoFunc(\".hugo-0100\");\t// 0100\n\n\t} else if ($(\"#pass-0\").is(\":checked\")) {\n\t\t\n\t\thideHugoFunc(\".hugo-0010\");\t// 0010\t\t\n\n\t} else if ($(\"#cancel-0\").is(\":checked\")) {\n\t\t\n\t\thideHugoFunc(\".hugo-0001\");\t// 0001\n\n\t//None\t\n\n\t} else {\n\n\t\thideHugoFunc(\".hugo-0000\");\t// default - 0000\n\n\t}\n\t\n\tif ($(\"#cover-0\").is(\":checked\")) {\n\t\t$(\"#addon-1\").addClass(\"showAddOn\");\n\t} else {\n\t\t$(\"#addon-1\").removeClass(\"showAddOn\");\n\t}\n\t\n\tif ($(\"#sim-0\").is(\":checked\")) {\n\t\t$(\"#addon-2\").addClass(\"showAddOn\");\n\t} else {\n\t\t$(\"#addon-2\").removeClass(\"showAddOn\");\n\t}\t\n\t\n\tif ($(\"#pass-0\").is(\":checked\")) {\n\t\t$(\"#addon-3\").addClass(\"showAddOn\");\n\t} else {\n\t\t$(\"#addon-3\").removeClass(\"showAddOn\");\n\t}\t\n\n\tif ($(\"#cancel-0\").is(\":checked\")) {\n\t\t$(\"#addon-4\").addClass(\"showAddOn\");\n\t} else {\n\t\t$(\"#addon-4\").removeClass(\"showAddOn\");\n\t}\n}", "function letsDivide() {\n if (solution1 == 0) {\n solution1 = Number(numberBucket);\n numberBucket = \"\";\n } else {\n operate();\n second2 = \"\";\n }\n chosenOperator = \"dividor\";\n setColor();\n}", "function luckBalance(k, contests) {\n\n let luck = 0\n\n let mustWinContests = []\n for (let i = 0; i < contests.length; i++) {\n if (contests[i][1] === 1) {\n mustWinContests.push(contests[i])\n }\n }\n mustWinContests = mustWinContests.sort(function(a, b){return a[0]-b[0]}).splice(0, mustWinContests.length - k)\n\n // for (let i = 0; i < contests.length; i++) {\n // if (mustWinContests.includes(contests[i]) === true){\n // luck--\n // } else {\n // luck++\n // }\n // }\n\n for (let i = 0; i < contests.length; i++) {\n luck += contests[i][0]\n }\n\n for (let i = 0; i < mustWinContests.length; i ++) {\n luck = luck - (2 * mustWinContests[i][0])\n }\n\n return luck\n}", "function solutionChecker(solution) {\n\t// check rows\n\tfor(let i = 0; i <= 8; i++) {\n\t\tif(!checkRow(solution[i])) return false;\n\t}\n\t// check collums\n\tlet auxRow;\n\tfor(let i = 0; i <= 8; i++) {\n\t\tauxRow = [];\n\t\tfor(let j = 0; j <= 8; j++) {\n\t\t\tauxRow.push(solution[j][i]);\t\t// \t the numbers of the collumn are put in an array,\n\t\t}\t\t\t\t\t\t\t\t\t\t// so its easier to analyse\n\t\tif(!checkRow(auxRow)) return false;\t\t\n\t}\n\t// check big squares\n\tfor(let i = 0; i <= 2; i++) {\n\t\tfor(let j = 0; j <= 2; j++) {\n\t\t\tauxRow = solution[i*3].slice(j*3, j*3+3) // the same is done to the numbers of a big square\n\t\t\t\t.concat(\n\t\t\t\t\tsolution[i*3+1].slice(j*3, j*3+3)\n\t\t\t\t).concat(\n\t\t\t\t\tsolution[i*3+2].slice(j*3, j*3+3)\t\t\t\n\t\t\t\t);\n\t\t\tif(!checkRow(auxRow)) return false;\t\t\n\t\t}\n\t}\n\treturn true;\n\tfunction checkRow(row) {\n\t\treturn numbers.every(number => {\n\t\t\treturn row.some(num => num == number);\n\t\t});\n\t}\n}", "function confirmSlice(y1, x1, y2, x2) {\n\tsliceArray.push([y1, x1, y2, x2]);\n\t\n\t// set the values in the isInSlice array\n\tfor (let y = y1; y <= y2; y++) {\n\t\tfor (let x = x1; x <= x2; x++) {\n\t\t\tif (isInSlice[y][x] === false) {\n\t\t\t\t// everything has gone as planned\n\t\t\t\tisInSlice[y][x] = true;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconsole.error(\"Uh oh, an invalid slice has been confirmed.\");\n\t\t\t}\n\t\t}\n\t}\n}", "function luckBalance(k, contests) {\n let importantes =[];\n let noimportantes=[];\n let aux= [];\n console.log(contests)\n contests.forEach((e1,index1)=>{\n e1.forEach((e2,index,arr)=>{\n if(index==1){\n if(e2==1){\n importantes.push(arr[index-1]);\n aux.push(arr[index-1]);\n }\n }\n if(index==1){\n if(e2==0){\n noimportantes.push(arr[index-1]);\n }\n }\n \n \n \n });\n });\n importantes.sort(function(a, b){return a-b});\n aux.sort(function(a, b){return a-b});\n console.log(\"primero: importantes: \"+importantes +\" no importantes: \"+noimportantes+\" por restar: \"+aux);\n \n let lose= importantes.length-k;\n aux.splice(lose,aux.length-1);\n //aux.splice(lose, aux.length-1);\n importantes.splice(0,lose);\n let sumai= 0;\n let sumani=0;\n let sumau=0;\n importantes.forEach(e=> sumai+=e);\n noimportantes.forEach(e=> sumani+=e);\n aux.forEach(e=>sumau+=e);\n let lucky = sumai+sumani-sumau;\nconsole.log(\"importantes: \"+importantes +\" no importantes: \"+noimportantes+\" perdida: \"+lose+ \"por restar: \"+aux);\nreturn lucky;\n}", "function getTriangleTypeNumber(s1, s2, s3) {\n if (isNaN(s1) || isNaN(s2) || isNaN(s3)) {\n codeCoverage[12] = true;\n return 0; \n } else if (s1 < 0 || s2 < 0 || s3 < 0) {\n codeCoverage[0] = true;\n return 0;\n } else if (s1 == 0) {\n codeCoverage[1] = true;\n return 0; \n } else if (s2 == 0) {\n codeCoverage[2] = true;\n return 0;\n } else if (s3 == 0) {\n codeCoverage[3] = true;\n return 0;\n } else if (s1 - s2 == s3) {\n codeCoverage[4] = true;\n return 0;\n } else if (s2 - s1 == s3) {\n codeCoverage[5] = true;\n return 0;\n } else if (s3 - s2 == s1) {\n codeCoverage[6] = true;\n return 0;\n } else if (s1 - s2 > s3) {\n codeCoverage[7] = true;\n return 0;\n } else if (s2 - s1 > s3) {\n codeCoverage[8] = true;\n return 0;\n } else if (s3 - s2 > s1) {\n codeCoverage[9] = true;\n return 0;\n } else if (s1 == s2 && s1 == s3 && s2 == s3) {\n codeCoverage[10] = true;\n return 1;\n } else if (s1 != s2 && s1 != s3 && s2 != s3) {\n codeCoverage[11] = true;\n return 3; \n } else {\n codeCoverage[13] = true;\n return 2;\n }\n}", "function vctrChck()\r\r\t{\r \r\t\t// A variable redefined as \"result\" (out of the loop) is carried in a final sequence of mini-loops that check to tabulate a final \"result\". This particular variable states the \"result\" is \"BOTH FIGHTERS' REACH AN UNFORTUNATE DRAW\" because \"10\" duel rounds have passed and neither player has claimed victory, nor sealed their bloody fate with death.\r\t\tvar result=\"BOTH FIGHTERS' REACH AN UNFORTUNATE DRAW\";\r\t\t\r\t\t// The \"if\" statement passes the parameter of variable \"plyr1Hlth\" which is a \"conditional\" that checks to verify if it is \"less than\" the sum of \"1\". Then, the \"&&\" operator pairs the parameter of variable \"plyr2Hlth\" which checks to verify if it also is \"less than\" the sum of \"1\". \r if (rivals[0].health < 1 && rivals[1].health < 1)\r\t\t\r {\r\t\t\t\r // If the above sum of both players is infact \"0\", then \"result\" variable is equal to \"BOTH FIGHTERS' SEAL THEIR FATE AS A BLOODY DEATH\".\r\t\t\tresult = \"BOTH FIGHTERS' SEAL THEIR FATE AS A BLOODY DEATH\";\r\t\t\t\r } \r\t\t\r\t\t// The \"else if\" statement is yet another \"conditional\" statement that the parameter of variable \"plyr1Hlth\" which checks to verify if it is \"less than\" the sum of \"1\".\r\t\telse if (rivals[0].health < 1 )\r\t\t\r\t\t{\r\t\t\t\r\t\t\t// If the above sum of both players is infact \"0\", then \"result\" variable is equal to \"plyr2Name\" to which \"adds\" the string \" IS VICTORIOUS!!!\".\r result = (rivals[1].name) + \" IS VICTORIOUS!!!\";\r } \r\t\t\r\t\t// The \"else if\" statement is yet another \"conditional\" statement that the parameter of variable \"plyr2Hlth\" which checks to verify if it is \"less than\" the sum of \"1\".\r\t\telse if (rivals[1].health < 1 )\r\t\t\r {\r\t\t\t// If the above sum of both players is infact \"0\", then \"result\" variable is equal to \"plyr1Name\" to which \"adds\" the string \" IS VICTORIOUS!!!\".\r result = (rivals[0].name) + \" IS VICTORIOUS!!!\";\r\t\t\t\r }\r\t\t\r\t\t// If any of the above statements in the \"vctrChck\" function is \"true\" then \"return\" (stops the execution of a function and returns a value from that function) that \"result\" variable with the correct above statement.\r return result;\r }\r\r/******* The OLD program was executed below *******/\r\r // The \"duel\" function executes to start the javascript program.\r\t// duel();", "function Puzzle() {\n let rectcount = 0;\n this.stack = [];\n this.first = function(width, height) {\n var rectangle, row, column, mask;\n rectangle = [];\n for (row = 0; row < height; row++) {\n rectangle[row] = [];\n for (column = 0; column < width; column++) {\n rectangle[row][column] = false;\n }\n }\n\n // Exclude by 3x3 in the middle of the board\n if (rectcount === 0){\n rectangle[6][6] = true;\n rectangle[6][7] = true;\n rectangle[6][8] = true;\n rectangle[7][6] = true;\n rectangle[7][7] = true;\n rectangle[7][8] = true;\n rectangle[8][6] = true;\n rectangle[8][7] = true;\n rectangle[8][8] = true;\n rectcount = 1;\n }\n // Vars to check wheter or not each shape is used\n mask = [\n false, false, false, false, false, false, false,\n false, false, false, false, false, false, false,\n false, false, false, false, false, false, false,\n false, false, false, false, false, false, false,\n false, false, false, false, false, false, false, false\n ];\n return new State(rectangle, mask, 0);\n };\n\n // Run the puzzle solver, set object, stop program when the solution is found\n this.run = function(width, height) {\n var hexominos, state, count;\n hexominos = new Hexominos();\n hexominos.initialize(width, height);\n state = this.first(width, height);\n state.add(hexominos.rectangle);\n this.stack.push(state);\n \n // 33 figures cells = 198\n count = 198;\n \n // If the shape fits, then push the state to the stack\n while (this.stack.length > 0) {\n state = this.stack.pop();\n if (state.count == count) {\n break;\n }\n while (state.next()) {\n if (state.fit()) {\n this.stack.push(state);\n state = state.copy();\n state.add(hexominos.rectangle);\n this.stack.push(state);\n break;\n }\n }\n }\n };\n}", "function cut() {}", "function solution(n) {\n d = new Array(30);\n l = 0;\n while (n > 0) {\n d[l] = n % 2;\n n = Math.floor(n / 2);\n l += 1;\n }\n console.log('l = ', l);\n console.log('d = ', d);\n for (p = 1; p < 1 + l; ++p) {\n ok = true;\n for (i = 0; i < l - p; ++i) {\n if (d[i] != d[i + p]) {\n ok = false;\n break;\n }\n }\n if (ok) {\n return p;\n }\n }\n return -1;\n}" ]
[ "0.62119865", "0.5658088", "0.56347024", "0.5539704", "0.5496342", "0.5487966", "0.54491174", "0.54458094", "0.5435846", "0.543056", "0.5404392", "0.5380468", "0.5343816", "0.5332424", "0.5328485", "0.5324252", "0.53133583", "0.5275224", "0.5255005", "0.5250793", "0.5250793", "0.52393335", "0.52215195", "0.5217306", "0.52031046", "0.51829827", "0.5181906", "0.51592803", "0.515769", "0.5129648", "0.5120457", "0.5112855", "0.5096446", "0.50835836", "0.5070479", "0.5069646", "0.506865", "0.5065191", "0.50488", "0.5029556", "0.5017643", "0.5013332", "0.50127447", "0.50058305", "0.49903497", "0.4979324", "0.4967082", "0.49659675", "0.49564284", "0.49549943", "0.4954269", "0.49518174", "0.49513867", "0.49390522", "0.49284244", "0.49272785", "0.4927059", "0.49211013", "0.49111044", "0.49107707", "0.490989", "0.4909377", "0.4899867", "0.4898973", "0.48944566", "0.4893962", "0.48919165", "0.48862532", "0.48821285", "0.48796314", "0.48753062", "0.48686203", "0.48579738", "0.485763", "0.4856901", "0.48565477", "0.48529872", "0.48502567", "0.48476067", "0.48457047", "0.48387754", "0.48369333", "0.48323816", "0.4826679", "0.4823115", "0.48227483", "0.48156404", "0.48153508", "0.48142502", "0.48112202", "0.48086303", "0.480459", "0.48000255", "0.4797983", "0.4797049", "0.4791003", "0.47854707", "0.47827792", "0.47807768", "0.47803968", "0.47779617" ]
0.0
-1
given two strings, determine if the first string ends with the second string
function solution(str, ending){ return str.endsWith(ending) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function endOther(string1, string2){\n string1 = string1.toLowerCase();\n string2 = string2.toLowerCase();\n if(string1.endsWith(string2) || string2.endsWith(string1)){\n return true;\n }else{\n return false;\n }\n}", "function endsWith(a, b) {\n if (a.length < b.length) { return false; }\n return a.substring(a.length - b.length) == b;\n }", "function sc_isStringSuffix(cs1, cs2) {\n var tmp = cs2.lastIndexOf(cs1);\n return tmp !== false && tmp >= 0 && tmp === cs2.length - cs1.length;\n}", "function solution(str, ending){\nif(str.endsWith(ending)) return true\nreturn false\n}", "function endsWith(x, y, bool){\n x = x.toString();\n return bool ? x.toUpperCase().endsWith(y.toUpperCase()) : x.endsWith(y);\n }", "function lastCharacter(string1, string2) {\n\tlet result;\n\tif (typeof string1 === 'string' && typeof string2 === 'string') {\n\t\tif (string1[string1.length -1] === string2[string2.length-1])\n\t\t\tresult = true;\n\t\telse result = false;\n\t}\n\treturn result;\n}", "function solution(str, ending) {\n return str.endsWith(ending);\n}", "function solution(str, ending){\n // TODO: complete\n return str.endsWith(ending)\n}", "function solution(str, ending){\n return str.endsWith(ending);\n}", "function solution(str, ending){\n return str.endsWith(ending);\n}", "function endsWith(str, suffix) {\n\t str = toString(str);\n\t suffix = toString(suffix);\n\n\t return str.indexOf(suffix, str.length - suffix.length) !== -1;\n\t }", "function xStrEndsWith( s, end )\r\n{\r\n if( !xStr(s,end) ) return false;\r\n var l = s.length;\r\n var r = l - end.length;\r\n if( r > 0 ) return s.substring( r, l ) == end;\r\n return s == end;\r\n}", "function solution(str, ending){\n return str.endsWith(ending);\n }", "function endsWith(str, suffix) {\r\n\tvar test = str.indexOf(suffix);\r\n return str.indexOf(suffix) !== -1;\r\n}", "function strEndsWith(str, suffix) {\n var lastIndex = str.lastIndexOf(suffix);\n return (lastIndex != -1) && (lastIndex + suffix.length == str.length);\n}", "function endsWith(str, suffix) {\n return str.indexOf(suffix, str.length - suffix.length) !== -1;\n}", "function endsWith(str, suffix) {\n return str.indexOf(suffix, str.length - suffix.length) !== -1;\n}", "function endsWith(str, suffix) {\n return str.indexOf(suffix, str.length - suffix.length) !== -1;\n}", "function endsWith(str, suffix) {\n return str.indexOf(suffix, str.length - suffix.length) !== -1;\n}", "function endsWith(str, suffix) {\n return str.indexOf(suffix, str.length - suffix.length) !== -1;\n}", "function endsWith(str, suffix) {\n return str.indexOf(suffix, str.length - suffix.length) !== -1;\n}", "function endsWith(str, suffix) {\n return str.indexOf(suffix, str.length - suffix.length) !== -1;\n}", "function endsWith(str, suffix) {\n if (str === null || suffix === null)\n return false;\n return str.indexOf(suffix, str.length - suffix.length) !== -1;\n }", "function solution(str, ending){\r\n const endingLength = ending.length\r\n return (str.substring(str.length - endingLength)) === ending\r\n}", "function isSuffixOf(xs, ys){\r\n return isPrefixOf(reverse(xs), reverse(ys));\r\n}", "function solution(str, ending) {\n if(!ending.length) return true;\n return str.slice(-(ending.length)) === ending;\n}", "function stringRotation (string1, string2) {\n if (string1.length !== string2.length) {\n return false;\n }\n return (string2 + string2).includes(string1);\n}", "function endsWith(haystack, needle) {\n var diff = haystack.length - needle.length;\n if (diff > 0) {\n return haystack.lastIndexOf(needle) === diff;\n }\n else if (diff === 0) {\n return haystack === needle;\n }\n else {\n return false;\n }\n}", "function isSubsequence(str1, str2) {\n // if str1 > str2, return false\n if (!str1) return true;\n if (str1.length > str2.length) return false;\n // have two pointers (track of index)\n let firstPointer = 0;\n // iterate over second string\n for (let secondPointer = 0; secondPointer < str2.length; secondPointer++) {\n // if char matches first string\n if (str2[secondPointer] === str1[firstPointer]) firstPointer++;\n // iterate over first string\n // otherwise continue to iterate the second string\n if (firstPointer === str1.length) return true;\n }\n // if we finish iterating through the entire str1, return true, otherwise false\n return false;\n}", "function solution(str, ending){\n return ending === str.substring(str.length - ending.length)\n}", "function endsin (str, suffix) {\n if (str.length < suffix.length) return false\n return (str.slice(-suffix.length) === suffix)\n}", "isEndingWith(value, sub) {\n return this.isString(value) && value.endsWith(sub);\n }", "function endsWith(haystack, needle) {\n const diff = haystack.length - needle.length;\n if (diff > 0) {\n return haystack.lastIndexOf(needle) === diff;\n }\n else if (diff === 0) {\n return haystack === needle;\n }\n else {\n return false;\n }\n}", "function endsWith(haystack, needle) {\n var diff = haystack.length - needle.length;\n if (diff > 0) {\n return haystack.indexOf(needle, diff) === diff;\n }\n else if (diff === 0) {\n return haystack === needle;\n }\n else {\n return false;\n }\n}", "function endsWith(ch)\n{\n return this.lastIndexOf(ch) == this.length - ch.length;\n}", "function confirmEnding(str, target) {\n\treturn str.lastIndexOf(target) === str.length - target.length;\n}", "function confirmEnding(str, target) {\n var start = str.length - (target.length);\n //Var for just comparing length of string\n if(str.substr(start, str.length) == target) {\n //Compares end of string with the target string\n return true;\n } else {\n return false;\n }\n \n}", "function stringEndsWith(str, suffix) {\n return str.indexOf(suffix, str.length - suffix.length) !== -1;\n}", "function stringEndsWith(str, suffix) {\n return str.indexOf(suffix, str.length - suffix.length) !== -1;\n}", "function confirmEnding(str, target) {\n //1. of corse .endsWith() method\n //str = str.endsWith(target);\n //return str\n\n //2. .slice() method\n //return str.slice(str.length - target.length) === target;\n\n //3. usual for loop\n let flag = false;\n //start comparing only if target is shorter, else - false\n //compare from the last char till the first of the target\n for ( let i = target.length-1, j = str.length-1; target.length < str.length && i >= 0; i--, j--){\n if (target[i] == str[j]) { \n flag = true;\n } else {\n flag = false\n break\n }\n }\n\n\n return flag;\n }", "function ends_with(thestring, pattern) {\n var d = thestring.length - pattern.length;\n return d >= 0 && thestring.lastIndexOf(pattern) === d;\n}", "function endsWith(stringA, extension) {\n\t\t\treturn -1 !== stringA.indexOf(extension, stringA.length - extension.length);\n\t\t}", "function isSubsequece(string1, string2) {\n if(string1.length > string2.length) {\n return false;\n }\n\n let j = 0;\n let i = 0;\n while(j < string2.length) {\n if(string1[i] === string2[j]) {\n j++;\n i++;\n }\n if(string1[i] !== string2[j]) {\n j++;\n }\n if(i === string1.length) {\n return true;\n }\n }\n return false;\n}", "function doesStringEndWith(s, suffix) {\n return s.substr(s.length - suffix.length) === suffix;\n}", "function doesStringEndWith(s, suffix) {\r\n return s.substr(s.length - suffix.length) === suffix;\r\n}", "function doesStringEndWith(s, suffix) {\r\n return s.substr(s.length - suffix.length) === suffix;\r\n}", "function twoStrings(s1, s2) {\r\n \r\n var brk;\r\n \r\n var i=0,z;\r\n while(i<s1.length){\r\n if(z>=0){\r\n break;\r\n }\r\n z=s2.indexOf(s1[i]);\r\n i++;\r\n \r\n }\r\n if(z>=0){\r\n return \"YES\";\r\n }else{\r\n return \"NO\";\r\n }\r\n \r\n }", "function oneAway(string1, string2) {\r\n if (string1 === string2) return true;\r\n for (let i = 0; i < string1.length; i++) {\r\n const check1 = string1.slice(0, i) + string1.slice(i + 1);\r\n const check2 = string2.slice(0, i) + string2.slice(i + 1);\r\n if (check1 === string2 || check2 === string1 || check1 === check2) return true;\r\n }\r\n return false;\r\n}", "function endsWith(input, value) {}", "function strEndsWith(input, match) {\n return input.slice(-1 * match.length) === match;\n }", "function strEndsWith(input, match) {\n return input.slice(-1 * match.length) === match;\n }", "function twoStrings(s1, s2) {\n for (let index = 0; index < s2.length; index++) {\n const letter = s2[index];\n if (s1.includes(letter)) {\n return 'YES';\n }\n }\n return 'NO';\n}", "function isRotation(str1, str2) {\n\n\tif (str1.length !== str2.length) return false;\n\n\tlet double = str1 + str1;\n\n\treturn double.includes(str2)\n\n}", "function isSubsequence(str1, str2) {\n // if str1 and str2 lengths are 0\n if (str1.length === 0 && str2.length === 0) {\n // return true\n return true\n }\n // create a tracker to save str1 index\n let tracker = 0;\n // iterate over str2\n for (let char of str2) {\n // if char at str2 is str1 at tracker\n if (char === str1[tracker]) {\n // increment tracker\n tracker++;\n }\n // if the tracker is the same as str1 length\n if (str1.length === tracker) {\n // return true\n return true;\n }\n }\n // return false\n return false;\n }", "function twoStrings(s1, s2) {\n const s1len = s1.length;\n const s2len = s2.length;\n let result = \"NO\";\n\n if(s1len >= 1 \n && s1len <= 100000\n && s2len >= 1\n && s2len <= 100000) {\n //traverses each letter to see if one letter === in other string.\n result = (s1.split('')\n //use filter to remove any character not present in the other string.\n .filter((el, key) => s2.indexOf(el) > -1)\n .length > 0) ? \"YES\" : \"NO\";\n } \n return result;\n}", "function isRotation(str1, str2) {\n if (str1.length !== str2.length) {\n return false;\n } else {\n let concatination = str1 + str1;\n if (concatination.indexOf(str2) !== -1) return true;\n return false;\n }\n}", "check(s1, s2) {\n for (let i = 0; i < s1.length; i++) {\n if (s1.charAt(i) != s2.charAt(i)) {\n return false;\n }\n }\n return true;\n }", "function checkIfStringEndsWithSuffix(string, suffix) {\n return string.slice((string.length - suffix.length), string.length) === suffix;\n}", "function confirmEnding(str, target) {\n var end = \"\";\n for(var i = str.length - target.length; i < str.length; i++) {\n end += str[i];\n }\n return end === target;\n}", "function isSubsequence(str1, str2) {\n\tlet i = 0;\n\tlet j = 0;\n\twhile (j < str2.length) {\n\t\tif (str1[i] === str2[j]) i++;\n\t\tif (i === str1.length) return true;\n\t\tj++;\n\t}\n\treturn false;\n}", "function confirmEnding(str, target) {\n let indexCompare = str.length - target.length;\n let slicedStr = str.slice(indexCompare, str.length);\n if (target == slicedStr) return true;\n else return false;\n}", "function strEndsWith ( input, match ) {\r\n\t\treturn input.slice(-1 * match.length) === match;\r\n\t}", "function strEndsWith ( input, match ) {\r\n\t\treturn input.slice(-1 * match.length) === match;\r\n\t}", "function EndsWith(str, suffix) {\n\treturn str && String(str).endsWith(suffix);\n}", "function strEndsWith ( input, match ) {\n\t\treturn input.slice(-1 * match.length) === match;\n\t}", "function strEndsWith ( input, match ) {\n\t\treturn input.slice(-1 * match.length) === match;\n\t}", "function isSubsequence(str1, str2) {\n var i = 0;\n var j = 0;\n if (!str1) return true;\n while (j < str2.length) {\n if (str2[j] === str1[i]) i++;\n if (i === str1.length) return true;\n j++;\n }\n return false;\n }", "function confirmEnding(str, target) \n{\n return str.slice(str.length - target.length) === target;\n}", "function arrayEndsWith(array1, array2) {\n\t\tlet ends = array1.slice(array1.length - array2.length);\n\n\t\tfor (let i = 0; i < array2.length; i++) {\n\t\t\tif (ends[i] !== array2[i]) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}", "function isSubsequence(str1, str2) {\n\n if (str1.length > str2.length) return false\n\n let index1 = 0\n let index2 = 0\n\n while (index2 < str2.length) {\n if (str2[index2] === str1[index1]) {\n index1++\n if (index1 === str1.length) return true\n }\n index2++\n }\n\n return false\n}", "function isSubsequence(str1, str2) {\n var i = 0;\n var j = 0;\n if (!str1) return true;\n while (j < str2.length) {\n if (str2[j] === str1[i]) i++;\n if (i === str1.length) return true;\n j++;\n }\n}", "function endsWith(string, pattern) {\n\t\tvar d = string.length - pattern.length;\n\t\treturn d >= 0 && string.indexOf(pattern, d) === d;\n\t}", "function isSubsequence(str1, str2) {\n let currIdx = 0;\n\n for (let i = 0; i < str2.length; i++) {\n if (str2[i] === str1[currIdx]) {\n currIdx++;\n }\n if (currIdx === str1.length) {\n return true;\n }\n }\n return false;\n}", "function confirmEnding(str, target) {\n var targetLength = target.length;\n\tvar ending = str.substring(str.length-targetLength);\n return ending === target;\n}", "function isSubsequence(str1, str2) {\n var i = 0;\n var j = 0;\n if (!str1) return true;\n while (j < str2.length) {\n if (str2[j] === str1[i]) i++;\n if (i === str1.length) return true;\n j++;\n }\n return false;\n}", "function confirmEnding(str, target) {\n \n // measure length of target string\n let lenTarget = target.length;\n \n // check end of str using negative indexing on str.slice()\n let strSuffix = str.slice(-lenTarget);\n \n // compare suffix with target\n let result = (target == strSuffix);\n \n return result;\n}", "function isSubstring(s1, s2) {\r\n return s1.includes(s2);\r\n}", "function confirmEnding(str, target) {\n let end = str.endsWith(target);\n return end;\n }", "function end(str, target) {\n // \"Never give up and good luck will find you.\" -- Falcor\n\n var length = target.length;\n var isEqual = target === str.substr(-length);\n return isEqual;\n\n}", "function strEndsWith(input, match) {\n return input.slice(-1 * match.length) === match;\n }", "function isSubsequence(str1, str2) {\n let i = 0\n let j = 0\n if (!str1) return false\n while (j < str2.length) {\n if (str2[j] === str1[i]) i++\n if (i === str1.length) return true\n j++\n }\n return false\n}", "function isSubsequence (str1, str2) {\n let i = 0\n let j = 0\n if (!str1) return true\n while (j < str2.length) {\n if (str1[i] === str2[j]) i++\n if (i === str1.length) return true\n j++\n }\n return false\n}", "function confirmEnding(str, target) \n{\n if(str.endsWith(target))\n {\n return str;\n }\n\n}", "function substring(string1, string2){\n let pattern = \"\";\n for(let i = 0; i < string1.length; i++){\n pattern += string1[i];\n }\n for(let i = 0; i < string2.length; i++){\n if(string2.includes(pattern)){\n return true;\n }\n }\n return false;\n}", "function stringLastIndexOf(s1, s2) {\n var i;\n for (i = s1.length; i > 0; i--) {\n if (s1[i] == s2)\n return i;\n }\n return -1;\n}", "function isSubsequence(str1, str2) {\n let p1 = 0;\n let p2 = 0;\n while (p1 < str1.length && p2 < str2.length) {\n if (str1[p1] === str2[p2]) {\n p1++;\n p2++;\n } else {\n // str1[p1] !== str2[p2]\n p2++;\n }\n }\n if (p1 === str1.length) return true;\n else return false;\n}", "function longestString (str1, str2) {\n if (str1.length < str2.length) {\n return -1;\n }\n if (str1.length > str2.length) {\n return 1;\n }\n // str1 must be equal to str2\n return 0;\n}", "function oneAway(str1, str2) {\n if (str1.length - str2.length > 1 || str2.length - str1.length > 1) {\n return false;\n } \n\n if (str1.length === str2.length) {\n let charDiff = 0;\n for (let i = 0; i < str1.length; i++) {\n if (str1[i] !== str2[i]) {\n charDiff++;\n }\n\n if (charDiff > 1) {\n return false;\n }\n }\n } else {\n let max;\n let min;\n\n if (str1.length > str2.length) {\n max = str1;\n min = str2;\n } else {\n max = str2;\n min = str1;\n }\n\n let i = 0;\n let j = 0;\n let charDiff = 0;\n\n while (i < max.length && j < min.length) {\n if (max[i] !== min[j]) {\n charDiff++;\n j--;\n }\n\n if (charDiff > 1) {\n return false;\n }\n\n i++;\n j++;\n }\n }\n\n return true;\n}", "function isSubsequence(str1, str2) {\n let pointer1 = 0;\n let pointer2 = 0;\n let matches = 0;\n\n while (pointer2 < str2.length) {\n if (str1[pointer1] === str2[pointer2]) {\n matches++;\n pointer1++;\n pointer2++;\n } else {\n pointer2++;\n }\n }\n if (matches === str1.length) {\n return true;\n }\n return false;\n}", "function isSubsequence2(str1, str2) {\n if (str1.length === 0) return true;\n if (str2.length === 0) return false;\n if (str1[0] === str2[0]) return isSubsequence2(str1.slice(1), str2.slice(1));\n else return isSubsequence2(str1, str2.slice(1));\n}", "function confirmEnding (str, target) {\n let lastStr = str.slice(str.length - target.length, str.length)\n\n if (lastStr === target) {\n return true\n } else {\n return false\n }\n}", "function confirmEnding(str, target){\n return str.slice(str.length - target.length) === target;\n}", "function isSubsequence(str1, str2) {\n let i = 0\n while(i<str2.length){\n if(str1[0] == str2[i]){\n if(str1.length < 0){\n str1.shift()\n } else {\n return true\n }\n }\n i++\n }\n return false\n}", "function isRotation(str1, str2) {\n let str1Length = str1.length;\n\n // check that they are not empty strings\n if (str1Length == str2.length && str1Length > 0) {\n // basically double the longer string and see if it includes the smaller one- like in the cs challenge\n let str1Double = str1 + str1;\n return str1Double.includes(str2);\n }\n return false;\n}", "function isMerge(s, part1, part2) {\n\n // convert strings to arrays for processing\n var sArr = s.split('');\n var p1Arr = part1.split('');\n var p2Arr = part2.split('');\n\n // track case where character in s cannot be found\n var valid = true;\n\n // starting at the first character in s\n // for each character\n sArr.forEach(function(char){\n // check to see if the character can be found at the current location in either of the two other strings\n if (p1Arr[0] === char) {\n p1Arr.shift();\n } else if (p2Arr[0] === char) {\n p2Arr.shift();\n } else {\n // if the character cannot be found then make arguments as invalid\n valid = false;\n }\n });\n // after going through all of the characters in s\n // check to see that the part1 and part2 strings are empty\n if (valid && p1Arr.length === 0 && p2Arr.length === 0) {\n // if both are empty then return true\n return true;\n }\n // else return false\n return false;\n}", "function confirmEnding(str, target) {\n\treturn str.slice(str.length - target.length) === target;\n}", "function rotatedString(str1, str2) {\n if (str1.length != str2.length) {\n return false;\n }\n const temp = str1.concat(str1);\n if (temp.includes(str2)) {\n return true;\n } else {\n return false;\n }\n}", "function isSubsequence(str1, str2) {\n var i = 0;\n var j = 0;\n if (!str1) {\n console.log(\"isSubsequence:\",true);return;\n }\n while (j < str2.length) {\n if (str2[j] === str1[i]) i++;\n if (i === str1.length) {\n console.log(\"isSubsequence:\",true);return;\n }\n j++;\n }\n console.log(\"isSubsequence:\",false);return;\n }", "function f(str) {\n if (str.length == 0) return false\n else if (str.length == 1) return true\n else {\n let first = str.slice(0, (str.length) / 2)\n let second = str.slice((str.length + 1) / 2, str.length)\n let i = 0\n let j = first.length\n while (i !== j) {\n if (first[i] == second[j]) {\n i++\n j++\n } else return false\n }\n return true\n }\n}", "function second_contains_first (str1, str2) {\n // is the first string in the second\n\n // for each in string1 i\n // for each in string2 k\n // if i==k\n // walk until false, \n\n\n }" ]
[ "0.8507432", "0.8217708", "0.7524355", "0.73843324", "0.72632766", "0.7217883", "0.71901774", "0.71891886", "0.71859145", "0.71859145", "0.7176736", "0.7166842", "0.7125076", "0.70127064", "0.70106536", "0.69919944", "0.69919944", "0.69919944", "0.69919944", "0.69919944", "0.69919944", "0.69919944", "0.6963762", "0.6948986", "0.69306666", "0.6925592", "0.6917949", "0.6915976", "0.6871884", "0.6852202", "0.6850822", "0.68433666", "0.6841151", "0.6832094", "0.68314254", "0.6824184", "0.68001074", "0.6799086", "0.6799086", "0.679742", "0.67961925", "0.6795469", "0.6788512", "0.6784831", "0.6782916", "0.6782916", "0.6781852", "0.67705786", "0.6766694", "0.67661494", "0.67473274", "0.6709621", "0.66931033", "0.669092", "0.6680719", "0.6679647", "0.6667413", "0.6658127", "0.6656809", "0.66555434", "0.6651125", "0.66503596", "0.66503596", "0.6645465", "0.66445744", "0.66445744", "0.66428244", "0.66383904", "0.6631175", "0.6623419", "0.6620814", "0.6614452", "0.6604774", "0.6594496", "0.6592243", "0.65904903", "0.65891826", "0.65886486", "0.6588434", "0.6586956", "0.6585767", "0.65734977", "0.65722686", "0.65722024", "0.6565165", "0.6557345", "0.6547239", "0.65432525", "0.6538256", "0.652914", "0.65185994", "0.6517787", "0.6512883", "0.65126604", "0.65098", "0.65084815", "0.65010446", "0.6496311", "0.6495948", "0.6495211" ]
0.7175202
11
count amount of characters in string
function count (string) { var count = {}; string.split('').forEach(function(s) { count[s] ? count[s]++ : count[s] = 1; }); return count; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function count(str) {\n return str.length;\n}", "function stringCount(str) {\n return str.length\n}", "function countChars(txt) {\n return txt.length;\n}", "function numChars(str1){\n return str1.length\n}", "function count(str,char) {\n\tvar re = new RegExp(char,\"gi\");\n\treturn (str.match(re) || []).length;\n}", "function countChars(str,char){\n\tvar count =0\n\twhile(str !=\"\"){\n if(str[0] === char){\n \tcount++;\n }\n str = str.slice(1);\n }\n return count\n }", "function countChars(){\n\n}", "function numOfChar(string) {\n // Regular expression, get all characters\n let regExp = /./g;\n let retThis = string.match(regExp);\n\n if (retThis)\n {\n return retThis.length;\n }\n else\n {\n return 0;\n }\n}", "function charactersOccurencesCount() {\n \n}", "function charactersOccurencesCount() {\n \n}", "function charactersOccurencesCount() {\n \n}", "function charactersOccurencesCount() {\n \n}", "function countChars(str, char) {\n count = 0;\nfor (var i = 0; i <= str.length - 1; i++) {\n if (str[i] === char) {\n count++;\n}\n}\nreturn count;\n}", "function sc_stringLength(s) { return s.length; }", "function charactersOccurencesCount() {\n\n}", "function charactersOccurencesCount() {\n\n}", "function charactersOccurencesCount() {\n\n}", "function charactersOccurencesCount() {\n\n}", "function charactersOccurencesCount() {\n\n}", "function getCount(str) {\n // regex:\n // 'g' tells to find all matches, not just the first.\n // 'i' tells to be case insensitive.\n // What goes inside the '//'' is the pattern.\n // '[]'' tells to match any character in a set.\n // 'aeiou' are the characters in the set.\n // because of the '^' the replace function removes everything that is NOT within the\n // regex statement\n // without it, the replace function would replace all of the vowels and return only\n // the other characters\n return str.replace(/[^aeiou]/gi, '')\n // then count the length of the remaining string\n .length;\n}", "function countChars(str, char) {\n var numOfChar = 0;\n\n for (var i = 0; i < str.length; i++) {\n if (str[i] === char)\n numOfChar += 1;\n\n }\n return numOfChar;\n }", "function getCount(str) {\n return str.toLowerCase().split('').filter(function(char) {\n return char == 'a' || char == 'e' || char == 'i' || char == 'o' || char == 'u';\n }).length;\n}", "function fancyCount(str){\n return Array.from(str.split(/[\\ufe00-\\ufe0f]/).join(\"\")).length;\n }", "function countChar(s, c){\n let counter = 0; \n for(let a=0; a<=s.length; a++){\n if(s[a] === c){\n counter++; \n }\n }\n return counter; \n}", "function countChar(string, theChar) {\r\n\tvar total = 0;\r\n\r\n\tfor (var i = 0; i < string.length; ++i) {\r\n\t\tif (string.charAt(i) === theChar) {\r\n\t\t\t++total;\r\n\t\t}\r\n\t}\r\n\r\n\treturn total;\r\n}", "function char_count(str, letter){\n\tconst regExp = new RegExp(letter,\"gi\");\n\treturn str.match(regExp).length;\n}", "function subLength(str,char)\n{\n let charcount=0;\n let len=-1;\n for(let i=0;i<=str.length;i++)\n {\n if( str[i]===char)\n {\n charcount++;\n \n } \n \n }\n \n return charcount;\n \n}", "function fancyCount(str){\n return Array.from(str.split(/[\\ufe00-\\ufe0f]/).join(\"\")).length;\n}", "function Count(str, c) {\n var counts = 0;\n for (var _i = 0, str_1 = str; _i < str_1.length; _i++) {\n var chr = str_1[_i];\n if (chr == c) {\n counts = counts + 1;\n }\n }\n return counts;\n }", "function countChar(string, char) {\n var count = 0\n char = char.toLowerCase()\n var x = string.toLowerCase().split(\"\")\n for(var i=0;i<x.length;i++){\n if(x[i]==char) count++\n }\n return count\n}", "function getCount(str) {\n return (str.match(/[aeiou]/ig)||[]).length;\n }", "function countChars(string, character){\n\tvar count= 0;\n\tfor (var i= 0; i < string.length; i++){\n\t\tif (string[i]=== character){\n\t\t\tcount++;\n\t\t}\n\n\t}\n\treturn count;\n}", "function char_count(str, letter) {\nlet count = 0;\n for (let i = 0; i < str.length; i++) \n {\n if (str.charAt(i) == letter) \n {\n count += 1;\n }\n }\nreturn count;\n}", "function countChars(string) {\n var stringArray = string.split(\"\").filter(function(x) {\n if (x !== \" \") {\n return x;\n }\n });\n\n return stringArray.reduce(function(acc, curr) {\n\n if (!acc[curr]) {\n acc[curr] = 1;\n }\n else {\n acc[curr] += 1;\n }\n return acc;\n }, {});\n}", "function countChars(strText,charToCount)\r\n\t{\r\n\t\tvar intStartingPosition = 0;\r\n\t\tvar intFoundPosition =0;\r\n\t\tvar intCount = 0;\r\n\t\t\r\n\t\t// checking for the null character\t\r\n\t\tif (charToCount==\"\")\r\n\t\t{\r\n\t\t\treturn intCount;\r\n\t\t}\t\r\n\t\twhile((intFoundPosition=strText.indexOf(charToCount,intStartingPosition)) >= 0)\r\n\t\t{\r\n\t\t\tintCount++;\r\n\t\t\tintStartingPosition = intFoundPosition + 1;\r\n\t\t}\r\n\t\t\t\r\n\t\treturn intCount ;\r\n\t}", "function countCharacters(string) {\n var count = new Map();\n string.split('').forEach(function(s) {\n count.set(s, (count.get(s) ?? 0) + 1);\n });\n return count;\n}", "function countChar(string, char) {\n var count = 0;\n for (var number = 0; number < string.length; number++) {\n if (string.charAt(number)===char)\n count++;\n };\n return count;\n}", "function length (string){\n\treturn string.length;\n}", "function countCharacter(str, char) \r\n{\r\n if (!str)\r\n return 0;\r\n\r\n var count = 0;\r\n for(var i = 0; i < str.length; i++)\r\n {\r\n if(str.charAt(i) === char)\r\n count++;\r\n }\r\n \r\n return count;\r\n}", "function countCharacters(s) {\n return s.ranges.reduce((count, [from,to]) => {\n return count + (to - from);\n }, 0);\n}", "function count(input) {\n var numberChar = input.length;\n return numberChar;\n}", "function countChar(str, character){\n let count = 0;\n for(let char of str){\n char === character ? count++ : null;\n }\n return count;\n}", "function numberofCharacters(input) {\n const num = input.length\n console.log( input + \" \" + \"has\" + \" \" + num + \" \" + \"characters\");\n}", "function letterCounter (x) {\n\t return x.replace(/[^a-zA-Z]/g, '').length;\n\t}", "function strCount(str, letter){ \n let counter = 0;\n for (i = 0; i < str.length; i++){\n if (str.charAt(i) === letter){\n counter += 1;\n }\n }\n return counter;\n}", "function length(str) {\n return str.length;\n}", "function stringLength(str){\nvar result =0;\nwhile(str != \"\"){\n\n \tresult+=1;\n str= str.slice(1);\n}\n \n return result;\n \n }", "function countChar(str,letter){\n\tvar count = 0;\n\tfor(var i = 0; i < str.length; i++){\n\t\tif(str[i] === letter){\n\t\t\tcount++;\n\t\t}\n\t}\n\treturn count;\n}", "function char_count(str, letter){\n\nvar character=letter;\nvar count=0;\nfor(var i=0;i<str.length;i++){\n if(str.charAt(i)==character){\n count++;\n }\n}\nreturn count;\n}", "function count(str, letter){\r\n let n =0\r\n if(str === \"\"){\r\n return 0\r\n } else {\r\n return 1+ count(str.substr(1), letter) \r\n } \r\n }", "function countAs(string) {\n var stringArray = string.split(\"\");\n var count = 0;\n\n stringArray.forEach(function (letter) {\n if (letter === \"a\") {\n count++;\n }\n });\n\n return count;\n}", "function count_char_string (substring, string) {\n var n=0;\n var pos=0;\n\n while(true){\n pos=string.indexOf(substring,pos);\n if(pos!=-1){ n++; pos+=substring.length;}\n else{break;}\n }\n return(n);\n }", "function charFreq(string) {\n //...\n}", "function charFreq(string) {\n //...\n}", "function length(str) {\n\treturn str.length;\n}", "function countChar(string){\n var counts = {}; //1\n var currChar, currCharCount; //1\n for (var i = 0; i < string.length; i++){ // n\n currChar = string[i]; // 1\n currCharCount = 1; // 1\n for (var j = i+1; j < string.length; j++){ // n - j\n if (currChar === string[j]){ //1\n currCharCount++; //1\n }\n }\n if (!counts.hasOwnProperty(currChar)){ // 1\n counts[currChar] = currCharCount; //1\n }\n }\n return counts; //1\n}", "function RunLength(str) {\n var letter = str.charAt(0);\n var count = 0;\n var result = '';\n str.split('').forEach(function(c) {\n if (c == letter)\n count++;\n else {\n result += count + letter;\n letter = c;\n count = 1;\n }\n });\n result += count + letter;\n return result;\n}", "function getCharCount(str) {\n var charCount = 0;\n var whiteSpaceRegExp = /\\s/g;\n var whiteSpaceChar = /&nbsp;/g;\n if (str !== null || str !== undefined) {\n charCount = str.replace(whiteSpaceRegExp, '').replace(whiteSpaceChar, '').length;\n }\n return charCount;\n }", "function countChar(str, letter) {\n var letterCount = 0;\n for (let i = 0; i < str.length; i++) {\n if (str.charAt(i) == letter) {\n letterCount += 1;\n }\n }\n return letterCount;\n}", "function charCount(myChar, str) {\n let times = 0;\n str.split('').map((char) => {\n if (char === myChar) {\n times++\n }\n return char;\n })\n return times;\n}", "function countChar(string, char) {\n let letterCounter = 0;\n for (let i = 0; i < string.length; i++) {\n if (string.charAt(i) == char) {\n letterCounter++;\n }\n }\n return letterCounter;\n}", "function counts(str, chr){\n var count = 0; \n for (let index = 0; index < str.length; index++) {\n if(str[index] === chr) count++;\n }\n console.log( `the count of ${chr} is ` + count);\n}", "function totalLetters (string) {\n var length=0;\n for (var i=0; i < string.length; i++){\n length = length + string[i].length;\n }\n console.log(length);\n}", "function length(str) {\n return str.length;\n }", "function strCount(str, letter){ \n counter = 0;\n for (var i = 0; i < str.length; i++) {\n if (letter === str[i]) {\n counter++\n }\n }\nreturn counter\n}", "function strCount(str, letter){\n return str.split(letter).length - 1;\n}", "function getCount(str) {\n let vowelsRegex = /[a,e,i,o,u]/g\n let result = str.match(vowelsRegex)\n return result ? result.length : 0\n}", "function getChrCount(string, chr) {\r\n return string.split(chr).length - 1;\r\n}", "function getLength(string){\n return string.length;\n}", "function charFreq(string){\n //...\n}", "function charFreq(string){\n //...\n}", "function getCount(str) {\n const regex = /[aeiou]/g\n \n return str.match(regex) == null ? 0 : str.match(regex).length\n }", "function countOccurrences(string, letter) {\n console.log(string.split(letter).length - 1);\n}", "function countLetters(str, chr) {\n return str.toUpperCase().split(chr.toUpperCase()).length-1;\n}", "function countLettersAndDigits(input) {\n //I first set const for a pattern using regexp (regular expression)\n const patt = /[0-9]|[a-z]|[A-Z]/g;\n //use the match function to find all letters and digits and count the length.\n return (input.match(patt)||[]).length;\n }", "function countChar(str,element){\nvar arr = str.split('');\nvar total = 0 ;\n\n\tfor(i=0;i<arr.length;i++){\n\t\tif(arr[i]=== element)\n\t\t\ttotal++;\n\t}\t\n\treturn total;\n}", "function countCharacters(string){\n const temp = {}\n const tempStringArray = string.split(\"\");\n tempStringArray.forEach((item) =>{\n temp.hasOwnProperty(item) ? temp[item] += 1 : temp[item] = 1;\n })\n\n\n return temp;\n }", "function countChars(str) {\n var result = {\n };\n Array.from(str).forEach(function(char) {\n var curVal = result[char];\n if (curVal) result[char] += 1;\n else result[char] = 1;\n });\n return result;\n}", "function countOccurrences(string, character) {\n var arry = string.split(' ');\n return filter(arry, function(element, i){\n return element === character;\n }).length\n }", "function charCount(str){\n // do something\n // return an object with keys that are lowercase alphanumeric characters in the string; values should be the counts for those characters in the string\n // only keeping track of lowercased alphanumeric characters \n}", "function charCount(string)\n{\n\tvar count = {};\n\n\tfor(var i = 0; i<= string.length - 1; i++)\n\t{\n\t\tvar char = string[i];\n\n\t\tif(count[char] === undefined)\n\t\t{\n\t\t\tcount[char] = 1\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcount[char] += count[char];\n\t\t}\n\t}\n\treturn count;\n}", "function countBs(string) {\n return countChar(string, \"B\");\n}", "function getLength(string) {\n return string.length\n}", "function occurrences (char,str){\n let count = 0 \n for (let i = 0; i < str.length; i++){\n if(char === str[i]){\n count++\n }\n}\nreturn count;\n}", "function countCharOccurrences(str, char) {\n return str.toLowerCase().split(char.toLowerCase()).length - 1;\n}", "static countSubString(input, strToCount) {\n if (!input || !strToCount) {\n return 0;\n }\n return (input.match(new RegExp(strToCount, 'g')) || []).length;\n }", "function getLength(string) {\n return string.length;\n}", "function getLength(string) {\n return string.length;\n}", "function getLength(string) {\n return string.length;\n}", "function countLetters (s) {\n return s.split('')\n .filter(c => c !== '-')\n .reduce((counts, c) => {\n const count = counts[c] || 0\n return Object.assign(counts, { [c]: count + 1 })\n }, {})\n}", "function noOfOccurance(str) {\n\tvar count=0;\n\tfor(let i=0; i<str.length; ++i) {\n\t\tif(str[i]==\"m\") count++\n\t}\n\treturn count;\n}", "function getCount(str) {\n let vowelsCount = 0;\n for (current_char of str) {\n if (current_char === 'a' | current_char === 'e' | current_char === 'i' | current_char === 'o' | current_char === 'u') {\n vowelsCount++;\n }\n }\n return vowelsCount;\n }", "function charNumInString(string, char) {\n let count = 0\n for (const str_char of string) {\n if (str_char == char) {\n count++\n }\n }\n return count\n }", "function countComSubs(str) {\n var count = 1;\n var spc = \" \";\n var rg = new RegExp(spc, 'g');\n var res = str.match(rg);\n if (res == null) {\n count = -100;\n } else {\n count = res.length;\n }\n return count;\n}", "function countChars(string, letter) {\n let evenStr = string.toLowerCase();\n let evenLtr = letter.toLowerCase();\n let stringCount = 0;\n for(let i = 0; i < evenStr.length; i++){\n if(evenStr[i] === evenLtr){\n stringCount++;\n }\n }\n return stringCount;\n}", "function countNumOfWords(str) {\n\n}", "function getCount4(str) {\n const vowels = {\n a: true,\n e: true,\n i: true,\n o: true,\n u: true\n };\n\n return str.split('').filter((currentLetter) => vowels[currentLetter]).length;\n}", "function countChars(str) {\n var result = {};\n Array.from(str).forEach(function (char) {\n var curVal = result[char];\n\n if (curVal) {\n result[char] += 1;\n } else {\n result[char] = 1;\n }\n });\n return result;\n}", "function strLen(str) {\n // hello\n // debugger;\n // isejimo salyga\n if (str === \"\") return 0;\n\n // console.log(\"str:\", str);\n\n //veiksmas ir rekursija\n let total = 1 + strLen(str.slice(1));\n return total;\n}", "function charCount(charCount) {\n // let length = charCount.length;\n // console.log(length);\n console.log(\"charCount is \" + charCount.length);\n}", "function getCharCount1 (str) {\n charCount = {}\n for(let char of str) {\n charCount[char] = charCount[char] ? charCount[char]+1 : 1\n }\n return charCount\n}" ]
[ "0.8247284", "0.819294", "0.80376357", "0.79851925", "0.7916394", "0.7881483", "0.7865591", "0.78522545", "0.7838028", "0.7838028", "0.7838028", "0.7838028", "0.7816918", "0.78112334", "0.77909994", "0.77909994", "0.77909994", "0.77909994", "0.77909994", "0.7771662", "0.774138", "0.7730968", "0.769827", "0.76802766", "0.767116", "0.76599115", "0.765118", "0.76314086", "0.75960714", "0.75875074", "0.75702965", "0.75700706", "0.75361055", "0.7535204", "0.7514061", "0.74794984", "0.74617016", "0.7453646", "0.7450445", "0.7429384", "0.74186856", "0.7401512", "0.7392399", "0.73871416", "0.7378493", "0.73771304", "0.737116", "0.7369591", "0.7367692", "0.7358959", "0.73525727", "0.73448116", "0.7338755", "0.7338755", "0.7336529", "0.7334932", "0.7332194", "0.733092", "0.7326411", "0.7319318", "0.7311933", "0.7309945", "0.73077816", "0.73051184", "0.7297693", "0.72879475", "0.72839993", "0.7278077", "0.7267705", "0.7264636", "0.7264636", "0.7240411", "0.7230395", "0.7220573", "0.7217229", "0.72109246", "0.7207035", "0.72062665", "0.71898174", "0.7177587", "0.7173407", "0.7149041", "0.71420926", "0.7137825", "0.7135628", "0.71212393", "0.71173185", "0.71173185", "0.71173185", "0.71168816", "0.7109511", "0.71088535", "0.7108658", "0.71070236", "0.70935977", "0.7084078", "0.707277", "0.70701516", "0.70670027", "0.7064951", "0.70644826" ]
0.0
-1
'this' is a reference to an object that represents the current execution scope
function sayHi() { console.log("HI"); console.log(this); // will print the window object }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function contextOfThis(){\n return this\n}", "function doSomethingElse() {\n console.log(this, 'normal function, this has its own context here');\n console.log(self, 'normal function with a workaround to use this storing it in a variable called self');\n }", "function thisExample(){\n\tconsole.log(this); //will also represent the Window\n}", "function whatIsThis() {\n console.log(\"this = \", this);\n}", "function whatIsThis() {\n console.log(this);\n}", "function getThis(){\n // console.log(this);\n}", "function printThis() {\n console.log(this); // this logs the window context\n}", "function whatisthis() {\n return this;\n }", "function thisFunction() {\n console.log(this);\n}", "function checkThis()\n{\nconsole.log(this);\n}", "function this1() {\n console.log(\"this in function\", this);\n}", "function a() {\n console.log(this);\n}", "function qwe(){\n // \"this\" is different here too!\n console.log(this); // not what we wanted!\n }", "function logThis() {\n console.log(this);\n}", "function printThis() {\n console.log(this);\n}", "function foo () {\n console.log(this); // what does this point to? // the global object, which is window\n}", "function a(){\n console.log(this)\n}", "function calling() {\n console.log(this)\n}", "function myname() {\n console.log('i am this', this) // 'this' have current calling reference\n\n} // undefined", "function SomeFunc() {\n //console.log(this);\n \n}", "function checkThis() {\n console.log(this);\n}", "function foo(){\n\tconsole.log(this); //window object\n}", "function a() {\n console.log(this)\n}", "function foo() {\n alert(this);\n}", "function logThisFn() {\n console.log('Function logThis: ', this); // this point to the same memory spot of the global ex context\n\n // I can create a variable attached to the global object\n this.myNewVariable = 'Hello';\n}", "function thisWindow(){\n console.log(this);\n}", "function whatIsThis() {\n return this;\n}", "function whatIsThis() {\n return this;\n}", "function callThat(){\n console.log(this)\n }", "function showThis() {\n console.log(this);\n}", "function doStuff() {\n console.log('I am doing things.');\n console.log(this);\n}", "function aFunction () {\n console.log(this); \n}", "function foo() {\n console.log(this.bar);\n}", "function foo() {\n console.log(this.bar);\n}", "function foo() {\n console.log(this.bar);\n}", "function foo(){\n console.log(this.bar);\n}", "function alertThis() {\n alert(this);\n}", "function a(){\n\tconsole.log(this)\t\n}", "function f(){\n console.log(this);\n }", "function foo1() {\n console.log(\"Hello Foo1\");\n console.log(this);\n}", "function thisIsFun() {\n console.log(this); //undefined\n}", "function someFunc(param) {\n console.log(\"param:\", param)\n console.log(\"this:\", this)\n}", "function self($this) {\n\treturn $this;\n}", "function doSomething(service){\n this.foo = 'Hello';\n var self = this;\n service.something(function(){\n // console.log(this.foo)\n console.log(self.foo);\n });\n}", "function myfunc() {\n console.log(this);\n}", "function myfunc(){\n console.log(this);\n}", "start() {\n //let self = this;\n }", "function demo(){\n console.log(this);\n}", "function name(){\nconsole.log(this);//this do show the whole window object because this is not assined to a object method\n// if you use this keyword in any function or conditions(if ,ifelse ,etc) or loops (for,while,etc) then this keyword poits on the window object\n}", "function whodis() {\n console.log(this);\n}", "function myFunc() {\n console.log(this); // Again what is returned depends on where it is run\n}", "function obj() { return this; }", "function fu1() {\n console.log('this::', this);\n}", "ThisExpression(node) {\n const current = stack.getCurrent();\n\n if (current && !current.valid) {\n context.report({ node, message: \"Unexpected 'this'.\" });\n }\n }", "function someFunction1 () {\n console.log(this);\n return;\n}", "function myFunction() {\n console.log(this);\n}", "function hello() {\n\tconsole.log(this);\n}", "function myFunction() {\n console.log(this);\n}", "constructor(params) {\n super(params);\n\n const oThis = this;\n }", "function simpleFunction() {\n console.log(this)\n}", "function x()\n{\n\tconsole.log(this);\n}", "function sayBye() {\n log(this);\n}", "function getThis() {\n console.log(this); //undefined in strict mode but Window\n}", "function baz() {\n var self = this;\n console.log('baz');\n bar();\n}", "function foo() {\n console.log(\"gl \" + this.bar);\n}", "function foo() {\n\tconsole.log( this.bar );\n}", "function getWindowThis() {\n console.log(this)\n}", "function greet()\n{\n console.log(this);\n}", "function foo() {\n console.log( this.bar );\n}", "function sayHi() {\n console.log(\"HI\");\n console.log(this); // --> should return an WINDOW object. --> current execution scope. \n}", "function start() {\n console.log(this);\n}", "function window() {\n console.log(this);\n}", "function window() {\n console.log(this);\n}", "function foo(){\n console.log(this.a);\n}", "function foo() {\n console.log(this.a);\n}", "function foo() {\n console.log(this.a);\n}", "function foo() {\n console.log(this.a);\n}", "function foo() {\n console.log(this.a);\n}", "function foo(){\n console.log(this.a);\n}", "function foo() {\n console.log(this.a);\n}", "function %%Name%%() {\n\t\t\t/*jshint validthis: true */\n\t\t\tvar vm = this;\n\n\t\t}", "function globalBinding() {\n console.log(this); //points to the window object\n}", "get context() {\n\t\treturn this.__context;\n\t}", "get context() {\n\t\treturn this.__context;\n\t}", "get context() {\n\t\treturn this.__context;\n\t}", "function inner(){\n\t\t\tconsole.log(this); //will again represent Window since inner is not a method but a function\n\t\t}", "function windowbinding() {\n console.log(this);\n}", "constructor() {\n super()\n self = this\n self.init()\n }", "constructor(name, age)\n {\n this._name = name;\n this._age = age;\n\n //mojem da setnem neshto na funkciq\n this._something = function(){\n return \"I am Function\";\n }\n //tik moga da si rabota normalno\n let friend = \"Petre\"; \n let arr = [];\n let obj = {};\n\n //this sochi kum tekushtata instanciq na klasa:\n //OBACHE VUV FUNKCIQ 'this' VECHE NE RABOTI\n //OBACHE NIE UK MOJEM DA GO SEIVAME V PROMENLIVA I DA SI GO POLZVAME\n let tekushObekt = this; \n console.log(tekushObekt); //Person { _name: 'Atanas', _age: 25 }\n\n\n function printThis() {\n console.log(this); // undefined\n console.log(tekushObekt); //Person { _name: 'Atanas', _age: 25 }\n }\n printThis(); // VAJNO!!! : Sus printThis.call(this); PROMENQME THIS-a DA SI SOCHI KUM OBEKTA KAKTO PREDI\n }", "function myFunction() {\n alert(this); // will alert \"undefined\"\n }", "function testThis() {\n console.log(chalk.yellow('this => ' + this));\n console.log(chalk.yellow('this === global => ' + (this === global)));\n }", "function perro(){\r\n console.log(this)\r\n}", "static get() { return currentContext; }", "function thisLogger(){\n console.log(this)\n}", "function foo2() {\n console.log(this.a);\n}", "function foo2() {\n console.log(this.a);\n}", "function this_in_strict() {\n log(this)\n}", "function foo() {\n console.log(this.bar); // default binding - looks to the global scope\n}", "function fnc () {\n console.log(this);\n}", "function greet(){ console.log(this)}", "function foo1() {\n console.log(this.a);\n}" ]
[ "0.7430529", "0.72209483", "0.7047724", "0.7002351", "0.6924332", "0.68703294", "0.68342733", "0.6818696", "0.6809573", "0.6760662", "0.67591065", "0.6720123", "0.67157316", "0.6705324", "0.6703768", "0.66869605", "0.6669496", "0.6666427", "0.6646928", "0.6641873", "0.6639027", "0.6623308", "0.6619538", "0.66102266", "0.6608503", "0.6599229", "0.6585168", "0.6585168", "0.6584892", "0.65783817", "0.65742636", "0.6532871", "0.6530568", "0.6530568", "0.65298915", "0.652079", "0.65163183", "0.6506418", "0.649927", "0.64946365", "0.6489163", "0.6483701", "0.64819264", "0.6475017", "0.644607", "0.64188254", "0.64138126", "0.64117336", "0.6410543", "0.6397476", "0.63886285", "0.6378691", "0.6368837", "0.63446623", "0.63430697", "0.6342122", "0.6339864", "0.63335824", "0.6261979", "0.6261691", "0.6256518", "0.62547874", "0.62512815", "0.62353", "0.6233279", "0.6213729", "0.6212539", "0.62107176", "0.6202785", "0.6200159", "0.61740386", "0.6171634", "0.6171634", "0.6171136", "0.61642736", "0.61642736", "0.61642736", "0.61642736", "0.61563826", "0.6149223", "0.61386925", "0.6129517", "0.6126804", "0.6126804", "0.6126804", "0.6118209", "0.61004543", "0.60880303", "0.607897", "0.60775816", "0.6071619", "0.6068127", "0.6060049", "0.6055971", "0.6050705", "0.6050705", "0.60504013", "0.6045556", "0.60410094", "0.6040392", "0.6034316" ]
0.0
-1
'this' in arrow functions refers to the same object as 'this' in its parent function
start2() { this.timerId = setInterval(() => { console.log(this.pickPhrase()); // 'this' refers to annoyer object }, 3000); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function foo() {\n // console.log(this);\n return () => {\n console.log(\"In arrow function:\", this.a);\n };\n}", "function contextOfThis(){\n return this\n}", "function callMeMaybe() {\r\n return () => { console.log('arrow function: ', this)}\r\n}", "function foo() {\n console.log(this.bar);\n}", "function thisFunction() {\n console.log(this);\n}", "function a() {\n console.log(this)\n}", "function whatIsThis() {\n console.log(this);\n}", "function foo() {\n console.log(this.bar);\n}", "function foo() {\n console.log(this.bar);\n}", "function a(){\n console.log(this)\n}", "function a() {\n console.log(this);\n}", "function whatIsThis() {\n console.log(\"this = \", this);\n}", "function foo(){\n console.log(this.bar);\n}", "function this1() {\n console.log(\"this in function\", this);\n}", "function logThis() {\n console.log(this);\n}", "function getThis(){\n // console.log(this);\n}", "function someFunc(param) {\n console.log(\"param:\", param)\n console.log(\"this:\", this)\n}", "function whatIsThis() {\n return this;\n}", "function whatIsThis() {\n return this;\n}", "function qwe(){\n // \"this\" is different here too!\n console.log(this); // not what we wanted!\n }", "function printThis() {\n console.log(this);\n}", "function doSomethingElse() {\n console.log(this, 'normal function, this has its own context here');\n console.log(self, 'normal function with a workaround to use this storing it in a variable called self');\n }", "function f(){\n console.log(this);\n }", "function foo(){\n console.log(this.a);\n}", "function Obj() { //函数有自己的this\n const f = ()=>console.log(this);\n f();\n}", "function foo() {\n console.log(this.a);\n}", "function foo() {\n console.log(this.a);\n}", "function foo() {\n console.log(this.a);\n}", "function foo() {\n console.log(this.a);\n}", "function SomeFunc() {\n //console.log(this);\n \n}", "function foo() {\n console.log(this.a);\n}", "function foo(){\n console.log(this.a);\n}", "function foo(){\n var a = \"Hello\";\n this.a = 22;\n this.greet =()=>{\n return this.a;\n }\n}", "function explainTheValueOfThis() {\n let obj, method;\n\n obj = {\n go: function () { alert(this); console.log(this); }\n };\n\n obj.go(); // (1) [object Object] // 'this' points to the object obj\n\n (obj.go)(); // (2) [object Object] // 'this' points to the object obj\n\n (method = obj.go)(); // (3) undefined // If 'use strict', 'this' is undefined. If not 'use strict' 'this' points to the global object (window)\n\n (obj.go || obj.stop)(); // (4) undefined // If 'use strict', 'this' is undefined. If not 'use strict' 'this' points to the global object (window)\n}", "function perro(){\r\n console.log(this)\r\n}", "function thisIsFun() {\n console.log(this); //undefined\n}", "function foo() {\n console.log( this.bar );\n}", "function thisExample(){\n\tconsole.log(this); //will also represent the Window\n}", "function showThis() {\n console.log(this);\n}", "function fu1() {\n console.log('this::', this);\n}", "function foo2() {\n console.log(this.a);\n}", "function foo2() {\n console.log(this.a);\n}", "function aFunction () {\n console.log(this); \n}", "function simpleFunction() {\n console.log(this)\n}", "function whatisthis() {\n return this;\n }", "function checkThis() {\n console.log(this);\n}", "constructor(params) {\n super(params);\n\n const oThis = this;\n }", "function self($this) {\n\treturn $this;\n}", "function myfunc() {\n console.log(this);\n}", "function cica () {\n console.log(this)\n}", "function foo() {\n console.log(\"gl \" + this.bar);\n}", "function Person() {\n this.name = 'Jack',\n this.age = 25,\n this.sayName = function () {\n\n console.log(this.age);\n let innerFunc = () => {\n console.log(this.age);\n }\n\n innerFunc();\n }\n}", "function demo(){\n console.log(this);\n}", "function myFunction() {\n console.log(this);\n}", "function whodis() {\n console.log(this);\n}", "function outer() {\n // Arrow Functionで定義した関数を返す\n return () => {\n // この関数の外側には`outer`関数が存在する\n // `outer`関数に`this`を書いた場合と同じ\n return this;\n };\n}", "function foo () {\n console.log(this); // what does this point to? // the global object, which is window\n}", "function foo1() {\n console.log(\"Hello Foo1\");\n console.log(this);\n}", "function afterSomeTime() {\n this.text = \"Two seconds have passed..\";\n let func = () => {\n // Notice how here 'this' captures the outer this\n console.log(this.text);\n };\n setTimeout(func, 2000);\n}", "function thisLogger(){\n console.log(this)\n}", "function a(){\n\tconsole.log(this)\t\n}", "function myname() {\n console.log('i am this', this) // 'this' have current calling reference\n\n} // undefined", "function someFunction1 () {\n console.log(this);\n return;\n}", "start() {\n //let self = this;\n }", "constructor(name, age)\n {\n this._name = name;\n this._age = age;\n\n //mojem da setnem neshto na funkciq\n this._something = function(){\n return \"I am Function\";\n }\n //tik moga da si rabota normalno\n let friend = \"Petre\"; \n let arr = [];\n let obj = {};\n\n //this sochi kum tekushtata instanciq na klasa:\n //OBACHE VUV FUNKCIQ 'this' VECHE NE RABOTI\n //OBACHE NIE UK MOJEM DA GO SEIVAME V PROMENLIVA I DA SI GO POLZVAME\n let tekushObekt = this; \n console.log(tekushObekt); //Person { _name: 'Atanas', _age: 25 }\n\n\n function printThis() {\n console.log(this); // undefined\n console.log(tekushObekt); //Person { _name: 'Atanas', _age: 25 }\n }\n printThis(); // VAJNO!!! : Sus printThis.call(this); PROMENQME THIS-a DA SI SOCHI KUM OBEKTA KAKTO PREDI\n }", "greet(firstName, lastName) {\n console.log(`${this.msg} ${firstName} ${lastName}`);\n // gets the context inherited from the parent scope which is this object\n const innerArrowGreet = () => `${this.msg} ${firstName} ${lastName}`;\n console.log('inner Greet ', innerArrowGreet());\n // gets the context from the window object as this is not bound to anything!\n const innerWOArrowGreet = function () {\n return `${this.msg} ${firstName} ${lastName}`;\n };\n console.log('w/o arrow inner ', innerWOArrowGreet());\n }", "function myfunc(){\n console.log(this);\n}", "function doStuff() {\n console.log('I am doing things.');\n console.log(this);\n}", "function calling() {\n console.log(this)\n}", "function callThat(){\n console.log(this)\n }", "function myFunction() {\n console.log(this);\n}", "function Person(name){\n this.name = name;\n this.greeting =()=>{\n console.log(this.name);\n }\n}", "function printThis() {\n console.log(this); // this logs the window context\n}", "function foo() {\n console.log( this.a );\n}", "function foo1() {\n console.log(this.a);\n}", "function fnc () {\n console.log(this);\n}", "function doSomething(service){\n this.foo = 'Hello';\n var self = this;\n service.something(function(){\n // console.log(this.foo)\n console.log(self.foo);\n });\n}", "function checkThis()\n{\nconsole.log(this);\n}", "function foo() {\n\tconsole.log( this.bar );\n}", "function illustration() {\n console.log(`${this}`);\n}", "function testThis() {\n console.log(chalk.yellow('this => ' + this));\n console.log(chalk.yellow('this === global => ' + (this === global)));\n }", "function greet()\n{\n console.log(this);\n}", "function myFunc() {\n console.log(this); // Again what is returned depends on where it is run\n}", "function foo() {\n console.log( this.a );\n}", "function foo() {\n console.log( this.a );\n}", "function foo() {\n console.log( this.a );\n}", "function log() {\n console.log(this);\n}", "function hello() {\n\tconsole.log(this);\n}", "constructor(props){\n super(props);\n this.fooFunc=this.fooFunc.bind(this);\n this.fooFunc1=this.fooFunc1.bind(this);\n //console.log(this);\n }", "function test() {\n 'use strict';\n console.log(this); // undefined\n }", "function foo(){\n\tconsole.log(this); //window object\n}", "function functionThis() {\n val = this;\n}", "function sayBye() {\n log(this);\n}", "function Greeting() {\n console.log(this);\n}", "function thisWindow(){\n console.log(this);\n}", "print() {\n console.log(this) // here this means actually object\n }", "function f(x) {\n console.log(this.a);\n console.log(x);\n}", "function x()\n{\n\tconsole.log(this);\n}", "function func2() {\n console.log(this);\n}", "function funFunction() {\n return this;\n}", "function func() {\n return this;\n}" ]
[ "0.7275097", "0.69523966", "0.69335866", "0.6865415", "0.6853091", "0.6851767", "0.6844596", "0.68111867", "0.68111867", "0.67866653", "0.6780214", "0.67790794", "0.67765754", "0.67743975", "0.6729302", "0.66929823", "0.6655402", "0.6652875", "0.6652875", "0.66292596", "0.66213703", "0.659772", "0.6550503", "0.6524604", "0.65230644", "0.6522732", "0.6522732", "0.6522732", "0.6522732", "0.64824337", "0.64490527", "0.644515", "0.6430782", "0.6415745", "0.64156425", "0.6403794", "0.6401142", "0.6393559", "0.63855284", "0.63592297", "0.6358835", "0.6358835", "0.6356819", "0.6352866", "0.6348147", "0.6342058", "0.6334508", "0.6333103", "0.6332647", "0.6329319", "0.63166326", "0.6312585", "0.62702084", "0.6269813", "0.6249612", "0.6240625", "0.62402976", "0.62365586", "0.62319714", "0.62299603", "0.62232363", "0.622024", "0.6215601", "0.62151325", "0.6205312", "0.6203431", "0.62028795", "0.6197912", "0.6195443", "0.6182411", "0.6176802", "0.61666346", "0.6166269", "0.61659324", "0.61484486", "0.6134245", "0.6125776", "0.6102615", "0.6097865", "0.60912275", "0.6088884", "0.6074289", "0.6063574", "0.6061484", "0.6061484", "0.6061484", "0.6059381", "0.60546577", "0.60395205", "0.60366505", "0.60330224", "0.60253936", "0.60123324", "0.60066056", "0.60014015", "0.59941244", "0.5989124", "0.59811157", "0.5972776", "0.597195", "0.59710604" ]
0.0
-1
this method should be supported in RXJS 2 public patients: Observable> = this._patients.asObservable();
constructor(patientBackendService) { this.patientBackendService = patientBackendService; this._patients = new Rx_1.BehaviorSubject(immutable_1.List([])); this._patientFormPage = new Rx_1.BehaviorSubject(PatientFormPage.Details); this._showCardView = new Rx_1.BehaviorSubject(true); this._startIndex = new Rx_1.BehaviorSubject(0); this._endIndex = new Rx_1.BehaviorSubject(3); this._patientsSize = new Rx_1.BehaviorSubject(0); this.loadInitialData(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "get patients () {\n\t\treturn this._patients;\n\t}", "getObservable()\n {\n return this.subject.asObservable();\n }", "function Observable() {\n\t/**\n\t * Lista di osservatori che richiedono di essere notificati ad un cambiamento di stato.\n\t * @type {Array.<Observer>}\n\t * @private\n\t */\n\tthis.observers = [];\n\n}", "function updatePatients() {\r\n let fullPatients = App.models.patients.getPatients();\r\n\r\n self.patients = _.filter(fullPatients, self.filters);\r\n }", "function Observable()\n{\n\t// list of observers\n\tObject.defineProperty( this, '_observers', {\n\t\tvalue : new Array(),\n\t\tenumerable : false, // property is not enumerable, so it won't appear in JSON\n\t\twritable : false, // can't be replaced with another object, but array can still be changed\n\t\tconfigurable : false, // can't be deleted\n\t});\n}", "getPatientList() {\n\t Httpconfig.httptokenget(Constant.siteurl+'api/Users/?user_type=patient')\n\t\t.then((response) => {\n console.log(response)\n\t\t\tthis.setState({\n\t\t\t\tpatients: response.data\n\t\t\t});\n\t\t\tconsole.log(this.state.patients);\n\t\t})\n\t\t.catch((error) => {\n\t\t\tconsole.log(error);\n\t\t})\n\t}", "function Observable() {\n this.listeners = {};\n }", "getPatientQueue() {\n return this.patientsQueue.getCollection();\n }", "getOtherPlayerList() {\n let observable = new rxjs__WEBPACK_IMPORTED_MODULE_2__[\"Observable\"](observer => {\n this.socket.on('serverUpdatePlayerList', (msg) => {\n var output = this.getAllOtherPlayersList(msg);\n observer.next(output);\n });\n return () => {\n this.disconnectSocket();\n };\n });\n return observable;\n }", "static getPatients(){\n return new Promise((resolve, reject) => {\n httpApi.get(this.baseUrl)\n .then(response => {\n DefaultHandler(response);\n resolve(response.data);\n })\n .catch(err => {\n DefaultErrorHandler(err);\n reject(err);\n })\n });\n }", "async getPatients(ctx) {\n\n let queryResults = await this.queryByObjectType(ctx, 'patient');\n return queryResults;\n\n }", "get devices() {\n return this._devices;\n }", "get subscriptions() {\r\n return new Subscriptions(this);\r\n }", "getEddyBeacons() {\n return self._eddyBeaconsSubject.asObservable();\n }", "getVoteResults() {\n let observable = new rxjs__WEBPACK_IMPORTED_MODULE_2__[\"Observable\"](observer => {\n this.socket.on('serverSendVoteResults', (results, winners, cardVotingOn) => {\n observer.next([results, winners, cardVotingOn]);\n });\n return () => {\n this.disconnectSocket();\n };\n });\n return observable;\n }", "subscribe() {\n this.unsubscribe();\n this.sub_list.map(\n (value) => this.subscriptions.push(\n this.eventbus.subscribe(value[0], value[1])\n ));\n }", "function Subject () {\n this._observerList = [];\n}", "subscribe(onNext, onThrow, onReturn) {\n return this._subject.subscribe({ next: onNext, error: onThrow, complete: onReturn });\n }", "subscribe(onNext, onThrow, onReturn) {\n return this._subject.subscribe({ next: onNext, error: onThrow, complete: onReturn });\n }", "subscribe(onNext, onThrow, onReturn) {\n return this._subject.subscribe({ next: onNext, error: onThrow, complete: onReturn });\n }", "subscribe(onNext, onThrow, onReturn) {\n return this._subject.subscribe({ next: onNext, error: onThrow, complete: onReturn });\n }", "subscribe(onNext, onThrow, onReturn) {\n return this._subject.subscribe({ next: onNext, error: onThrow, complete: onReturn });\n }", "function createWithObservable() {\n return Object(__WEBPACK_IMPORTED_MODULE_1__streamingComponent__[\"a\" /* streamingComponent */])(props$ => props$.pipe(Object(__WEBPACK_IMPORTED_MODULE_0_rxjs_operators__[\"distinctUntilChanged\"])((props, prevProps) => props.observable === prevProps.observable), Object(__WEBPACK_IMPORTED_MODULE_0_rxjs_operators__[\"switchMap\"])(props => props.observable.pipe(Object(__WEBPACK_IMPORTED_MODULE_0_rxjs_operators__[\"map\"])(observableValue => props.children\n ? props.children(observableValue)\n : id(observableValue))))));\n}", "function ToasterService() {\n var _this = this;\n this.addToast = new rxjs.Observable(function (observer) { return _this._addToast = observer; }).pipe(operators.share());\n this.clearToasts = new rxjs.Observable(function (observer) { return _this._clearToasts = observer; }).pipe(operators.share());\n this._removeToastSubject = new rxjs.Subject();\n this.removeToast = this._removeToastSubject.pipe(operators.share());\n }", "get sourcePatientInfo () {\n\t\treturn this._sourcePatientInfo;\n\t}", "getdata() {\n return Observable.create((observer) => {\n socket.on('res', (data) => {\n observer.next(data);\n });\n });\n }", "subscribe(onNext, onThrow, onReturn) {\n return this._subject.subscribe({\n next: onNext,\n error: onThrow,\n complete: onReturn\n });\n }", "constructor() {\n makeAutoObservable(this);\n }", "constructor() {\n makeAutoObservable(this);\n }", "static async getAllPatients(req,res){\n const patients = await Collections.Patient\n .find() //to find all patients data\n .populate('assignDoctor', '-_id -__v')\n .populate({\n path : 'patientDrugDetail',\n populate: {\n path :'afternoon morning night',\n model : 'Medicines',\n select : '-_id -__v'\n }\n }) //to get detail about doctor assigne to patient\n .select('-_id -__v') //exclud id and version of data\n\n res.send(patients)\n }", "static getAllBusinesses$() {\n return Observable.create(async observer => {\n const collection = mongoDB.db.collection(CollectionName);\n const cursor = collection.find({});\n let obj = await this.extractNextFromMongoCursor(cursor);\n while (obj) {\n observer.next(obj);\n obj = await this.extractNextFromMongoCursor(cursor);\n }\n\n observer.complete();\n });\n }", "function Subject() {\n this.observers = [];\n}", "function init() {\r\n self.patients = App.models.patients.getPatients();\r\n }", "function ObservableList(){\n BaseModel.call(this, [], null);\n}", "function ToasterService() {\r\n var _this = this;\r\n this.addToast = new rxjs__WEBPACK_IMPORTED_MODULE_1__[\"Observable\"](function (observer) { return _this._addToast = observer; }).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"share\"])());\r\n this.clearToasts = new rxjs__WEBPACK_IMPORTED_MODULE_1__[\"Observable\"](function (observer) { return _this._clearToasts = observer; }).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"share\"])());\r\n this._removeToastSubject = new rxjs__WEBPACK_IMPORTED_MODULE_1__[\"Subject\"]();\r\n this.removeToast = this._removeToastSubject.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"share\"])());\r\n }", "constructor() {\n makeAutoObservable(this);\n }", "get records() {\n return this[_RECORDS];\n }", "get(options) {\n return Object(rxjs__WEBPACK_IMPORTED_MODULE_1__[\"from\"])(this.query.get(options)).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"observeOn\"])(this.afs.schedulers.insideAngular));\n }", "get(options) {\n return Object(rxjs__WEBPACK_IMPORTED_MODULE_1__[\"from\"])(this.query.get(options)).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"observeOn\"])(this.afs.schedulers.insideAngular));\n }", "function ToasterService() {\r\n\t var _this = this;\r\n\t this.addToast = new Observable_1.Observable(function (observer) { return _this._addToast = observer; }).share();\r\n\t this.clearToasts = new Observable_1.Observable(function (observer) { return _this._clearToasts = observer; }).share();\r\n\t this._removeToastSubject = new Subject_1.Subject();\r\n\t this.removeToast = this._removeToastSubject.share();\r\n\t }", "get_all_patient_info() {\n return this.pool.getConnection().then(connection => {\n var res = connection.query(patient_sql.get_all_patient_info_sql);\n connection.release();\n return res;\n });\n\n }", "portList() {\n try {\n this._userService.getregistryList()\n .pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_11__[\"first\"])())\n .subscribe((res) => {\n this.filteredPortListRes = res;\n if (this.filteredPortListRes.success === true) {\n this.filteredPortData = this.filteredPortListRes.data;\n }\n }, err => {\n console.log(err);\n });\n }\n catch (err) {\n console.log(err);\n }\n }", "portList() {\n try {\n this._userService.getregistryList()\n .pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_11__[\"first\"])())\n .subscribe((res) => {\n this.filteredPortListRes = res;\n if (this.filteredPortListRes.success === true) {\n this.filteredPortData = this.filteredPortListRes.data;\n }\n }, err => {\n console.log(err);\n });\n }\n catch (err) {\n console.log(err);\n }\n }", "subscribe () {}", "data() {\n return Session.get('patient')\n }", "function Subject(){\n this.observers = new ObserverList();\n}", "function BaseObservable() {}", "get(options) {\n return Object(rxjs__WEBPACK_IMPORTED_MODULE_1__[\"from\"])(this.ref.get(options)).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"observeOn\"])(this.afs.schedulers.insideAngular));\n }", "listen(name) {\n if (!this._observables[name]) {\n this._subjects[name] = new rxjs__WEBPACK_IMPORTED_MODULE_3__[\"BehaviorSubject\"](null);\n this._observables[name] = this._subjects[name].asObservable();\n }\n return this._observables[name];\n }", "get update() {\n return this.updateSubject.asObservable();\n }", "allNotes() {\n return this.notes;\n }", "function andObservables(observables) {\n return observables.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__[\"mergeAll\"])(), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__[\"every\"])(function (result) { return result === true; }));\n}", "function AsyncSubject() {\n\t __super__.call(this, subscribe);\n\n\t this.isDisposed = false;\n\t this.isStopped = false;\n\t this.hasValue = false;\n\t this.observers = [];\n\t this.hasError = false;\n\t }", "function AsyncSubject() {\n\t __super__.call(this, subscribe);\n\n\t this.isDisposed = false;\n\t this.isStopped = false;\n\t this.hasValue = false;\n\t this.observers = [];\n\t this.hasError = false;\n\t }", "function AsyncSubject() {\n\t __super__.call(this, subscribe);\n\n\t this.isDisposed = false;\n\t this.isStopped = false;\n\t this.hasValue = false;\n\t this.observers = [];\n\t this.hasError = false;\n\t }", "function AsyncSubject() {\n\t __super__.call(this, subscribe);\n\n\t this.isDisposed = false;\n\t this.isStopped = false;\n\t this.hasValue = false;\n\t this.observers = [];\n\t this.hasError = false;\n\t }", "getAllSpeakers() {\n return speakers;\n }", "subscribe() {}", "getData() {\n return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__[\"of\"])(_static_data_aio_table_data__WEBPACK_IMPORTED_MODULE_8__[\"aioTableData\"].map(customer => new _interfaces_customer_model__WEBPACK_IMPORTED_MODULE_4__[\"Customer\"](customer)));\n }", "function AsyncSubject() {\n __super__.call(this, subscribe);\n\n this.isDisposed = false;\n this.isStopped = false;\n this.hasValue = false;\n this.observers = [];\n this.hasError = false;\n }", "function AsyncSubject() {\n __super__.call(this, subscribe);\n\n this.isDisposed = false;\n this.isStopped = false;\n this.hasValue = false;\n this.observers = [];\n this.hasError = false;\n }", "function load(participants$) {\n //participants$.subscribe(participants => {}\n }", "function tokenStream() {\n\n return Observable.from(TOKENS);\n}", "auditTrail(events) {\n return this.stateChanges(events).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"scan\"])((current, action) => [...current, ...action], []));\n }", "auditTrail(events) {\n return this.stateChanges(events).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"scan\"])((current, action) => [...current, ...action], []));\n }", "disableObservablesArray() {\n this.subscriptionsArray.unsubscribe();\n this.subscriptionsArray = null;\n }", "get initialized$() {\n return this.initializedSubject.asObservable();\n }", "function SpeakersListViewModel() {\n\n let observableSpeakerModel = {\n isLoading: false,\n\n uniqueSpeakers: [], //array of unique speaker names\n\n speakers: new ObservableArray([]), //array of all speakers objects \n \n loadSpeakers : function () {\n \n this.set(\"isLoading\", true);\n\n console.log(\"Start loading speakers\");\n\n file.readText()\n .then(function (content) {\n var data = JSON.parse(content); \n\n //we are creating the list of speakers, so empty the existing ones first\n viewModel.empty();\n\n //loop thru the sessions file (our database) and extract all unique speakers into the unique speakers array list\n data.forEach(function(sessionObj) { \n \n let firstName = sessionObj.firstName;\n let lastName = sessionObj.lastName;\n\n //we are using the variable fullName as the unique key in the uniqueSpeakers array list\n let fullName = firstName + ' ' + lastName;\n\n //search for the fullname in the uniqueSpeakers array list\n var fullNameFound = false; \n for (var i = 0; i < viewModel.uniqueSpeakers.length; i++) {\n if (viewModel.uniqueSpeakers[i] == fullName) {\n fullNameFound = true;\n //console.log(fullName + ' is already in the unique speakers list.'); \n break;\n }\n } \n\n if (!fullNameFound) {\n //console.log('Found unique speaker ' + fullName);\n\n //add the speaker to the unique speaker array list\n viewModel.uniqueSpeakers.push(fullName);\n\n //add the unique speaker to the speaker object for the view model\n viewModel.speakers.push({\n \"firstName\" : firstName,\n \"lastName\" : lastName,\n \"fullName\" : fullName\n });\n }\n\n\n });\n\n // sort the speaker names in ascending order\n sortSpeakerNames(viewModel.speakers);\n\n console.log(\"Finished loading speakers\");\n\n viewModel.set(\"isLoading\", false); //set loading to false after loading speakers\n\n }), function (error) {\n alert(\"Error. Please check your network connection.\")\n };\n }, \n\n empty: function () {\n console.log('Emptying list of speakers');\n console.log('Before emptying list: size is ' + this.speakers.length);\n while (this.speakers.length) {\n this.speakers.pop();\n }\n console.log('After emptying list: size is ' + this.speakers.length);\n }\n\n }\n\n var viewModel = observableModule.fromObject(observableSpeakerModel);\n\n return viewModel; //returns viewModel object containing speakers data \n}", "function getData() {\n let beers = [\n {name: \"Sam Adams\", country: \"USA\", price: 8.50},\n {name: \"Bud Light\", country: \"USA\", price: 6.50},\n {name: \"Brooklyn Lager\", country: \"USA\", price: 8.00},\n {name: \"Sapporo\", country: \"Japan\", price: 7.50}\n ];\n\n return Observable.create(observer =>\n {\n let counter = 0;\n beers.forEach(b =>\n {\n observer.next(b);\n counter++;\n\n if (counter > Math.random()*5) {\n observer.error({\n status: 500,\n description: \"Beer stream error\"\n });\n }\n });\n\n // We never got here in case of the error.\n // GOTCHA: In this demo forEach() method in line 17 actually calls next() for every item in \"beers\".\n // Try to comment the line #50 to see this in action.\n observer.complete();\n });\n}", "function AsyncSubject() {\n __super__.call(this);\n this.isDisposed = false;\n this.isStopped = false;\n this.hasValue = false;\n this.observers = [];\n this.hasError = false;\n }", "function AsyncSubject() {\n __super__.call(this);\n this.isDisposed = false;\n this.isStopped = false;\n this.hasValue = false;\n this.observers = [];\n this.hasError = false;\n }", "function AsyncSubject() {\n __super__.call(this);\n this.isDisposed = false;\n this.isStopped = false;\n this.hasValue = false;\n this.observers = [];\n this.hasError = false;\n }", "function AsyncSubject() {\n __super__.call(this);\n this.isDisposed = false;\n this.isStopped = false;\n this.hasValue = false;\n this.observers = [];\n this.hasError = false;\n }", "function AsyncSubject() {\n __super__.call(this);\n this.isDisposed = false;\n this.isStopped = false;\n this.hasValue = false;\n this.observers = [];\n this.hasError = false;\n }", "function AsyncSubject() {\n __super__.call(this);\n this.isDisposed = false;\n this.isStopped = false;\n this.hasValue = false;\n this.observers = [];\n this.hasError = false;\n }", "function AsyncSubject() {\n\t __super__.call(this);\n\t this.isDisposed = false;\n\t this.isStopped = false;\n\t this.hasValue = false;\n\t this.observers = [];\n\t this.hasError = false;\n\t }", "function observable(source, convertNested) {\n if (convertNested === void 0) { convertNested = true; }\n // Check\n if (xp.isNotifier(source)) {\n throw new Error('Source object is already observable.');\n }\n if (!(typeof source === 'object')) {\n throw new Error('Source must be an object.');\n }\n else if (source instanceof Date) {\n throw new Error('Dates cannot be converted into an observable.');\n }\n // Return\n if (Array.isArray(source)) {\n return new xp.ObservableCollection(source, convertNested);\n }\n else {\n return new xp.ObservableObject(source, convertNested);\n }\n }", "function SanityObservableMinimal() {\n Observable.apply(this, arguments); // eslint-disable-line prefer-rest-params\n}", "function SanityObservableMinimal() {\n Observable.apply(this, arguments); // eslint-disable-line prefer-rest-params\n}", "getAllJournals () {\n\t\t\tthis.$axios.get('/api/JournalContrlr').then(res => {\n\t\t\t\tthis.allJournals = res.data\n\t\t\t});\n\t\t}", "get objects() {\n return this._objects\n }", "function refreshDevices(){\n\tsensors= temper.getDevices().map( _temperPromise)\n\treturn sensors\n}", "getAllUsers() {\r\n return this.users;\r\n }", "function SanityObservableMinimal() {\n Observable.apply(this, arguments) // eslint-disable-line prefer-rest-params\n}", "function getAllAppointments() {\n console.log('client request to server for all appointments');\n vm.navBar.updateCurrentNavItem('all');\n $http.get('/appointments/all').then(function(response) {\n vm.allAppointments.array = response.data;\n console.log(vm.allAppointments.array);\n });\n }", "makeSubscriptions() {\n\t\tthis.subscribing = this.tx.makeSubscriptions([\n\n\t\t\t// Subscribe to broadcast events\n\t\t\t{ cmd: P.PACKET_EVENT, nodeID: this.nodeID },\n\n\t\t\t// Subscribe to requests\n\t\t\t{ cmd: P.PACKET_REQUEST, nodeID: this.nodeID },\n\n\t\t\t// Subscribe to node responses of requests\n\t\t\t{ cmd: P.PACKET_RESPONSE, nodeID: this.nodeID },\n\n\t\t\t// Discover handler\n\t\t\t{ cmd: P.PACKET_DISCOVER },\n\t\t\t{ cmd: P.PACKET_DISCOVER, nodeID: this.nodeID },\n\n\t\t\t// NodeInfo handler\n\t\t\t{ cmd: P.PACKET_INFO }, // Broadcasted INFO. If a new node connected\n\t\t\t{ cmd: P.PACKET_INFO, nodeID: this.nodeID }, // Response INFO to DISCOVER packet\n\n\t\t\t// Disconnect handler\n\t\t\t{ cmd: P.PACKET_DISCONNECT },\n\n\t\t\t// Heartbeat handler\n\t\t\t{ cmd: P.PACKET_HEARTBEAT },\n\n\t\t\t// Ping handler\n\t\t\t{ cmd: P.PACKET_PING }, // Broadcasted\n\t\t\t{ cmd: P.PACKET_PING, nodeID: this.nodeID }, // Targeted\n\n\t\t\t// Pong handler\n\t\t\t{ cmd: P.PACKET_PONG, nodeID: this.nodeID }\n\n\t\t]).then(() => {\n\t\t\tthis.subscribing = null;\n\t\t});\n\n\t\treturn this.subscribing;\n\t}", "function getSubscriptions(){\n\t\t\treturn subscriptions;\n\t\t}", "function Emitter() {\n this._subscriptions = [];\n}", "getAuctionItems() {\r\n return this._httpClient.get(this.getUrl + \"/auctionItems\").pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_0__[\"map\"])(response => response));\r\n }", "customers() {\n return this.deliveries().map(delivery => {\n return delivery.customer();\n });\n }", "function Patient(name, code) {\n this.name = name;\n this.code = code;\n}", "loadTiposUtilizador() {\n return this.tipoUtilizadorService.GetTiposUtilizador().subscribe((data) => {\n this.tipoUtilizadorList = data;\n });\n }", "getEvents(){\n return this.events.slice();\n }", "connect() {\n // Combine everything that affects the rendered data into one update\n // stream for the data-table to consume.\n const dataMutations = [\n Object(rxjs__WEBPACK_IMPORTED_MODULE_2__[\"of\"])(this.data),\n this.paginator.page,\n this.sort.sortChange\n ];\n return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__[\"merge\"])(...dataMutations).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_1__[\"map\"])(() => {\n return this.getPagedData(this.getSortedData([...this.data]));\n }));\n }", "function toObservable(source, options) {\n !options?.injector && assertInInjectionContext(toObservable);\n const injector = options?.injector ?? inject(Injector);\n const subject = new ReplaySubject(1);\n const watcher = effect(() => {\n let value;\n try {\n value = source();\n }\n catch (err) {\n untracked(() => subject.error(err));\n return;\n }\n untracked(() => subject.next(value));\n }, { injector, manualCleanup: true });\n injector.get(DestroyRef).onDestroy(() => {\n watcher.destroy();\n subject.complete();\n });\n return subject.asObservable();\n}", "async getTreatments() {\n if(this.UserType !== \"Patient\")\n throw new Error(\"Only patients can have treatments\");\n\n let user = await this.getUserByCert(true);\n\n return user.treatments;\n }", "ngOnInit() {\n const loading$ = this.store.select(_user_selectors__WEBPACK_IMPORTED_MODULE_2__[\"getLoading\"]);\n const loaded$ = this.store.select(_user_selectors__WEBPACK_IMPORTED_MODULE_2__[\"getLoaded\"]);\n Object(rxjs__WEBPACK_IMPORTED_MODULE_3__[\"combineLatest\"])([loading$, loaded$]).subscribe(data => {\n if (!data[0] && !data[1]) {\n this.store.dispatch(new _user_actions__WEBPACK_IMPORTED_MODULE_1__[\"LoadUsers\"]()); //action dispatch\n }\n });\n this.store.pipe(Object(_ngrx_store__WEBPACK_IMPORTED_MODULE_0__[\"select\"])(_user_selectors__WEBPACK_IMPORTED_MODULE_2__[\"getUser\"])).subscribe(data => {\n this.data = data;\n });\n }", "statusList() {\n try {\n this._userService.getstatusList()\n .pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_11__[\"first\"])())\n .subscribe((res) => {\n this.statusListRes = res;\n if (this.statusListRes.success === true) {\n this.statusListData = this.statusListRes.data;\n console.log(this.statusListData);\n }\n }, err => {\n console.log(err);\n });\n }\n catch (err) {\n console.log(err);\n }\n }", "function Patient(nickName, firstName) {\n this.nickName = nickName;\n this.firstName = firstName;\n}", "notify() {\n console.log('Subject1: notifying observers...');\n this.#observers.forEach((observer) => {\n observer.update(this);\n });\n }" ]
[ "0.69550824", "0.61484927", "0.5973468", "0.583888", "0.5726242", "0.56862605", "0.56724006", "0.5556667", "0.541952", "0.5415404", "0.53977174", "0.52335817", "0.51911044", "0.518723", "0.51717466", "0.51546496", "0.5144299", "0.514183", "0.514183", "0.514183", "0.514183", "0.514183", "0.51257247", "0.51222277", "0.51146716", "0.5099768", "0.5085474", "0.5066642", "0.5066642", "0.5054448", "0.50484294", "0.50315535", "0.5008759", "0.49999198", "0.499303", "0.4970156", "0.49307242", "0.4916888", "0.4916888", "0.49070147", "0.4892441", "0.48666063", "0.48666063", "0.48340675", "0.48311335", "0.48249596", "0.4822538", "0.4799685", "0.47859806", "0.47855777", "0.47793943", "0.47733763", "0.476123", "0.476123", "0.476123", "0.476123", "0.4754225", "0.47334057", "0.4730582", "0.47094443", "0.47094443", "0.47051513", "0.47041637", "0.47010517", "0.47010517", "0.46969116", "0.46849602", "0.46766078", "0.4656306", "0.4653329", "0.46450353", "0.46450353", "0.46450353", "0.46450353", "0.46450353", "0.4640889", "0.46383387", "0.46253535", "0.46253535", "0.46196622", "0.46167287", "0.46073535", "0.46068245", "0.4606552", "0.46058518", "0.460075", "0.4597593", "0.45874327", "0.4572725", "0.4572522", "0.45674422", "0.4564775", "0.4561524", "0.45541346", "0.45418116", "0.45416674", "0.45325422", "0.45316958", "0.45159683", "0.4511488" ]
0.6391625
1
Pagination properties getter and setter
get startIndex() { return asObservable_1.asObservable(this._startIndex); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "get pageSize() { return this._pageSize; }", "get currentPagination() {\n return this._currentPagination;\n }", "get pageSizeOptions() { return this._pageSizeOptions; }", "get paginator() { return this._paginator; }", "function Pagination(props) {\r\n var _this = _super.call(this, props) || this;\r\n _this.state = {\r\n pages: _this.calculatePagination()\r\n };\r\n return _this;\r\n }", "get currentPage() { return this._currentPage; }", "SET_PAGINATION(state, data) {\n state.pagination = data;\n }", "function initPagination() {\n ctrl.page = {\n number: ctrl.page.number || 0,\n size: 10\n };\n }", "pagination() {\n //Convert the data into Int using parseInt(string, base value)\n // || 1 is used in case user does not specify any page value similarly for limit default is 10\n const page = parseInt(this.queryStr.page, 10) || 1;\n const limit = parseInt(this.queryStr.limit, 10) || 10;\n // to get the data on pages rather than page 1\n const skipResults = (page - 1) * limit;\n\n //skip method is used to skip through the specified number of data\n //limit method is used to limit the no of data returned at a time.\n this.query = this.query.skip(skipResults).limit(limit);\n\n return this;\n }", "initPagination(){\n this.getPagination().initPagination();\n }", "setTotalPages(page){\n this.page=page;\n }", "currentPageNumber() {\n return this.paginator.currentPage\n }", "set Page(value) {\n currentPage = value;\n }", "currentPage() {\n let page = this.paginator.getPage()\n return page\n }", "get pageIndex() { return this._pageIndex; }", "get get_pages () {\n\n return this._pages;\n\n }", "getCurrentPagination() {\n return this._currentPagination;\n }", "getCurrentPagination() {\n return this._currentPagination;\n }", "getCurrentPagination() {\n return this._currentPagination;\n }", "function _pagination_setPageData() {\r\n var _pagination = _data['pagination'];\r\n\r\n var _startIdx = _pagination['currentPage'] * _pagination['numElementsPerPage'];\r\n\r\n _pagination['current']['elyos'].empty().pushAll(_data['elyos'].slice(_startIdx, _startIdx + _pagination['numElementsPerPage']));\r\n _pagination['current']['asmodians'].empty().pushAll(_data['asmodians'].slice(_startIdx, _startIdx + _pagination['numElementsPerPage']));\r\n _pagination['current']['versus'].empty().pushAll(_data['versus'].slice(_startIdx, _startIdx + _pagination['numElementsPerPage']));\r\n }", "function setPaginatedProperty(default_value, property, value){\t\n\tsetViewLevelProperty('paginatedProperties', default_value, property, value); \n}", "getPageSize() {\n return this.paginator.pageSize\n }", "getLimitAndOffsetByPageAndContentPerPage() {\n const offset = this.currentPage() * this.perPage() - this.perPage();\n const limit = this.perPage();\n\n return {\n offset,\n limit,\n };\n }", "getPaginas() {\n return this.paginaDados;\n }", "_applyPagination() {\n let page = Math.ceil(this.page / this.maxSize) - 1;\n let start = page * this.maxSize;\n let end = start + this.maxSize;\n return [start, end];\n }", "function Paginator() {\n var self = this;\n this._products = {};\n this.ppp = $.var.hashParser.get(\"ppp\") | 30;\n this.products = [];\n this.pages = [[]];\n this.currentpage = 0;\n\n $(\"#itemsPerPage\").change(function(e) {\n var v = parseInt(e.currentTarget.value);\n $(e).blur();\n // eslint-disable-next-line\n if (v !== v) {\n self.setPPP(\"all\");\n } else {\n self.setPPP(v);\n }\n self.parse(self._products);\n });\n}", "setPages(page){\n this.page=page;\n }", "resetPaginationOptions() {\n let paginationOptions;\n if (this.options && this.options.isWithCursor) {\n // first, last, after, before\n paginationOptions = {\n after: '',\n before: undefined,\n last: undefined\n };\n }\n else {\n // first, last, offset\n paginationOptions = ((this.options && this.options.paginationOptions) || this.getInitPaginationOptions());\n paginationOptions.offset = 0;\n }\n // save current pagination as Page 1 and page size as \"first\" set size\n this._currentPagination = {\n pageNumber: 1,\n pageSize: paginationOptions.first || DEFAULT_PAGE_SIZE,\n };\n this.updateOptions({ paginationOptions });\n }", "getInitPaginationOptions() {\n const paginationFirst = this.pagination ? this.pagination.pageSize : DEFAULT_ITEMS_PER_PAGE;\n return (this.options && this.options.isWithCursor) ? { first: paginationFirst } : { first: paginationFirst, offset: 0 };\n }", "function _currentPageData() {\n let first = rows.length > 0 ? (currentPage - 1) * rowsPerPage + 1 : 0;\n let last = rows.length < rowsPerPage ? totalItems : (currentPage - 1) * rowsPerPage + rowsPerPage;\n \n return {\n first,\n last,\n current:currentPage,\n totalItems,\n } \n }", "updatePagination() {\n this._checkPaginationEnabled();\n this._checkScrollingControls();\n this._updateTabScrollPosition();\n }", "get pages() {\n return { ...this._pages\n };\n }", "updatePagination() {\n\t\tlet next_page = this.current_page+1;\n\t\tlet next_next_page = next_page+1;\n\t\tgetComponentElementById(this,\"PaginationCurrentItem\").html('<span class=\"page-link\">'+this.current_page+'</span>');\n\t\tgetComponentElementById(this,\"PaginationNextItem\").html('<span class=\"page-link\">'+next_page+'</span>');\n\t\tgetComponentElementById(this,\"PaginationNextNextItem\").html('<span class=\"page-link\">'+next_next_page+'</span>');\n\t\tgetComponentElementById(this,\"ResultCountWrapper\").html('<span class=\"badge float-right\">Total: '+this.total_items+'</span>');\n\t}", "@readOnly\n @computed('pageNumber', '_pageNumber', 'valuesTotal', 'values.length')\n computedPageNumber: function (pageNumber, _pageNumber, valuesTotal) {\n if (pageNumber !== null) {\n return pageNumber\n }\n return _pageNumber\n }", "handlePaging() {\n if (!this.settings.paging) {\n return;\n }\n\n this.element.addClass('paginated');\n this.tableBody.pager({\n componentAPI: this,\n dataset: this.settings.dataset,\n hideOnOnePage: this.settings.hidePagerOnOnePage,\n source: this.settings.source,\n pagesize: this.settings.pagesize,\n indeterminate: this.settings.indeterminate,\n rowTemplate: this.settings.rowTemplate,\n pagesizes: this.settings.pagesizes,\n pageSizeSelectorText: this.settings.groupable ? 'GroupsPerPage' : 'RecordsPerPage',\n showPageSizeSelector: this.settings.showPageSizeSelector,\n activePage: this.restoreActivePage ? parseInt(this.savedActivePage, 10) : 1\n });\n\n if (this.restoreActivePage) {\n this.savedActivePage = null;\n this.restoreActivePage = false;\n }\n }", "set currentPagination(currentPagination) {\n this._currentPagination = currentPagination;\n }", "function Paginator(per_page, length) {\n // You really should be calling this with `new Paginator`, but WHATEVER.\n if (!(this instanceof Paginator)) {\n return new Paginator(per_page, length);\n }\n\n // Woo, defaults!\n this.per_page = per_page || 25;\n this.length = length || 10;\n}", "function Pagination( element, options ){\n /** the total number of pages */\n this.numPages = null;\n /** the current, active page */\n\t\tthis.currPage = 0;\n\t\treturn this.init( element, options );\n }", "function paginationService() {\n\n var instances = {};\n var lastRegisteredInstance;\n\n this.registerInstance = function(instanceId) {\n if (typeof instances[instanceId] === 'undefined') {\n instances[instanceId] = {\n asyncMode: false\n };\n lastRegisteredInstance = instanceId;\n }\n };\n\n this.deregisterInstance = function(instanceId) {\n delete instances[instanceId];\n };\n \n this.isRegistered = function(instanceId) {\n return (typeof instances[instanceId] !== 'undefined');\n };\n\n this.getLastInstanceId = function() {\n return lastRegisteredInstance;\n };\n\n this.setCurrentPageParser = function(instanceId, val, scope) {\n instances[instanceId].currentPageParser = val;\n instances[instanceId].context = scope;\n };\n this.setCurrentPage = function(instanceId, val) {\n instances[instanceId].currentPageParser.assign(instances[instanceId].context, val);\n };\n this.getCurrentPage = function(instanceId) {\n var parser = instances[instanceId].currentPageParser;\n return parser ? parser(instances[instanceId].context) : 1;\n };\n\n this.setItemsPerPage = function(instanceId, val) {\n instances[instanceId].itemsPerPage = val;\n };\n this.getItemsPerPage = function(instanceId) {\n return instances[instanceId].itemsPerPage;\n };\n\n this.setCollectionLength = function(instanceId, val) {\n instances[instanceId].collectionLength = val;\n };\n this.getCollectionLength = function(instanceId) {\n return instances[instanceId].collectionLength;\n };\n\n this.setAsyncModeTrue = function(instanceId) {\n instances[instanceId].asyncMode = true;\n };\n\n this.setAsyncModeFalse = function(instanceId) {\n instances[instanceId].asyncMode = false;\n };\n\n this.isAsyncMode = function(instanceId) {\n return instances[instanceId].asyncMode;\n };\n }", "function paginationService() {\n\n var instances = {};\n var lastRegisteredInstance;\n\n this.registerInstance = function(instanceId) {\n if (typeof instances[instanceId] === 'undefined') {\n instances[instanceId] = {\n asyncMode: false\n };\n lastRegisteredInstance = instanceId;\n }\n };\n\n this.deregisterInstance = function(instanceId) {\n delete instances[instanceId];\n };\n \n this.isRegistered = function(instanceId) {\n return (typeof instances[instanceId] !== 'undefined');\n };\n\n this.getLastInstanceId = function() {\n return lastRegisteredInstance;\n };\n\n this.setCurrentPageParser = function(instanceId, val, scope) {\n instances[instanceId].currentPageParser = val;\n instances[instanceId].context = scope;\n };\n this.setCurrentPage = function(instanceId, val) {\n instances[instanceId].currentPageParser.assign(instances[instanceId].context, val);\n };\n this.getCurrentPage = function(instanceId) {\n var parser = instances[instanceId].currentPageParser;\n return parser ? parser(instances[instanceId].context) : 1;\n };\n\n this.setItemsPerPage = function(instanceId, val) {\n instances[instanceId].itemsPerPage = val;\n };\n this.getItemsPerPage = function(instanceId) {\n return instances[instanceId].itemsPerPage;\n };\n\n this.setCollectionLength = function(instanceId, val) {\n instances[instanceId].collectionLength = val;\n };\n this.getCollectionLength = function(instanceId) {\n return instances[instanceId].collectionLength;\n };\n\n this.setAsyncModeTrue = function(instanceId) {\n instances[instanceId].asyncMode = true;\n };\n\n this.setAsyncModeFalse = function(instanceId) {\n instances[instanceId].asyncMode = false;\n };\n\n this.isAsyncMode = function(instanceId) {\n return instances[instanceId].asyncMode;\n };\n }", "function Paginator(per_page, length) {\n // You really should be calling this with `new Paginator`, but WHATEVER.\n if (!(this instanceof Paginator)) {\n return new Paginator(per_page, length);\n }\n\n // Woo, defaults!\n this.per_page = per_page || 25;\n this.length = length || 10;\n}", "function getPages() {\r\n\treturn pages;\r\n}", "function paginationService() {\n\n var instances = {};\n var lastRegisteredInstance;\n\n this.registerInstance = function(instanceId) {\n if (typeof instances[instanceId] === 'undefined') {\n instances[instanceId] = {\n asyncMode: false\n };\n lastRegisteredInstance = instanceId;\n }\n };\n\n this.deregisterInstance = function(instanceId) {\n delete instances[instanceId];\n };\n\n this.isRegistered = function(instanceId) {\n return (typeof instances[instanceId] !== 'undefined');\n };\n\n this.getLastInstanceId = function() {\n return lastRegisteredInstance;\n };\n\n this.setCurrentPageParser = function(instanceId, val, scope) {\n instances[instanceId].currentPageParser = val;\n instances[instanceId].context = scope;\n };\n this.setCurrentPage = function(instanceId, val) {\n instances[instanceId].currentPageParser.assign(instances[instanceId].context, val);\n };\n this.getCurrentPage = function(instanceId) {\n var parser = instances[instanceId].currentPageParser;\n return parser ? parser(instances[instanceId].context) : 1;\n };\n\n this.setItemsPerPage = function(instanceId, val) {\n instances[instanceId].itemsPerPage = val;\n };\n this.getItemsPerPage = function(instanceId) {\n return instances[instanceId].itemsPerPage;\n };\n\n this.setCollectionLength = function(instanceId, val) {\n instances[instanceId].collectionLength = val;\n };\n this.getCollectionLength = function(instanceId) {\n return instances[instanceId].collectionLength;\n };\n\n this.setAsyncModeTrue = function(instanceId) {\n instances[instanceId].asyncMode = true;\n };\n\n this.setAsyncModeFalse = function(instanceId) {\n instances[instanceId].asyncMode = false;\n };\n\n this.isAsyncMode = function(instanceId) {\n return instances[instanceId].asyncMode;\n };\n }", "function paginationService() {\n\n var instances = {};\n var lastRegisteredInstance;\n\n this.registerInstance = function(instanceId) {\n if (typeof instances[instanceId] === 'undefined') {\n instances[instanceId] = {\n asyncMode: false\n };\n lastRegisteredInstance = instanceId;\n }\n };\n\n this.isRegistered = function(instanceId) {\n return (typeof instances[instanceId] !== 'undefined');\n };\n\n this.getLastInstanceId = function() {\n return lastRegisteredInstance;\n };\n\n this.setCurrentPageParser = function(instanceId, val, scope) {\n instances[instanceId].currentPageParser = val;\n instances[instanceId].context = scope;\n };\n this.setCurrentPage = function(instanceId, val) {\n instances[instanceId].currentPageParser.assign(instances[instanceId].context, val);\n };\n this.getCurrentPage = function(instanceId) {\n var parser = instances[instanceId].currentPageParser;\n return parser ? parser(instances[instanceId].context) : 1;\n };\n\n this.setItemsPerPage = function(instanceId, val) {\n instances[instanceId].itemsPerPage = val;\n };\n this.getItemsPerPage = function(instanceId) {\n return instances[instanceId].itemsPerPage;\n };\n\n this.setCollectionLength = function(instanceId, val) {\n instances[instanceId].collectionLength = val;\n };\n this.getCollectionLength = function(instanceId) {\n return instances[instanceId].collectionLength;\n };\n\n this.setAsyncModeTrue = function(instanceId) {\n instances[instanceId].asyncMode = true;\n };\n\n this.isAsyncMode = function(instanceId) {\n return instances[instanceId].asyncMode;\n };\n }", "function paginationService() {\n\n var instances = {};\n var lastRegisteredInstance;\n\n this.registerInstance = function(instanceId) {\n if (typeof instances[instanceId] === 'undefined') {\n instances[instanceId] = {\n asyncMode: false\n };\n lastRegisteredInstance = instanceId;\n }\n };\n\n this.isRegistered = function(instanceId) {\n return (typeof instances[instanceId] !== 'undefined');\n };\n\n this.getLastInstanceId = function() {\n return lastRegisteredInstance;\n };\n\n this.setCurrentPageParser = function(instanceId, val, scope) {\n instances[instanceId].currentPageParser = val;\n instances[instanceId].context = scope;\n };\n this.setCurrentPage = function(instanceId, val) {\n instances[instanceId].currentPageParser.assign(instances[instanceId].context, val);\n };\n this.getCurrentPage = function(instanceId) {\n var parser = instances[instanceId].currentPageParser;\n return parser ? parser(instances[instanceId].context) : 1;\n };\n\n this.setItemsPerPage = function(instanceId, val) {\n instances[instanceId].itemsPerPage = val;\n };\n this.getItemsPerPage = function(instanceId) {\n return instances[instanceId].itemsPerPage;\n };\n\n this.setCollectionLength = function(instanceId, val) {\n instances[instanceId].collectionLength = val;\n };\n this.getCollectionLength = function(instanceId) {\n return instances[instanceId].collectionLength;\n };\n\n this.setAsyncModeTrue = function(instanceId) {\n instances[instanceId].asyncMode = true;\n };\n\n this.isAsyncMode = function(instanceId) {\n return instances[instanceId].asyncMode;\n };\n }", "updatePagination(newPage, pageSize) {\n this._currentPagination = {\n pageNumber: newPage,\n pageSize,\n };\n let paginationOptions;\n if (this.options && this.options.isWithCursor) {\n paginationOptions = {\n first: pageSize\n };\n }\n else {\n paginationOptions = {\n first: pageSize,\n offset: (newPage > 1) ? ((newPage - 1) * pageSize) : 0 // recalculate offset but make sure the result is always over 0\n };\n }\n // unless user specifically set \"enablePagination\" to False, we'll update pagination options in every other cases\n if (this._gridOptions && (this._gridOptions.enablePagination || !this._gridOptions.hasOwnProperty('enablePagination'))) {\n this.updateOptions({ paginationOptions });\n }\n }", "updatePagination(newPage, pageSize) {\n this._currentPagination = {\n pageNumber: newPage,\n pageSize,\n };\n // unless user specifically set \"enablePagination\" to False, we'll update pagination options in every other cases\n if (this._gridOptions && (this._gridOptions.enablePagination || !this._gridOptions.hasOwnProperty('enablePagination'))) {\n this._odataService.updateOptions({\n top: pageSize,\n skip: (newPage - 1) * pageSize\n });\n }\n }", "updatePagination(newPage, pageSize) {\n this._currentPagination = {\n pageNumber: newPage,\n pageSize,\n };\n // unless user specifically set \"enablePagination\" to False, we'll update pagination options in every other cases\n if (this._gridOptions && (this._gridOptions.enablePagination || !this._gridOptions.hasOwnProperty('enablePagination'))) {\n this._odataService.updateOptions({\n top: pageSize,\n skip: (newPage - 1) * pageSize\n });\n }\n }", "changePerPage(value) {\n this.perPage = value;\n if (this.page*value > this.data.meta.total) {\n this.page = Math.floor(this.data.meta.total / value) + 1;\n }\n this.fetch();\n }", "static get PAGE_ITEMS() {\n return 50;\n }", "function _paginator( offset ) {\n let arrayPages = [];\n let from = currentPage - offset;\n let to = from + (offset * 2);\n if(from < 1) from = 0;\n if(to >= totalPages) to = totalPages - 1;\n\n while(from <= to){\n arrayPages.push(from + 1);\n from ++;\n }\n return{\n backDisabled:currentPage <= 1 ? true : false,\n showFirstItem: currentPage > offset ? true : false,\n nextDisabled: currentPage >= totalPages ? true : false,\n showLastItem: currentPage < totalPages - offset - 1 ? true : false,\n items:arrayPages,\n totalPages,\n offset,\n totalItems\n }\n }", "paginate(){\n const { page, limit } = this.queryString; // extract page and limit from queryString\n // ex: /api/v1/tours?page=2&limit=10 ==> displaying page nb 2 with 10 documents max per page\n // in this case => 1-10: page 1, 11-20: page 2, 21-30: page 3 .....\n const pageNb = page * 1 || 1; // convert to number || page 1 by default -- we by default limit, if one day we have 1000 documents...\n const limitSet = limit * 1 || 100; // 100 documents limit by page by default\n const skipValue = (pageNb - 1) * limitSet;\n // query = query.skip(10).limit(10); // skip amount of results that will be skiped\n this.query = this.query.skip(skipValue).limit(limitSet);\n\n return this; // for chaining ! return the object\n }", "static get PAGE_ITEMS() {\n return 10;\n }", "function setPagination() {\n //recreated paging list\n $(\"div#current-data #pagination ul li\").detach();\n $(\"div#current-data #pagination ul\").append(\n \"<li id='firstPage' title='First'><a href='#' aria-label='First'><span aria-hidden='true'>&laquo;</span></a></li>\"+\n \"<li id='prevPage' title='Previous'><a href='#' aria-label='Previous'><span aria-hidden='true'>&lt;</span></a></li>\"\n );\n var startPageNo = Math.floor(currPageNo/pagePerLoad) * pagePerLoad + (currPageNo%pagePerLoad === 0 ? 0 : 1); //start page no of serial page on page selected\n var endPageNo = maxPage < (startPageNo + pagePerLoad) ? maxPage : (startPageNo + pagePerLoad -1); //end page no of serial page on page selected\n for(var idx = startPageNo; idx <= endPageNo; idx++) {\n $(\"div#current-data #pagination ul\").append(\n \"<li id='page\"+idx+\"'\"+(idx === currPageNo ? \" class='active' \" : \"\")+\"><a href='#'>\"+idx+\"</a></li>\"\n );\n }\n $(\"div#current-data #pagination ul\").append(\n \"<li id='nextPage' title='Next'><a href='#' aria-label='Next'><span aria-hidden='true'>&gt;</span></a></li>\"+\n \"<li id='lastPage' title='Last'><a href='#' aria-label='Last'><span aria-hidden='true'>&raquo;</span></a></li>\"\n );\n }", "getTotalPaginas() {\n return this.totalPaginas;\n }", "renderPagination() {\n if (!_.isEmpty(this.props.pageMeta)) {\n const lastRecord = this.props.pageMeta.current_items_count + this.props.pageMeta.offset;\n const firstRecord = this.props.pageMeta.offset + 1;\n const totalItemsCount = this.props.pageMeta.total_items_count;\n\n return (\n <div className=\"row\">\n <b> {firstRecord}-{lastRecord}/{totalItemsCount}</b> <br/>\n <nav aria-label=\"Page navigation example\">\n\n <ul className=\"pagination\">\n {this.renderFirstPaginationButton()}\n {this.props.pageMeta.has_prev_page &&\n (<li className=\"page-item\" data-toggle=\"tooltip\" data-placement=\"top\"\n title=\"Previous page\">\n <span className=\"page-link\"\n onClick={e => this.props.loadMore(this.props.location.pathname, this.props.pageMeta.prev_page_number, this.props.pageMeta.page_size)}>\n {this.props.pageMeta.prev_page_number}\n </span>\n </li>)}\n\n <li className=\"page-item active\">\n <a className=\"page-link page-ite\">\n {this.props.pageMeta.current_page_number}\n </a>\n </li>\n {this.props.pageMeta.has_next_page &&\n <li className=\"page-item\">\n <a className=\"page-link\"\n onClick={e => this.props.loadMore(this.props.location.pathname, this.props.pageMeta.next_page_number, this.props.pageMeta.requested_page_size)}>\n {this.props.pageMeta.next_page_number}\n </a>\n </li>}\n {this.renderLastPaginationButton()}\n </ul>\n </nav>\n </div>\n )\n }\n }", "onPageChange(page) {\n if (page == \"next\") {\n this.page = this.page + 1;\n } else if (page == \"prev\") {\n this.page = this.page - 1;\n } else {\n this.page = page;\n }\n if (this.page <= 0) {\n this.page = 1;\n }\n if (this.page > this.data.meta.last_page) {\n this.page = this.data.meta.last_page;\n }\n this.fetch();\n }", "function pageing() {\r\n opts.actualPage = $(\"#ddPaging\").val();\r\n bindDatasource();\r\n }", "pageCount() {\n return Math.round(this.itemCount() / this.itemsPerPage)\n }", "function PaginationHelper(collection, itemsPerPage){\n\n this.length= collection.length\n this.itemsPerPage= itemsPerPage;\n this.numberOfPages = collection.length/itemsPerPage\n\n\n }", "constructor(props) {\n super(props);\n const { itemsCount = null, pageLimit = 10, pageNeighbours = 0 } = props;\n this.pageLimit = typeof pageLimit === \"number\" ? pageLimit : 10;\n this.itemsCount = typeof itemsCount === \"number\" ? itemsCount : 0;\n // pageNeighbours can be: 0, 1 or 2\n this.pageNeighbours =\n typeof pageNeighbours === \"number\"\n ? Math.max(0, Math.min(pageNeighbours, 2))\n : 0;\n this.totalPages = Math.ceil(this.itemsCount / this.pageLimit);\n\n this.state = { currentPage: this.props.currentPage };\n }", "function setIndexes() {\n pageStartIndex = currentPage * itemsPerPage;\n pageEndIndex = pageStartIndex + itemsPerPage - 1;\n}", "get paginator() {\n if (this.pagination && this.props.globalSelector.orgIds.length > 0) {\n const pageCount = this.state.filterText !== '' ? this.state.filteredPageCount : this.state.pageCount;\n\n return (\n <Pagination\n handlePageClick={this.handlePageClick}\n pageCount={pageCount}\n currentPage={this.state.currentPage}\n />\n );\n }\n return false;\n }", "_createPages() {\n let self = this,\n size = Math.floor(self.get('queryCount') / self.get('pageSize')) + 1,\n range = Array(size),\n pagesArray = self.get('pagesArray');\n\n pagesArray.clear();\n let i = 1;\n for (i = 1; i <= range.length; i++) {\n var obj = Ember.Object.create({text: i, className: self.get('pageNumber') === i ? \"active\": \"\"});\n pagesArray.pushObject(obj);\n }\n }", "function pagination() {\r\n\t\t\t\t$scope.pageSize = $scope.shownoofrec;\r\n\t\t\t\t\r\n\t\t\t\t$scope.currentPage = 0;\r\n\t\t\t\t$scope.totalPages = 0;\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t$scope.nextDisabled = false;\r\n\t\t\t\t$scope.previousDisabled = true;\r\n\t\t\t\t\r\n\t\t\t\tif(self.Filtervehicles.length <= 10 ) {\r\n\t\t\t\t\t$scope.nextDisabled = true;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(self.Filtervehicles.length < 100) {\r\n\t\t\t\t\t$scope.totalnoof_records = self.Filtervehicles.length;\r\n\t\t\t\t\r\n\t\t\t\t} else {\r\n\t\t\t\t\tfindrecord_count();\r\n\t\t\t\t}\r\n\t\t\t}", "getPageCount() {\n return this.doc.pages.length;\n }", "function pagePagination(size){\n try{\n var optInit = {\n items_per_page: items_per_page,\n num_display_entries : items_per_page,\n prev_text: $(\"#previous\").val(),\n next_text: $(\"#next\").val(),\n callback: pageSelectCallback\n };\n $(\"#Pagination\").pagination(size, optInit);\n }catch (ex){\n }\n }", "function updatePagination () {\n ctrl.maxTabWidth = getMaxTabWidth();\n ctrl.shouldPaginate = shouldPaginate();\n }", "function PagingInfo(totalCount)\n {\n $scope.totalCount = totalCount;\n $scope.totalPage = Math.ceil( $scope.totalCount / $scope.pageRecord)\n $scope.totalOption=[{}];\n for(var i = 0 ;i< $scope.totalPage;i++)\n {\n $scope.totalOption[i]={size:i+1};\n }\n }", "function PagingInfo(totalCount)\n {\n $scope.totalCount = totalCount;\n $scope.totalPage = Math.ceil( $scope.totalCount / $scope.pageRecord)\n $scope.totalOption=[{}];\n for(var i = 0 ;i< $scope.totalPage;i++)\n {\n $scope.totalOption[i]={size:i+1};\n }\n }", "function updatePagination () {\n updatePagingWidth();\n ctrl.maxTabWidth = getMaxTabWidth();\n ctrl.shouldPaginate = shouldPaginate();\n }", "function updatePagination () {\n updatePagingWidth();\n ctrl.maxTabWidth = getMaxTabWidth();\n ctrl.shouldPaginate = shouldPaginate();\n }", "function C_Paginator()\n\t{\n\t\tvar $=this,\n\t\t\t_=null;\n\t\t\n\t\t\n\t\t$.object_dom___component\t\t\t\t=_;\n\t\t$.array_object_dom___navigation_item\t=[];\n\t\t\n\t\t$.object_dom___target\t\t\t\t\t=_;\n\t\t$.array_object_dom___target_item\t\t=[];\n\t\t\n\t\t$.integer___pages_amount\t\t\t\t=0;\n\t\t$.integer___selected_page_index\t\t\t=0;\n\t\t$.integer___previous_selected_page_index=0;\n\t\t\n\t\t$.object___control=\n\t\t{\n//\tANALYZE: prefix 'show_' (can exist oposite action - 'hide_')\n\t\t\tobject_dom___show_first_page\t\t:_,\n\t\t\tobject_dom___show_previous_page\t\t:_,\n\t\t\tobject_dom___show_next_page\t\t\t:_,\n\t\t\tobject_dom___show_last_page\t\t\t:_\n\t\t};\n\t\t\n\t\t\n\t\t$.F_Initialize=function(object___configuration)\n\t\t{\n\t\t\tif (object___configuration)\n\t\t\t{\n\t\t\t\t$.object_dom___component\t\t\t\t\t\t\t=object___configuration.object_dom___component||document.getElementById(object___configuration.string___DOM_id);\n\t\t\t\t$.object_dom___target\t\t\t\t\t\t\t\t=object___configuration.object_dom___target||document.getElementById(object___configuration.string___target_DOM_id);\n\t\t\t\t\n\t\t\t\t$.integer___selected_page_index\t\t\t\t\t\t=object___configuration.integer___selected_page_index||$.integer___selected_page_index;\n\n//\tANYLYZE: necessity to init $.integer___previous_selected_page_index here by configuration\t\t\t\t\n\n\t\t\t\t$.object___control.object_dom___show_previous_page\t=jQuery($.object_dom___component).find(\".class_div___element-Paginator--control__show_previous_page\")[0];\n\t\t\t\t$.object___control.object_dom___show_next_page\t\t=jQuery($.object_dom___component).find(\".class_div___element-Paginator--control__show_next_page\")[0];\n\t\t\t\n//\tevents:\n\t\t\t\t$.object___control.object_dom___show_previous_page.onclick=function()\n\t\t\t\t{\n\t\t\t\t\t$.F_ShowPreviousPage();\n\t\t\t\t};\n\t\t\t\t$.object___control.object_dom___show_next_page.onclick=function()\n\t\t\t\t{\n\t\t\t\t\t$.F_ShowNextPage();\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\tif (object___configuration['varchar___navigation_item_type']=='action')\n\t\t\t\t{\n//\tTODO: reorganize for set direct container\n\t\t\t\t\n\t\t\t\t\tvar array_object_dom___navigation_item\t=jQuery($.object_dom___component).find(\".class_div___element-Paginator--navigation_items\")[0].children,\n\t\t\t\t\t\tinteger___navigation_items_amount\t=array_object_dom___navigation_item.length;\n\t\t\t\t\t\n\t\t\t\t\tfor (var integer___index=0;integer___index<integer___navigation_items_amount;integer___index++)\n\t\t\t\t\t{\n//\tlink to child div/a on which attached events\n\t\t\t\t\t\t$.array_object_dom___navigation_item[integer___index]\t=array_object_dom___navigation_item[integer___index].children[0];\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (jQuery(array_object_dom___navigation_item[integer___index].children[0]).hasClass(\".class___element-status__selected\"))\n\t\t\t\t\t\t\t$.integer___previous_selected_page_index\t\t\t=integer___index;\n\n\t\t\t\t\t\t(function(integer___index)\n\t\t\t\t\t\t{\n//\tANALYZE,USABILITY: event type - click (change appearance/process only after mouse up) or mousedown?\n\t\t\t\t\t\t\tarray_object_dom___navigation_item[integer___index].children[0].onclick=function()\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$.F_ShowPageByIndex(integer___index);\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\n//\tprevent text mouse selection\n\t\t\t\t\t\t\tarray_object_dom___navigation_item[integer___index].children[0].onmousedown=function()\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t};\n//\tIE\n\t\t\t\t\t\t\tarray_object_dom___navigation_item[integer___index].children[0].onselectstart=function()\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t})(integer___index);\n\t\t\t\t\t\t\n\t\t\t\t\t\t$.integer___pages_amount++;\n\t\t\t\t\t}\n\t\t\t\t\t\n//\tANALYZE: prcessing linked objects\n\t\t\t\t\tif ($.object_dom___target)\n\t\t\t\t\t\t$.array_object_dom___target_item=$.object_dom___target.children;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tjQuery(array_object_dom___navigation_item).on('mouseenter',function()\n\t\t\t\t{\n\t\t\t\t\tjQuery(this).children().addClass(\"class___element-status__mouseover\");\n\t\t\t\t});\n\t\t\t\tjQuery(array_object_dom___navigation_item).on('mouseleave',function()\n\t\t\t\t{\n\t\t\t\t\tjQuery(this).children().removeClass(\"class___element-status__mouseover\");\n\t\t\t\t});\n\t\t\t\t\n\t\t\t\tjQuery($.object___control.object_dom___show_previous_page).children().on('mouseenter',function()\n\t\t\t\t{\n\t\t\t\t\tjQuery(this).addClass(\"class___element-status__mouseover\");\n\t\t\t\t});\n\t\t\t\tjQuery($.object___control.object_dom___show_previous_page).children().on('mouseleave',function()\n\t\t\t\t{\n\t\t\t\t\tjQuery(this).removeClass(\"class___element-status__mouseover\");\n\t\t\t\t});\n\t\t\t\tjQuery($.object___control.object_dom___show_next_page).children().on('mouseenter',function()\n\t\t\t\t{\n\t\t\t\t\tjQuery(this).addClass(\"class___element-status__mouseover\");\n\t\t\t\t});\n\t\t\t\tjQuery($.object___control.object_dom___show_next_page).children().on('mouseleave',function()\n\t\t\t\t{\n\t\t\t\t\tjQuery(this).removeClass(\"class___element-status__mouseover\");\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\t\t\n\t\t\n\t\t\n\t\t$.F_ShowFirstPage=function()\n\t\t{\n\t\t\t\n\t\t};\n\t\t$.F_ShowPreviousPage=function()\n\t\t{\n//\tANALYZE: necessity for case, when navigation is looped from left to right and reverse\n\t\t\tif ($.integer___selected_page_index>0)\n\t\t\t\t$.F_ShowPageByIndex($.integer___selected_page_index-1);\n\t\t};\n\t\t\n\t\t$.F_ShowPageByIndex=function(integer___index)\n\t\t{\n\t\t\t$.integer___selected_page_index\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t=integer___index;\n\t\t\t$.array_object_dom___navigation_item[$.integer___previous_selected_page_index].className\t=\"\";\n\t\t\t$.array_object_dom___navigation_item[$.integer___selected_page_index].className\t\t\t\t=\"class___element-status__selected\";\n\t\t\t\n//\tANALYZE: check necessity\n\t\t\tif ($.array_object_dom___target_item[integer___index])\n\t\t\t{\n//\thide previous selected page\n//\tTODO,ANALYZE: show loading animation by C_Animator component\n//\tshow target page\n\t\t\t\t\n\t\t\t\tif ($.array_object_dom___target_item[$.integer___previous_selected_page_index])\n\t\t\t\t\t$.array_object_dom___target_item[$.integer___previous_selected_page_index].style.display\t=\"none\";\n\t\t\t\t\n\t\t\t\tif ($.array_object_dom___target_item[$.integer___selected_page_index].tagName=='TABLE')\n\t\t\t\t\t$.array_object_dom___target_item[$.integer___selected_page_index].style.display\t\t=\"table\";\n\t\t\t\telse if ($.array_object_dom___target_item[$.integer___selected_page_index].tagName=='DIV')\n\t\t\t\t\t$.array_object_dom___target_item[$.integer___selected_page_index].style.display\t\t=\"block\";\n//\t\t\t\telse if ($.array_object_dom___target_item[$.integer___selected_page_index].tagName=='LI')\n//\t\t\t\t\t$.array_object_dom___target_item[$.integer___selected_page_index].style.display\t\t=\"list-item\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n//\tinitiate page loading (via AJAX or etc.)\n\t\t\t}\n\t\t\t\n\t\t\t$.integer___previous_selected_page_index\t=$.integer___selected_page_index;\n\t\t};\n\t\t\n\t\t$.F_ShowNextPage=function()\n\t\t{\n\t\t\tif ($.integer___selected_page_index<$.integer___pages_amount-1)\n\t\t\t\t$.F_ShowPageByIndex($.integer___selected_page_index+1);\n\t\t\t\n\t\t};\n\t\t$.F_ShowLastPage=function()\n\t\t{\n\t\t\t\n\t\t};\n\t\t\n\t\t\n\t}", "_paginate (entities, page, pageSize) {\n\t\treturn entities.slice((page - 1) * pageSize, (page - 1) * pageSize + pageSize)\n\t}", "async paginate(per_page = null, page = null) {\r\n if (!_.isNil(per_page)) {\r\n per_page = parseInt(per_page);\r\n } else {\r\n if (Request.has('per_page')) {\r\n per_page = parseInt(Request.get('per_page'));\r\n } else {\r\n per_page = 20;\r\n }\r\n }\r\n if (!_.isNil(page)) {\r\n page = parseInt(page);\r\n } else {\r\n if (Request.has('page')) {\r\n page = parseInt(Request.get('page'));\r\n } else {\r\n page = 1;\r\n }\r\n }\r\n let params = {\r\n offset: (page - 1) * per_page,\r\n limit: per_page,\r\n where: this.getWheres(),\r\n include: this.getIncludes(),\r\n order: this.getOrders(),\r\n distinct: true\r\n };\r\n\r\n if (!_.isArray(this.getAttributes()) && this.getAttributes().length > 0) {\r\n params = _.assign(params, { attributes: this.getAttributes() });\r\n }\r\n let model = this.Models();\r\n if (this.getScopes().length > 0) {\r\n _.forEach(this.getScopes(), scope => {\r\n model = model.scope(scope);\r\n });\r\n }\r\n const result = await model.findAndCountAll(params);\r\n\r\n const paginator = new LengthAwarePaginator(result.rows, result.count, per_page, page);\r\n return paginator;\r\n }", "function PaginationHelper(collection, itemsPerPage){\n this.arr = collection;\n this.itemsPerPage = itemsPerPage;\n this.itemCount; \n this.pageCount;\n }", "changePerPage(event) {\n const {params, accounting, setProp} = this.props;\n const perPage = parseInt(event.target.value, 10);\n setProp(Immutable.fromJS({\n paid: 1,\n unpaid: 1\n }), 'page');\n this.setState({\n perPage\n });\n const tab = accounting.get('tab');\n // Revert to page one, update search\n const search = this.updateBeforeRetrieval(tab);\n // Get records\n this.retrieveRecords(params.type, search, 1, perPage);\n }", "function Pager() {\n Emitter.call(this);\n this.el = dom(html);\n this.el.on('click', 'li > a', this.onclick.bind(this));\n this.perpage(5);\n this.total(0);\n this.show(0);\n}", "function Pager(props) {\n var _props$startFrom = props.startFrom,\n startFrom = _props$startFrom === void 0 ? 0 : _props$startFrom,\n _props$endAt = props.endAt,\n endAt = _props$endAt === void 0 ? 0 : _props$endAt,\n _props$totalRows = props.totalRows,\n totalRows = _props$totalRows === void 0 ? 0 : _props$totalRows,\n onPrev = props.onPrev,\n onNext = props.onNext;\n var isPrevDisabled = totalRows === 0 || startFrom === 0;\n var isNextDisabled = totalRows === 0 || endAt === totalRows;\n return /*#__PURE__*/react_default.a.createElement(react_default.a.Fragment, null, /*#__PURE__*/react_default.a.createElement(src[\"u\" /* Text */], {\n typography: \"body2\",\n color: \"primary.contrastText\"\n }, \"SHOWING \", /*#__PURE__*/react_default.a.createElement(\"strong\", null, startFrom + 1), \" to \", /*#__PURE__*/react_default.a.createElement(\"strong\", null, endAt), \" of\", ' ', /*#__PURE__*/react_default.a.createElement(\"strong\", null, totalRows)), /*#__PURE__*/react_default.a.createElement(StyledButtons, null, /*#__PURE__*/react_default.a.createElement(\"button\", {\n onClick: onPrev,\n title: \"Previous Page\",\n disabled: isPrevDisabled\n }, /*#__PURE__*/react_default.a.createElement(src_Icon[\"e\" /* CircleArrowLeft */], {\n fontSize: \"3\"\n })), /*#__PURE__*/react_default.a.createElement(\"button\", {\n onClick: onNext,\n title: \"Next Page\",\n disabled: isNextDisabled\n }, /*#__PURE__*/react_default.a.createElement(src_Icon[\"f\" /* CircleArrowRight */], {\n fontSize: \"3\"\n }))));\n}", "prevPage () {\n const { page } = this.computedPagination\n if (page > 1) {\n this.setPagination({ page: page - 1 })\n }\n }", "function PaginationHelper(collection, itemsPerPage) {\n this.collection = collection;\n this.itemsPerPage = itemsPerPage;\n let arr = [], temp = [], obj = {};\n this.arr = arr;\n this.obj = obj;\n\n for (let i = 0; i < collection.length; i++) {\n temp.push(collection[i]);\n if (temp.length === itemsPerPage) {\n arr.push(temp);\n temp = [];\n }\n }\n if (temp.length !== itemsPerPage) {\n arr.push(temp);\n }\n temp = 0;\n arr.forEach(array => {\n obj[temp] = array;\n temp++;\n })\n\n}", "function LengthAwarePaginator() {\n var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n\n _classCallCheck(this, LengthAwarePaginator);\n\n this.data = data;\n // Default to 5 per page\n this.perPage = 5;\n // Defines current page\n this.currentPage = 1;\n // Defines Search Index\n this.searchIndex = \"name\";\n // Defines Search String\n this.searchString = \"\";\n // Sets page to current page\n this.page = this.currentPage;\n }", "function buildPager() {\n vm.pagedItems = [];\n vm.itemsPerPage = 7;\n vm.currentPage = 1;\n vm.figureOutItemsToDisplay();\n }", "function paginationOptionsForNextPage(previousResult, pageSize) {\n if (previousResult !== undefined &&\n previousResult.response_metadata !== undefined &&\n previousResult.response_metadata.next_cursor !== undefined &&\n previousResult.response_metadata.next_cursor !== '') {\n return {\n limit: pageSize,\n cursor: previousResult.response_metadata.next_cursor,\n };\n }\n return;\n}", "onPaginationData(data) {\n this.$refs.pagination.setPaginationData(data);\n }", "function paginationBinding(){\n var selector = thisInstance.constants.selector,\n $paginationWrap = $(selector.paginationWrap),\n $nextButton = $paginationWrap.find(selector.nextPageButton),\n $prevButton = $paginationWrap.find(selector.prevPageButton);\n\n // next button bindings\n $nextButton.click(function(event){\n event.preventDefault();\n if(!$nextButton.hasClass('disable')){\n var firstIndex = parseInt($paginationWrap.find(selector.rangeFirst).text()),\n lastIndex = parseInt($paginationWrap.find(selector.rangeLast).text()),\n totalUsers = parseInt($paginationWrap.find(selector.totalUserCount).text()),\n usersPerPage = thisInstance.userPerPage,\n currentPage = parseInt(firstIndex / usersPerPage) + 1;\n if (lastIndex != totalUsers) {\n $nextButton.addClass('button-down');\n fetchAndLoadUserList({page: currentPage + 1}, undefined, undefined, function(){\n $nextButton.removeClass('button-down');\n });\n }\n }\n });\n // previous button bindings\n $prevButton.click(function(event){\n event.preventDefault();\n if(!$prevButton.hasClass('disable')){\n var firstIndex = parseInt($paginationWrap.find(selector.rangeFirst).text()),\n lastIndex = parseInt($paginationWrap.find(selector.rangeLast).text()),\n usersPerPage = thisInstance.userPerPage,\n currentPage = parseInt(firstIndex / usersPerPage) + 1;\n if (firstIndex >= usersPerPage) {\n fetchAndLoadUserList({page: currentPage - 1}, undefined, undefined, function(){\n $nextButton.removeClass('button-down');\n });\n }\n }\n });\n }", "dataInit() {\n this.paginate.page = 1\n this.data = _.cloneDeep(this.model)\n }", "_applyShowPagination(value, old) {\n if (value) {\n if (this.__pages.length > 1) {\n this.__pagination.show();\n }\n } else {\n this.__pagination.hide();\n }\n }", "static optOrderPagination(){\n return window.API_ROOT + 'rest/optOrder.pagination/v1';\n }", "constructor(array)\n {\n if (array.length > 0)\n this.#pages = [array];\n else\n this.#pages = [];\n this.#currentPageNumber = -1;\n }", "setPageArray() {\n const range = this.getPageRange(this.page, this.derivedPageCount);\n this.pages = [];\n for (let i = range.min; i <= range.max; i++) {\n const btnInfo = {\n class: i === this.page ? 'tag-pager__pager-button active' : 'tag-pager__pager-button',\n page: i,\n visible: i <= this.derivedPageCount,\n };\n this.pages.push(btnInfo);\n }\n }", "function setPage(value) {\n currentPage = value;\n}", "createPaging() {\n var result = [];\n for (let i = 1; i <= this.state.totalPage; i++) {\n result.push(\n <MDBPageNav href={\"/product/\" + i} >\n <span aria-hidden=\"true\">{i}</span>\n </MDBPageNav >\n )\n }\n return result;\n }", "if (currentPage <= 6) {\n startPage = 1;\n endPage = totalPages;\n }", "constructor(items, perPage = 10, currentPage = 1) {\n /**\n * All of the items being paginated.\n *\n * @var array\n */\n this.items = items;\n\n /**\n * The number of items to be shown per page.\n *\n * @var int\n */\n this.perPage = perPage;\n\n /**\n * The current page being \"viewed\".\n *\n * @var int\n */\n this.currentPage = currentPage;\n }", "function pmsetPagination(type){\n var curr = parseInt($('#PMPageNumber').text());\n var totalpage = $('#PMTotalPages').text();\n switch(type){\n case \"first\":\n curr = 1;\n break;\n case \"prev\":\n if(curr > 1){\n curr = curr - 1;\n }\n break;\n case \"next\":\n if(curr < totalpage){\n curr = curr + 1;\n }\n break;\n case \"last\":\n curr = totalpage;\n break;\n }\n $('#PMPageNumber').text(curr);\n//<<<<<\trmReloadTable();\n}", "function showPagination(count,current_page,offset,baseUrl, queryString,visibleNumbers,el,prefix,noHref) {\n let output=\"\";\n let fullUrl;\n if(el===undefined) el=\".pagination\";\n if(prefix === undefined || prefix === false) prefix=\"\";\n noHref=noHref===undefined ? false:noHref;\n if(queryString){\n fullUrl=baseUrl+\"?\"+queryString+\"&\"+prefix+\"page=%page%\";\n }else{\n fullUrl=baseUrl+\"?\"+prefix+\"page=%page%\";\n }\n if(count > offset){\n let lastPage=Math.ceil(count/offset);\n let endIndex,startIndex;\n if (current_page > 1){\n output+= noHref ? '<li class=\"page-item\"><a class=\"page-link\" data-page=\"1\" aria-label=\"Previous\"><span aria-hidden=\"true\">&laquo;</span></a></li><li class=\"page-item\"><a class=\"page-link\" data-page=\"'+(current_page-1)+'\" aria-label=\"Previous\">قبلی</a></li>':'<li class=\"page-item\"><a class=\"page-link\" href=\"'+baseUrl+'\" aria-label=\"Previous\"><span aria-hidden=\"true\">&laquo;</span></a></li><li class=\"page-item\"><a class=\"page-link\" href=\"'+substitute(fullUrl,{\"%page%\":current_page-1})+'\" aria-label=\"Previous\">قبلی</a></li>';\n }\n if((current_page+(visibleNumbers-1)) > lastPage){\n endIndex=lastPage;\n startIndex=current_page-(visibleNumbers-(lastPage-current_page));\n }else{\n\n startIndex=current_page - (visibleNumbers-1);\n endIndex=current_page+ (visibleNumbers-1);\n }\n startIndex= startIndex<=0 ? 1:startIndex;\n for(pageNumber=startIndex;pageNumber<=endIndex;pageNumber++){\n output+= pageNumber==current_page ? \"<li class='page-item active'>\":\"<li class='page-item'>\";\n output+=noHref ? \"<a class='page-link' data-page='\"+pageNumber+\"'>\"+pageNumber+\"</a>\":\"<a class='page-link' href='\"+substitute(fullUrl,{\"%page%\":pageNumber})+\"'>\"+pageNumber+\"</a>\";\n }\n if(current_page != lastPage){\n output+=noHref ? '<li class=\"page-item\"><a class=\"page-link\" data-page=\"'+(current_page+1)+'\" aria-label=\"Previous\">بعدی</a></li>':'<li class=\"page-item\"><a class=\"page-link\" href=\"'+substitute(fullUrl,{\"%page%\":current_page+1})+'\" aria-label=\"Previous\">بعدی</a></li>';\n output+=noHref ? '<li class=\"page-item\"><a class=\"page-link\" data-page=\"'+lastPage+'\" aria-label=\"Next\"><span aria-hidden=\"true\">&raquo;</span></a></li>':'<li class=\"page-item\"><a class=\"page-link\" href=\"'+substitute(fullUrl,{\"%page%\":lastPage})+'\" aria-label=\"Next\"><span aria-hidden=\"true\">&raquo;</span></a></li>';\n }\n }\n $(el).html(output);\n}", "function renderPagination() {\n const prev = document.querySelector('.page-nav.prev');\n const next = document.querySelector('.page-nav.next');\n const numberOfPages = Math.ceil(pagination.totalBookmarks / pagination.limit);\n\n // disable navigation when there are no other pages\n if (numberOfPages === 1) {\n prev.classList.add('disabled');\n next.classList.add('disabled');\n } else {\n prev.classList.remove('disabled');\n next.classList.remove('disabled');\n }\n\n // disable next if there are no more pages\n if (pagination.currentPage === numberOfPages - 1)\n next.classList.add('disabled');\n else\n next.classList.remove('disabled');\n\n // disable previous if you're on the first page\n if (pagination.currentPage === 0)\n prev.classList.add('disabled');\n else\n prev.classList.remove('disabled');\n\n // render pages\n const pageList = document.querySelector('.pagination > .pages');\n pageList.innerHTML = ''; // empty list\n\n for (let i = 0; i < numberOfPages; i++) {\n const page = document.createElement('a');\n const text = document.createTextNode(`${i}`);\n page.classList.add('page-nav');\n page.setAttribute('data-page-number', `${i}`);\n\n if (i === pagination.currentPage)\n page.classList.add('current');\n\n page.appendChild(text);\n pageList.append(page);\n }\n}", "addPagination() {\n if (this.pdfBuilder.includePageNumber) {\n const { doc, margins, documentFont } = this.pdfBuilder;\n let text = this.currentPage;\n doc.font(documentFont);\n doc.fontSize(9);\n\n if (this.docTitle.length > 0) {\n text = `${this.docTitle} - ${text}`;\n }\n doc.text(text, margins.left, this.height + margins.bottom, { align: 'right', width: this.width });\n }\n }", "function Page() {\n\n /**\n * ResultSet of the page\n * @name Page#data\n * @type {ResultSet}\n * @readonly\n * @throws {SuiteScriptError} READ_ONLY when setting the property is attempted\n *\n * @since 2018.1\n */\n this.data = undefined;\n /**\n * References the query results contained in this page.\n * @name QueryPage#pagedData\n * @type {PagedData}\n * @readonly\n * @throws {SuiteScriptError} READ_ONLY when setting the property is attempted\n *\n * @since 2018.1\n */\n this.pagedData = undefined;\n /**\n * The range of query results for this page.\n * @name QueryPage#pageRange\n * @type {PageRange}\n * @readonly\n * @throws {SuiteScriptError} READ_ONLY when setting the property is attempted\n *\n * @since 2018.1\n */\n this.pageRange = undefined;\n /**\n * Indicates whether the page is the first of the paged query results.\n * @name Page#isFirst\n * @type {boolean}\n * @readonly\n * @throws {SuiteScriptError} READ_ONLY when setting the property is attempted\n *\n * @since 2018.1\n */\n this.isFirst = undefined;\n /**\n * Indication whether this page is the last one\n * @name Page#isLast\n * @type {boolean}\n * @readonly\n * @throws {SuiteScriptError} READ_ONLY when setting the property is attempted\n *\n * @since 2018.1\n */\n this.isLast = undefined;\n /**\n * Returns the object type name (query.Page)\n * @governance none\n * @return {string}\n *\n * @since 2018.1\n */\n this.toString = function () { };\n\n /**\n * get JSON format of the object\n * @governance none\n * @return {Object}\n *\n * @since 2020.1\n */\n this.toJSON = function () { };\n }", "getItensPorPagina() {\n return this.itensPorPagina;\n }" ]
[ "0.74893063", "0.7349393", "0.7203362", "0.716896", "0.71516776", "0.71486986", "0.7138119", "0.7101385", "0.70203567", "0.70171416", "0.6896033", "0.6882311", "0.68740004", "0.6873007", "0.6853512", "0.681756", "0.68156886", "0.68156886", "0.68156886", "0.6754232", "0.6726965", "0.6710261", "0.6626192", "0.65919596", "0.659177", "0.6544107", "0.6526768", "0.6478072", "0.646018", "0.6459356", "0.6454101", "0.6414556", "0.641206", "0.6405816", "0.6373713", "0.6371731", "0.6367649", "0.6355541", "0.63395405", "0.63395405", "0.6328944", "0.63280714", "0.6320292", "0.63184893", "0.63184893", "0.6306568", "0.6292758", "0.6292758", "0.6288133", "0.62874424", "0.6268798", "0.6251435", "0.62481326", "0.6217759", "0.62070596", "0.6198613", "0.61785305", "0.6177422", "0.6175671", "0.61707956", "0.61584413", "0.6155743", "0.61522055", "0.6085821", "0.6079908", "0.6076458", "0.60757387", "0.6068828", "0.6060071", "0.6060071", "0.605842", "0.605842", "0.6050854", "0.60319126", "0.6022744", "0.6022118", "0.60068136", "0.59873027", "0.59851307", "0.59541345", "0.5942809", "0.59326106", "0.5932559", "0.59303653", "0.59272486", "0.592674", "0.5917567", "0.5914492", "0.59123", "0.5911996", "0.59083223", "0.5901984", "0.58866847", "0.5884324", "0.5873096", "0.5873058", "0.5861426", "0.5859833", "0.58596563", "0.58473617", "0.5838639" ]
0.0
-1
Formats the contact info
function formatItem(contact) { return contact.Name + ' [' + contact.Alias + '] | ' + contact.Team + ' | Hobbies: '+ contact.Hobbies; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function convertContactToString(item) {\n objString += '|{';\n objString += '\"type\": \"' + item.type + '\",';\n objString += '\"id\": \"' + item.id + '\",';\n objString += '\"firstName\": \"' + item.firstName + '\",';\n objString += '\"lastName\": \"' + item.lastName + '\",';\n objString += '\"phoneNumbers\": \"' + item.phoneNumbers + '\"';\n objString += '}';\n }", "function formatTypeaheadDisplay(contact) {\n if (utils.isEmptyVal(contact) || utils.isEmptyString(contact)) {\n return undefined;\n }\n //if name prop is not present concat firstname and lastname\n //return (contact.name || (contact.firstname + \" \" + contact.lastname));\n var firstname = angular.isUndefined(contact.first_name) ? '' : contact.first_name;\n var lastname = utils.isEmptyVal(contact.last_name) ? '' : contact.last_name;\n return (contact.name || (firstname + \" \" + lastname));\n\n }", "function contactHtmlFromObject(contact) {\n console.log(contact);\n var html = '';\n html += '<li class=\"list-group-item contact\">';\n html += '<div>';\n if (contact.name != '') {\n html += '<p class=\"lead\">' + contact.name + '</p>';\n }\n html += '<p><a href=\"' + contact.email + '\" target=\"_blank\" title=\"' + contact.email + '\">' + contact.email + '</a></p>';\n var textSelect = filterSelect(contact.location.city, listOption)\n if (textSelect != '') {\n\n\n var strZip = contact.location.zip == \"\" ? '' : '--' + contact.location.zip\n var strState = contact.location.state == \"\" ? '' : ',' + contact.location.state\n html += '<p><small>' + '<b>' + textSelect + '</b>' + strState + strZip + '</small></p>';\n }\n if (contact.time != undefined) {\n var d = new Date(contact.time);\n html += '<p>' + d.toLocaleString() + '</p>';\n }\n html += '</div>';\n html += '</li>';\n return html;\n}", "function formatCandidateDetails(array) {\n var contactInfo = {\n Address: null,\n City: null,\n CountryId: null,\n Emails: [],\n //Fax: null,\n //LinePhone1: null,\n //LinePhone2: null,\n MobilePhones: [],\n Postcode: null,\n StateName: null,\n StateRegionId: null,\n Suburb: null,\n };\n angular.forEach(array, function(item, index) {\n if (item.Type === 'e') {\n contactInfo.Emails.push({\n value: item.Email,\n isPrimary: false,\n isPublic: false\n });\n }\n else if (item.Type === \"p\") {\n contactInfo.MobilePhones.push({\n value: item.MobilePhone,\n isPrimary: false,\n isPublic: false\n }\n );\n }\n else if (item.Type === \"ad\") {\n contactInfo.Address = item.Address;\n contactInfo.City = item.City;\n contactInfo.Postcode = item.Postcode;\n contactInfo.StateName = item.StateName;\n contactInfo.StateRegionId = item.StateRegionId;\n contactInfo.Suburb = item.Suburb;\n contactInfo.CountryId = item.CountryId;\n }\n });\n\n return contactInfo;\n }", "function contactCleaner(contactInfo) {\n //check if object has all properties required.\n //combine the different form elements to make 1 name string and 1 address string that contain all the information.\n\n\n //check that the object contains the phoneContact proprty and that it is on\n //set the contactByPhone to true\n if(\"phoneContact\" in contactInfo && contactInfo.phoneContact == \"on\") {\n contactInfo.contactByPhone = true;\n }\n else {\n contactInfo.contactByPhone = false;\n }\n \n //check that the mailContact is in the object, and that it is enabled.\n if(\"mailContact\" in contactInfo && contactInfo.mailContact == \"on\") {\n contactInfo.contactByMail = true;\n }\n else {\n contactInfo.contactByMail = false;\n }\n \n //check for emailContact in the object, and make sure that it is enabled.\n if(\"emailContact\" in contactInfo && contactInfo.emailContact == \"on\") {\n contactInfo.contactByEmail = contactInfo.email;\n }\n else {\n contactInfo.contactByEmail = \"No\";\n }\n\n //check if the user selected the \"any\" option, and if they have then set all the contact options to the values they gave.\n if(\"anyContact\" in contactInfo && contactInfo.anyContact == \"on\") {\n contactInfo.contactByPhone = true;\n contactInfo.contactByMail = true;\n contactInfo.contactByEmail = contactInfo.email;\n }\n}", "function addContactInfo() {\n if (_.isEmpty($scope.contactInfo)) {\n $scope.contactInfoCssClass = 'state-filling';\n }\n\n $scope.contactInfo.push({type: ContactInfoTypeEnum.PHONE, value: ''});\n }", "function contactHtmlFromObject(contact){\r\n console.log( contact );\r\n var html = '';\r\n html += '<li class=\"list-group-item contact\">';\r\n html += '<div>';\r\n html += '<p class=\"lead\">'+contact.name+'</p>';\r\n html += '<p>'+contact.email+'</p>';\r\n html += '<p>'+contact.message+'</p>';\r\n html += '<p><small title=\"'+contact.location.zip+'\">'+contact.location.city+', '+contact.location.state+'</small></p>';\r\n html += '</div>';\r\n html += '</li>';\r\n return html;\r\n}", "contactsFormatter (currentVersion, roles) {\n const contacts = []\n\n const licenceHolderParty = currentVersion.parties.find((party) => {\n return party.ID === currentVersion.ACON_APAR_ID\n })\n\n const licenceHolderAddress = licenceHolderParty.contacts.find((contact) => {\n return contact.AADD_ID === currentVersion.ACON_AADD_ID\n })\n\n contacts.push({\n type: 'Licence holder',\n ...nald.formatting.nameFormatter(licenceHolderParty),\n ...nald.formatting.addressFormatter(licenceHolderAddress.party_address)\n })\n\n const contactCodes = ['FM', 'LA', 'LC', 'MG', 'RT']\n roles.filter(role => contactCodes.includes(role.role_type.CODE)).forEach((role) => {\n contacts.push({\n type: sentenceCase(role.role_type.DESCR),\n ...nald.formatting.nameFormatter(role.role_party),\n ...nald.formatting.addressFormatter(role.role_address)\n })\n })\n\n return contacts\n }", "function formatPeople(group) {\n let parsedInfo = group.map( person => {\n return {\n name: `${person.name.first} ${person.name.last}`,\n location: `${person.location.street} <br> ${person.location.city}, ${person.location.state} <br> ${person.location.postcode} `,\n picture: person.picture.large ,\n email: person.email ,\n phone: person.phone,\n }\n })\n return parsedInfo\n}", "function address(a) {\n var lines = [];\n if (a.info.name !== null && a.info.name)\n lines.push(\"<strong>\" + a.info.name + \"</strong>\");\n if (a.info.address_1 !== null && a.info.address_1)\n lines.push(a.info.address_1);\n if (a.info.address_2 !== null && a.info.address_2)\n lines.push(a.info.address_2);\n if (a.info.city || a.info.state || a.info.zip) {\n var line = [];\n if (a.info.city !== null)\n line.push(a.info.city);\n if (a.info.state !== null)\n line.push(a.info.state);\n if (a.info.zip !== null)\n line.push(a.info.zip);\n lines.push(line.join(\" \"));\n }\n if (a.country !== null && a.country)\n lines.push(a.country);\n if (a.info.phone !== null && a.info.phone)\n lines.push(a.info.phone);\n if (a.info.email !== null && a.info.email && a.info.email)\n lines.push(a.info.email);\n if (a.info.web !== null && a.info.web)\n lines.push(a.info.web);\n return lines.join(\"<br>\");\n}", "function renderContact(contact) {\n var id = contact.id,\n name = contact.name,\n email = contact.email,\n picture = contact.picture,\n _contact$address = contact.address,\n street = _contact$address.street,\n suite = _contact$address.suite,\n city = _contact$address.city,\n zipcode = _contact$address.zipcode,\n phone = contact.phone,\n website = contact.website,\n company = contact.company;\n return \"\\n <div class=\\\"card\\\" data-id=\\\"\".concat(id, \"\\\">\\n <button class=\\\"deleteBtn\\\" title=\\\"Delete this contact\\\">X</button>\\n <div class=\\\"avatar\\\">\\n <div class=\\\"circle\\\"></div>\\n <div class=\\\"circle\\\"></div>\\n <img src=\\\"\").concat(picture, \"\\\" />\\n </div>\\n <div class=\\\"info\\\">\\n <span class=\\\"name big\\\">\").concat(name, \"</span>\\n <span class=\\\"email small\\\">\").concat(email, \"</span>\\n </div>\\n <div class=\\\"details\\\">\\n <div class=\\\"phone\\\">\").concat(phone, \"</div>\\n <div class=\\\"website\\\">\").concat(website, \"</div>\\n </div>\\n\\n <div class=\\\"additional\\\">\\n <div class=\\\"address\\\">\\n <div class=\\\"suite\\\">\").concat(suite, \"</div>\\n <div class=\\\"street\\\">\").concat(street, \"</div>\\n <div class=\\\"city\\\">\").concat(city, \", \").concat(zipcode, \"</div>\\n </div>\\n <div class=\\\"company\\\">\\n <div class=\\\"label\\\">Works at</div>\\n <div class=\\\"company-name\\\">\").concat(company.name, \"</div>\\n </div>\\n </div>\\n</div>\\n\");\n}", "function cleanContact(contact, programmeList) {\n contact.id = contact.dataItemID;\n if (!contact.hasOwnProperty('name')) {\n contact.name = contact.id\n }\n delete contact.dataItemID;\n delete contact.dataTypeID;\n\n // look for relationships contact.xxx.[..,..,..] - but they should only be the reverse relationships\n // not sure we have a way to find those at the moment since cmdb return has already translated them\n relationships = []\n for (var reltype in contact) {\n for (var itemtype in contact[reltype]) {\n if (typeof contact[reltype][itemtype] === 'object') {\n for (relationship in contact[reltype][itemtype]) {\n relitemlink = \"\"\n relitem = itemtype + \": \" + contact[reltype][itemtype][relationship].dataItemID\n if (itemtype == 'system') {\n relitemlink = systemTool + contact[reltype][itemtype][relationship].dataItemID\n }\n if (itemtype == 'endpoint') {\n relitemlink = endpointTool + contact[reltype][itemtype][relationship].dataItemID\n }\n if (itemtype == 'contact') {\n relitemlink = contactTool + contact[reltype][itemtype][relationship].dataItemID\n }\n relationships.push({'reltype': reltype, 'relitem': relitem, 'relitemlink': relitemlink})\n }\n }\n }\n }\n if (relationships) {\n contact.relationships = relationships\n }\n\n // now add other fields to enable user interface\n contact.localpath = \"/contacts/\"+encodeURIComponent(contact.id);\n contact.ctypeList = getCtypeList(contact.contactType);\n contact.statusList = getStatusList(contact.status);\n// contact.programmeList = getProgrammeList(programmeList, contact.programme);\n\n if (!contact.avatar) {\n\n // Use gravatar to get avatar from email\n var md5hash = \"\";\n if (contact.email) {\n md5hash = crypto.createHash('md5').update(contact.email).digest('hex');\n }\n contact.avatar = \"https://www.gravatar.com/avatar/\"+md5hash+\"?s=80&d=blank\";\n }\n\n return contact;\n}", "function getContactData() {\n return contactData;\n }", "function onSuccess(contacts) {\n\t\t\t//console.log(JSON.stringify(contacts))\n\t\t\tvar li = '';\n\t\t\t$.each(contacts, function(key, value) {\n\t\t\t\tif (value.name) {\n\t\t\t\t\t$.each(value.name, function(key, value) {\n\t\t\t\t\t\tif (key == 'formatted') {\n\t\t\t\t\t\t\tname = value;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (value.phoneNumbers) {\n\t\t\t\t\t$.each(value.phoneNumbers, function(key, value) {\n\t\t\t\t\t\tphone = value.value;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tli += '<li style=\"text-decoration:none;\">' + name + ' ' + phone + '</li>';\n\t\t\t});\n\t\t\talert('sdj');\n\t\t\talert(li);\n\t\t\t$(\"#contact\").html(li);\n\t\t}", "function formatAddressForPrint(address) {\r\n var arr = [];\r\n address.address && arr.push(address.address);\r\n _.isObject(address.city) && arr.push(address.city.name);\r\n _.isObject(address.state) && arr.push(address.state.name);\r\n _.isObject(address.country) && arr.push(address.country.name);\r\n \r\n return arr.join('\\n\\r');\r\n }", "function composeContactData(data) {\n return _.isObject(data) && {\n contact_email : data['email'] || '',\n contact_firstname : data['firstName'] || '',\n contact_lastname : data['lastName'] || '',\n contact_handle : data['instagram'] || '',\n contact_phone : data['phone'] || ''\n }\n }", "function extendContact(contact, response) {\n contact.lastName = response.Surname;\n contact.otherNames = response.OtherNames;\n contact.status = response.status;\n contact.lga = response.LGA;\n contact.state = response.State;\n contact.dateFirstVisit = response.dailyVisits[0].dateOfVisit;\n contact.dateLastContact = dateParser.toISOStringGuessingFormat(\n response.DateLastContact, contact.dateFirstVisit);\n contact.daysSinceLastContact = dateParser.daysFromToday(\n contact.dateLastContact, contact.dateFirstVisit);\n contact.address = response.Address;\n contact.age = response.Age;\n contact.gender = response.Gender;\n contact.phone = response.Phone;\n contact.sourceCase = response.SourceCase;\n contact.contactType = response.ContactType;\n contact.dailyVisits = response.dailyVisits;\n contact.includingDetailedInfo = true;\n\n contact.dailyVisits = [];\n angular.forEach(response.dailyVisits, function(visit) {\n var symptoms = [];\n\n angular.forEach(visit.symptoms, function(value, key) {\n if (value && key !== 'temperature') {\n symptoms.push(key);\n }\n });\n\n contact.dailyVisits.push({\n dateOfVisit: visit.dateOfVisit,\n interviewer: visit.interviewer,\n temperature: visit.symptoms.temperature,\n symptoms: symptoms\n });\n });\n }", "function loanContactsDetails_Set(contact) {\n\n $(\"#LoanContactName_helm\").text(helm.formatText(contact.FullName));\n $(\"#LoanContactType_helm\").text(helm.formatText(contact.BorrowerTypeFormatted));\n $(\"#LoanContactBirthDate_helm\").text(helm.formatText(contact.BirthDateFormatted));\n\n // * nearest actual age - separate with forward slash if both values present;\n var ageDisplay = helm.formatText(contact.ActualAge);\n ageDisplay = (ageDisplay == 0) ? \"\" : ageDisplay;\n var nearestAge = helm.formatText(contact.NearestAge);\n nearestAge = (nearestAge == 0) ? \"\" : nearestAge;\n var ageTypeMedianText = \"\";\n if (ageDisplay.length !== 0 && nearestAge.length !== 0) {\n ageTypeMedianText = \" / \";\n }\n if (contact.BorrowerType !== Compass.Lookup.BorrowerType.AlternateContact.key) {\n ageDisplay += ageTypeMedianText + nearestAge;\n }\n \n\n //hide/show help bubble if nearest age is not present\n $(\"#NearestAgePopover_helm\").toggleClass(\"displayNone\", nearestAge === \"\");\n $(\"#LoanContactAge_helm\").text(ageDisplay);\n \n //hide gold star if NOT youngest borrower or only there is only one borrower \n if (helm.LoanDetailsData.LoanContacts.length > 1 && contact.IsYoungestCoBorrower) {\n $(\"#LoanContactsDetailsWrapper_helm div.starChar_helm\").attr(\"title\", \"Youngest \" + contact.BorrowerTypeFormatted.trim());\n $(\"#LoanContactIsYoungest_helm\").toggleClass(\"displayNone\", false);\n } else {\n $(\"#LoanContactIsYoungest_helm\").toggleClass(\"displayNone\", true);\n }\n \n /***/\n $(\"#ContactSsnSecure_helm\").text(helm.formatText(contact.SsnSecureFormatted));\n $(\"#ContactSsn_helm\").text(helm.formatText(contact.SsnFormatted));\n\n //hide/show help bubble if ssn is not present\n $(\"#SsnPopover_helm\").toggleClass(\"displayNone\", contact.SsnFormatted === \"\");\n\n $(\"#HomePhoneNo_helm\").text(helm.formatText(contact.HomePhoneNumberFormatted));\n\n // * Is the Borrower DOB \n var $missingDOBAlert = $(\"#MissingDOBAlert_Helm\");\n var $missingDOBAlertRedirectUrl = $(\"#MissingDOBAlert_Helm a\");\n if (contact.IndicateConfirmedDOB) {\n $(\"tr#ContactDOB_Helm\").toggleClass(\"redAlert\", true);\n $missingDOBAlert.toggleClass(\"displayNone\", false);\n $missingDOBAlertRedirectUrl.attr(\"href\", contact.DOBFixURL);\n }\n else { \n $(\"tr#ContactDOB_Helm\").toggleClass(\"redAlert\", false);\n $missingDOBAlert.toggleClass(\"displayNone\", true);\n $missingDOBAlertRedirectUrl.attr(\"href\", \"\");\n }\n }", "function formatAddress(employee) {\n let city = capitalize(employee.location.city);\n let state = capitalize(employee.location.state);\n let address = employee.location.street + '<br>'\n address += city + ', ' + state;\n address += ' ' + employee.location.postcode + ', ';\n address += employee.nat + '<br>';\n return address;\n}", "function formatAddress(address) {\n\treturn address;\n}", "function renderContact(id) {\n const contactId = id || getSelectedContactId()\n\n if (contactId) {\n const contact = client.contacts.get(contactId)\n updateContactForm(contact)\n const contactDisplay = document.getElementById('display')\n let text = '<h5>Contact Info</h5>'\n contactDisplay.innerHTML = ''\n Object.keys(contact).forEach(\n key => (text += '<li><b>' + key + '</b>: <i>' + contact[key] + '</i></li>')\n )\n\n contactDisplay.innerHTML = '<ul>' + text + '</ul>';\n } else {\n const contactDisplay = document.getElementById('display')\n contactDisplay.innerHTML = '';\n clearContact()\n }\n}", "function extractContactData(obj) {\n obj = _.isDefined(obj) ? obj : $cart || {};\n\n return {\n email : obj['contact_email'],\n fullName : (obj['contact_firstname'] + ' ' + obj['contact_lastname']).trim(),\n firstName : obj['contact_firstname'],\n lastName : obj['contact_lastname'],\n instagram : obj['contact_handle'],\n phone : obj['contact_phone']\n };\n }", "function formatContactName() {\n if (typeof(Storage) == \"undefined\") {\n alert(\"Configuration save failed\");\n return;\n }\n\n\tconst formatChars = document.forms[\"formatForm\"][\"inputChar\"].value;\n\tconst formatNum = document.forms[\"formatForm\"][\"inputNum\"].value;\n\n const formatOptions = getFormatOptions(formatChars, formatNum);\n\n for(var opt in formatOptions) {\n localStorage.setItem(opt, formatOptions[opt]);\n }\n alert(\"Configuration saved succesfully\");\n}", "function createContact(name, phone, address) {\n return `<p>${name} can be reached at ${phone} and lives at ${address}</p>`\n}", "function format(fieldLabel) {\n\t\t\t if (fieldLabel === \"address1\" || fieldLabel === \"city\") address += \", \";\n\t\t\t else if (fieldLabel === \"address2\") address += \"\\n\";\n\t\t\t else if (fieldLabel === \"state\") address += \" \";\n\t\t\t }", "renderContactInfo() {\n return (\n <ContactInfo\n onChange={this.onChangeContactInfo}\n onClickUpdate={this.onClickUpdateInfo}\n {...this.state.userdata}\n />\n );\n }", "function onSuccess(contacts) {\n console.log(\"\\n\\tCONTACTS:\");\n console.log(contacts);\n var r = Math.floor((Math.random() * contacts.length));\n console.log(\"Random contact: \" + r);\n //for (var i = 0; i < contacts.length; i++) {\n var output3 = document.querySelector(\"#three\");\n var p = document.createElement(\"p\");\n\n if (contacts.length != 0) {\n\n if (contacts[r].displayName != null) {\n p.innerHTML = \"<strong>Contact's Name:</strong> \" + contacts[r].displayName + \"<br>\";\n } else {\n p.innerHTML += \"<strong>Contact's Name:</strong> <small>No name on record.<small>\" + \"<br>\";\n }\n\n if (contacts[r].phoneNumbers != null) {\n for (var i = 0; i < contacts[r].phoneNumbers.length; i++) {\n if (contacts[r].phoneNumbers.length > 1) {\n p.innerHTML += \"<strong>Phone \" + (i + 1) + \" (\" + contacts[r].phoneNumbers[i].type + \")\" + \":</strong> \" + contacts[r].phoneNumbers[i].value + \"<br>\";\n } else {\n p.innerHTML += \"<strong>Phone:</strong> \" + contacts[r].phoneNumbers[i].value + \"<br>\";\n }\n }\n } else {\n p.innerHTML += \"<strong>Phone:</strong> <small>No phone number on record.</small>\" + \"<br>\";\n }\n\n if (contacts[r].emails != null) {\n for (var i = 0; i < contacts[r].emails.length; i++) {\n if (contacts[r].emails.length > 1) {\n p.innerHTML += \"<strong>Email \" + (i + 1) + \":</strong> \" + contacts[r].emails[i].value + \"<br>\";\n } else {\n p.innerHTML += \"<strong>Email:</strong> \" + contacts[r].emails[i].value + \"<br>\";\n }\n }\n } else {\n p.innerHTML += \"<strong>Email:</strong> <small>No email on record.</small>\" + \"<br>\";\n }\n\n\n if (contacts.addresses != null) {\n for (var i = 0; i < contacts[r].addresses.length; i++) {\n p.innerHTML += \"<strong>Address:</strong> \" + contacts[r].addresses[i].formatted + \"<br>\";\n }\n } else {\n p.innerHTML += \"<strong>Address:</strong> <small>No address on record.</small>\" + \"<br>\";\n }\n } else {\n p.innerHTML = \"No contacts found on phone.\"\n }\n output3.appendChild(p);\n\n //}\n}", "function format ( d ) {\n\n console.log(d);\n contacts_array[d.id] = d.contacts;\n\n\n // `d` is the original data object for the row\n var num_contacts = d.contacts.length;\n attendance = num_contacts;\n total_num_contacts = d.num_active_contacts;\n\n\n\n return '<table cellpadding=\"5\" cellspacing=\"0\" border=\"0\" style=\"padding-left:50px;\">'+\n '<tr>'+\n '<td><strong>Attendance:</strong></td>'+\n '<td style=\"padding: 0 30px;\"><a id=\"modal_launcher\" href=\"#\" data-row-id=\"' + d.id + '\">' + num_contacts + '/' + total_num_contacts + '</a></td>' +\n '</tr>'+\n '</table>';\n}", "function displayContactInfo(display_name = \"No Contact\", handle = \"-\") {\n const nameElement = document.getElementById(\"name\");\n const handleElement = document.getElementById(\"handle\");\n\n nameElement.textContent = display_name;\n handleElement.textContent = handle;\n}", "formatAddresses(recipients) {\n return recipients.map(({ email }) => {\n //format with helper, pass in email just extracted\n return new helper.Email(email);\n });\n }", "function FormatPhoneNumber() {\n\n return function (tel) {\n var formattedNumber = '';\n\n // If blank, null, undef - return an empty string\n if (!tel) {\n return '';\n }\n\n // Ensure it's a string and trim it while we're at it\n var value = tel.toString().trim();\n\n // If there's any non numeric digits, return the trimmed string\n if (value.match(/[^0-9]/)) {\n return tel;\n }\n\n // Format the phone number if it's 7, 10 or 11 chars long\n switch (value.length) {\n case 7:\n formattedNumber =\n value.substr(1, 3) + '-' +\n value.substr(4, 4);\n break;\n\n case 10:\n formattedNumber =\n '(' +\n value.substr(0, 3) + ') ' +\n value.substr(3, 3) + '-' +\n value.substr(6, 4);\n break;\n\n case 11:\n formattedNumber =\n value.substr(0, 1) + ' (' +\n value.substr(1, 3) + ') ' +\n value.substr(4, 3) + '-' +\n value.substr(7, 4);\n break;\n\n default:\n formattedNumber = value;\n }\n\n return formattedNumber;\n };\n }", "getFormattedAddress() {\n\n }", "function formatPhoneNumber(phone){\n // Code modified for Trac 1598.\n var phoneNumberLength = phone.length;\n if(!phoneNumberLength < 11){\n phone = ReplaceAll (phone, \" \" ,\"\");\n phone = ReplaceAll (phone, \"-\" ,\"\");\n phoneNumberLength = phone.length;\n if(phoneNumberLength == 11){\n var isOne = phone.substring(0,1);\n if(isOne == 1){\n phone= phone.replace(\"1\",\"\");\n }\n }\n }\n // End of code modified for Trac 1598.\n var sAreaCode = phone.substring(0,3);\n var s3dig = phone.substring(3,6);\n var s4dig = phone.substring(6,10);\n var newPhone = \"(\"+sAreaCode+\")\"+s3dig+\"-\"+s4dig;\n return newPhone;\n}", "function displayContactDetails(contact) {\n // set display\n clearDisplay();\n $(\"#detailHeading\")[0].innerHTML = contact.Name;\n $(\"#detailHeading\")[0].style.visibility = \"visible\";\n $(\"#detailOptions\")[0].style.visibility = \"visible\";\n $(\"#details\")[0].style.visibility = \"visible\";\n $(\"#editContact\")[0].addEventListener(\"click\", function () {\n editContactDetails(contact);\n });\n $(\"#deleteContact\")[0].addEventListener(\"click\", function () {\n displayDeleteContact(contact);\n });\n\n activeItem(contact.Id);\n $(\"#contactID\")[0].innerHTML = contact.Id;\n $(\"#contactSupIDInput\")[0].value = contact.SupID;\n $(\"#contactFullNameInput\")[0].value = contact.Name;\n $(\"#contactPhoneNoInput\")[0].value = contact.Phone;\n}", "function formatPhone(x){\n var areaCode = x.slice(0, 3);\n var first3 = x.slice(3, 6);\n var last4 = x.slice(6, 11);\n var phone = areaCode + \"-\" + first3 + \"-\" + last4;\n return phone;\n}", "function reformatUSPhone (USPhone)\r\n{ return (reformat (USPhone, \"(\", 3, \") \", 3, \"-\", 4))\r\n}", "function reformatUSPhone (USPhone)\r\n{ return (reformat (USPhone, \"(\", 3, \") \", 3, \"-\", 4))\r\n}", "function prepareContactDetail (customerDO) {\n\t\t\t\tvar contactDetail = {\n\t\t\t\t\t'phone1' : customerDO.phoneNumber,\n\t\t\t\t\t'email' : customerDO.email,\n\t\t\t\t\t'person' : {\n\t\t\t\t\t\t'firstName' : customerDO.firstName,\n\t\t\t\t\t\t'lastName' :customerDO.lastName\n\t\t\t\t\t},\n\t\t\t\t\t'address' : {\n\t\t\t\t\t\t'street1' : $scope.customerDO.street1,\n\t\t\t\t\t\t'city' : $scope.customerDO.city,\n\t\t\t\t\t\t'state' : $scope.customerDO.state,\n\t\t\t\t\t\t'country' : $scope.customerDO.country,\n\t\t\t\t\t\t'postalCode' : $scope.customerDO.postalCode\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\treturn contactDetail;\n\t\t\t}", "function parseContacts(response) {\n return response.rows.map(function(row) {\n return {\n lastName: row.key[0],\n otherNames: row.key[1],\n status: row.key[2],\n lga: row.value.lga,\n state: row.value.state,\n _id: row.value._id,\n daysSinceLastContact: dateParser.daysFromToday(\n row.value.dateLastContact, row.value.dateFirstVisit),\n includingDetailedInfo: false\n };\n });\n }", "function onSuccess(contacts) {\n for (var i=0; i<contacts.length; i++) {\n \n if (contacts[i].phoneNumbers != null) {\n $.each(contacts[i].phoneNumbers, function(i ,v){\n $.each(v, function(e, f){\n \n\n if (e == 'value') {\n var number = f.replace(/-|\\s/g,\"\"); \n console.log(number);\n\n }\n });\n });\n \n \n }\n\n }\n }", "function showInfo(contactID, searchCriteria) {\n \n var contInfoContainer = getElement(\"contact_info\");\n var contactFields = [\"*\"];\n var contactFindOptions = new ContactFindOptions();\n contactFindOptions.filter = searchCriteria;\n contactFindOptions.multiple = true;\n navigator.contacts.find(contactFields, contactSuccess, contactError, contactFindOptions);\n \n function contactSuccess(contacts) {\n \n contInfoContainer.innerHTML = \"\";\n for (var i = 0; i < contacts.length; i++) {\n \n if (contacts[i].id == contactID) {\n \n activeContact = contacts[i];\n \n var cNameSection = \"<div class='contactInfo'>\" +\n \"<div>\" + buildDisplayName(contacts[i]) + \"</div>\" +\n \"<div>\" + (!isEmptyOrBlank(contacts[i].nickname) ? ('\"' + contacts[i].nickname + '\"') : \"\") + \"</div>\" +\n \"</div>\";\n \n var cPhotoSection = \"<div class='contactImage'>\" +\n \"<img src='\" + \n ((contacts[i].photos && (contacts[i].photos.length > 0) && !isEmptyOrBlank(contacts[i].photos[0].value) && (contacts[i].photos[0].value.indexOf(\"//:0\") === -1)) \n ? contacts[i].photos[0].value \n : \"resources/nophoto.jpg\") + \n \"' width='50' height='50' />\" +\n \"</div>\";\n \n var cPhoneNumbersSection = \"\";\n if (contacts[i].phoneNumbers && (contacts[i].phoneNumbers.length > 0)) {\n \n var cPhoneNumbersSectionHeader = \"<div class='iSectionTitle'>Phone Numbers</div>\";\n var cPhoneNumbersSectionContent = \"\";\n for (var j = 0; j < contacts[i].phoneNumbers.length; j++) {\n if (contacts[i].phoneNumbers[j] && !isEmptyOrBlank(contacts[i].phoneNumbers[j].value)) {\n cPhoneNumbersSectionContent += \"<div class='iSectionItem'>\" +\n \"<div class='iItemType'>\" + contacts[i].phoneNumbers[j].type + \"</div>\" +\n \"<div class='iItemValue'>\" + contacts[i].phoneNumbers[j].value + \"</div>\" +\n \"</div>\";\n }\n }\n if (!isEmptyOrBlank(cPhoneNumbersSectionContent)) {\n cPhoneNumbersSection = cPhoneNumbersSectionHeader + cPhoneNumbersSectionContent;\n }\n }\n \n var cEmailsSection = \"\";\n if (contacts[i].emails && (contacts[i].emails.length > 0)) {\n \n var cEmailsSectionHeader = \"<div class='iSectionTitle'>Emails</div>\";\n var cEmailsSectionContent = \"\";\n for (var j = 0; j < contacts[i].emails.length; j++) {\n if (contacts[i].emails[j] && !isEmptyOrBlank(contacts[i].emails[j].value)) {\n cEmailsSectionContent += \"<div class='iSectionItem'>\" +\n \"<div class='iItemType'>\" + contacts[i].emails[j].type + \"</div>\" +\n \"<div class='iItemValue'>\" + contacts[i].emails[j].value + \"</div>\" +\n \"</div>\";\n }\n }\n if (!isEmptyOrBlank(cEmailsSectionContent)) {\n cEmailsSection = cEmailsSectionHeader + cEmailsSectionContent;\n }\n }\n \n var cIMsSection = \"\";\n if (contacts[i].ims && (contacts[i].ims.length > 0)) {\n \n var cIMsSectionHeader = \"<div class='iSectionTitle'>IMs</div>\";\n var cIMsSectionContent = \"\";\n \n for (var j = 0; j < contacts[i].ims.length; j++) {\n if (contacts[i].ims[j] && !isEmptyOrBlank(contacts[i].ims[j].value)) {\n cIMsSectionContent += \"<div class='iSectionItem'>\" +\n \"<div class='iItemType'>\" + contacts[i].ims[j].type + \"</div>\" +\n \"<div class='iItemValue'>\" + contacts[i].ims[j].value + \"</div>\" +\n \"</div>\";\n }\n }\n \n if (!isEmptyOrBlank(cIMsSectionContent)) {\n cIMsSection = cIMsSectionHeader + cIMsSectionContent;\n }\n }\n \n var cUrlsSection = \"\";\n if (contacts[i].urls && (contacts[i].urls.length > 0)) {\n \n var cUrlsSectionHeader = \"<div class='iSectionTitle'>Urls</div>\";\n var cUrlsSectionContent = \"\";\n \n for (var j = 0; j < contacts[i].urls.length; j++) {\n if (contacts[i].urls[j] && !isEmptyOrBlank(contacts[i].urls[j].value)) {\n cUrlsSectionContent += \"<div class='iSectionItem'>\" +\n \"<div class='iItemType'>\" + contacts[i].urls[j].type + \"</div>\" +\n \"<div class='iItemValue'>\" + contacts[i].urls[j].value + \"</div>\" +\n \"</div>\";\n }\n }\n if (!isEmptyOrBlank(cUrlsSectionContent)) {\n cUrlsSection = cUrlsSectionHeader + cUrlsSectionContent;\n }\n }\n \n var cAddressesSection = \"\";\n if (contacts[i].addresses && (contacts[i].addresses.length > 0)) {\n \n var cAddressesSectionHeader = \"<div class='iSectionTitle'>Addresses</div>\";\n var cAddressesSectionContent = \"\";\n \n for (var j = 0; j < contacts[i].addresses.length; j++) {\n if (contacts[i].addresses[j] && (!isEmptyOrBlank(contacts[i].addresses[j].streetAddress) || !isEmptyOrBlank(contacts[i].addresses[j].locality) ||\n !isEmptyOrBlank(contacts[i].addresses[j].region) || !isEmptyOrBlank(contacts[i].addresses[j].country))) {\n \n var atypeSubsection = ((!isEmptyOrBlank(contacts[i].addresses[j].type) && (contacts[i].addresses[j].type != \"undefined\")) ? (\"<div class='iItemType'>\" + contacts[i].addresses[j].type + \"</div>\") : \"\");\n var strSubsection = ((!isEmptyOrBlank(contacts[i].addresses[j].streetAddress) && (contacts[i].addresses[j].streetAddress != \"undefined\")) ? (\"<div>\" + contacts[i].addresses[j].streetAddress + \"</div>\") : \"\");\n var locSubsection = ((!isEmptyOrBlank(contacts[i].addresses[j].locality) && (contacts[i].addresses[j].locality != \"undefined\")) ? (\"<div>\" + contacts[i].addresses[j].locality + \"</div>\") : \"\");\n var regSubsection = ((!isEmptyOrBlank(contacts[i].addresses[j].region) && (contacts[i].addresses[j].region != \"undefined\")) ? contacts[i].addresses[j].region : \"\");\n var postSubsection = ((!isEmptyOrBlank(contacts[i].addresses[j].postalCode) && (contacts[i].addresses[j].postalCode != \"undefined\")) ? contacts[i].addresses[j].postalCode : \"\");\n if (regSubsection != \"\") {\n if (postSubsection != \"\") {\n regSubsection += \", \";\n }\n }\n regSubsection += postSubsection;\n var countrySubsection = ((!isEmptyOrBlank(contacts[i].addresses[j].country) && (contacts[i].addresses[j].country != \"undefined\")) ? (\"<div>\" + contacts[i].addresses[j].country + \"</div>\") : \"\");\n \n cAddressesSectionContent += \"<div class='iSectionItem'>\" +\n atypeSubsection +\n \"<div class='iItemValue'>\" + \n strSubsection +\n locSubsection +\n (\"<div>\" + regSubsection + \"</div>\") +\n countrySubsection +\n \"</div>\" +\n \"</div>\";\n }\n }\n if (!isEmptyOrBlank(cAddressesSectionContent)) {\n cAddressesSection = cAddressesSectionHeader + cAddressesSectionContent;\n }\n }\n \n var sectionHeading = \"\";\n var sectionContent = \"\";\n if (contacts[i].organizations && (contacts[i].organizations.length > 0)) {\n for (var j = 0; j < contacts[i].organizations.length; j++) {\n var typeSubsection = ((!isEmptyOrBlank(contacts[i].organizations[j].type) && (contacts[i].organizations[j].type != \"undefined\")) ? (\"<div class='iItemType'>\" + contacts[i].organizations[j].type + \"</div>\") : \"\");\n var deptSubsection = ((!isEmptyOrBlank(contacts[i].organizations[j].department) && (contacts[i].organizations[j].department != \"undefined\")) ? (contacts[i].organizations[j].department) : \"\");\n var orgSubsection = ((!isEmptyOrBlank(contacts[i].organizations[j].name) && (contacts[i].organizations[j].name != \"undefined\")) ? contacts[i].organizations[j].name : \"\");\n var orgLine = orgSubsection;\n if (deptSubsection != \"\") {\n if (orgSubsection != \"\") {\n orgLine += \", \";\n } \n orgLine += deptSubsection;\n }\n var titleSubsection = ((!isEmptyOrBlank(contacts[i].organizations[j].title)) ? (\"<div>\" + contacts[i].organizations[j].title + \"</div>\") : \"\");\n \n if ((orgLine != \"\") || (titleSubsection != \"\")) {\n sectionContent += \"<div class='iSectionItem'>\" +\n typeSubsection +\n \"<div class='iItemValue'>\" + \n (\"<div>\" + orgLine + \"</div>\") +\n titleSubsection +\n \"</div>\" +\n \"</div>\";\n }\n }\n if (!isEmptyOrBlank(sectionContent)) {\n sectionHeading = \"<div class='iSectionTitle'>Organizations</div>\";\n }\n }\n var cOrganizationsSection = sectionHeading + sectionContent;\n \n var cNoteSection = \"\";\n if (!isEmptyOrBlank(contacts[i].note)) {\n cNoteSection += \"<div class='iSectionTitle'>Note</div>\" +\n \"<div class='iSectionItem'>\" +\n \"<div class='iItemValue'>\" + contacts[i].note + \"</div>\" +\n \"</div>\";\n }\n \n contInfoContainer.innerHTML += cPhotoSection + cNameSection + cPhoneNumbersSection + cEmailsSection + \n cIMsSection + cUrlsSection + cAddressesSection + cOrganizationsSection + \n cNoteSection;\n $.mobile.changePage(\"#cont_info_page\", { transition: \"pop\" });\n break;\n }\n }\n }\n \n function contactError(contactError) {\n \n contInfoContainer.innerHTML = \"Contacts are unavailable\";\n $.mobile.changePage(\"#cont_info_page\", { transition: \"pop\" });\n }\n}", "function addDetails(contact) {\n get(contact._id)\n .then(function(response) {\n extendContact(contact, response);\n });\n }", "function Contact(jsonObject) {\n\tthis.firstName = \"\";\n\tthis.lastName = \"\";\n this.name = \"\";\n this.phones = {};\n this.emails = {};\n\tthis.address = \"\";\n}", "function formatAddress(response, index) {\n const physAddressObj = getStreetAddress(response, index);\n const addressLines = format(physAddressObj);\n return `\n ${addressLines}\n ${physAddressObj.city}, ${physAddressObj.stateCode} ${physAddressObj.postalCode}\n `;\n}", "function formatPhoneNumber(data) {\n let phoneNumberString = data['phone'];\n // returns the add student button if the space is available.\n if (phoneNumberString.includes('click')) {\n return '<button data-location=\"'+data['location']+'\" class=\"from_modal btn btn-success btn-sm\" data-toggle=\"modal\" data-target=\"#add_student_modal\">'\n + setIcons({icon_name: 'user-plus'})\n + phoneNumberString\n + '</button>';\n }\n let cleaned = ('' + phoneNumberString).replace(/\\D/g, '');\n // Blatantly took this from Stack Overflow.\n let match = cleaned.match(/^(\\d{3})(\\d{3})(\\d{4})$/);\n if (match) {\n return setIcons({icon_name: 'phone'}) + '(' + match[1] + ') ' + match[2] + '-' + match[3];\n }\n return null;\n}", "getContactDisplayName(first_name, middle_name, last_name) {\n\t var key = \"\";\n\t (first_name != \"\")? key += first_name + \" \" : key = key;\n\t (middle_name != \"\")? key += middle_name + \" \" : key = key;\n\t (last_name != \"\")? key += last_name : key = key;\n\t return key;\n\t}", "function formatPhoneText(value) {\n // replace the extra '-'\n value = value.trim().split(\"-\").join(\"\");\n\n if (value.length >= 3 && value.length < 6)\n value = value.slice(0, 3) + \"-\" + value.slice(3);\n else if (value.length >= 6)\n value = value.slice(0, 3) + \"-\" + value.slice(3, 6) + \"-\" + value.slice(6);\n\n return value;\n}", "function saveContactInfo() {\n\n $scope.savingContactInfo = true;\n $scope.contactInfoError = false;\n\n // Only save with valid input.\n if ($scope.contactInfoForm.$valid) {\n\n EventFormData.resetContactPoint();\n\n // Copy all data to the correct contactpoint property.\n for (var i = 0; i < $scope.contactInfo.length; i++) {\n if ($scope.contactInfo[i].type === 'url') {\n EventFormData.contactPoint.url.push($scope.contactInfo[i].value);\n }\n else if ($scope.contactInfo[i].type === 'phone') {\n EventFormData.contactPoint.phone.push($scope.contactInfo[i].value);\n }\n else if ($scope.contactInfo[i].type === 'email') {\n EventFormData.contactPoint.email.push($scope.contactInfo[i].value);\n }\n }\n\n var promise = eventCrud.updateContactPoint(EventFormData);\n promise.then(function() {\n controller.eventFormSaved();\n $scope.contactInfoCssClass = 'state-complete';\n $scope.savingContactInfo = false;\n }, function() {\n $scope.contactInfoError = true;\n $scope.savingContactInfo = false;\n });\n\n }\n }", "function formatAddress(addressObject) {\n if(isEmpty(addressObject.addressLine1) && isEmpty(addressObject.suburb)) {\n return '';\n }\n var str = addressObject.addressLine1 + ', ';\n if (!isEmpty(addressObject.addressLine2)) {\n str += addressObject.addressLine2 + ', ';\n }\n if (!isEmpty(addressObject.suburb)) {\n str += addressObject.suburb + ', ';\n }\n if (!isEmpty(addressObject.state)) {\n str += addressObject.state + ', ';\n }\n if (!isEmpty(addressObject.postcode)) {\n str += addressObject.postcode;\n }\n return str;\n}", "function Contact(firstName, lastName, phoneNumber, email, address, address2, city, state, zip) {\n this.firstName = firstName;\n this.lastName = lastName;\n this.phoneNumber = phoneNumber;\n this.email = email;\n this.address = address;\n this.address2 = address2\n this.city = city;\n this.state = state;\n this.zip = zip;\n}", "function onSuccess(contacts) {\n \tdocument.getElementById('contacts-output').innerHTML = \n\t\t\t \"<strong>You have \" + contacts.length + \"</strong> contacts.\";\n for (var i=0; i<contacts.length; i++) {\n \tif (contacts[i].name && contacts[i].name.formatted)\n \tdocument.getElementById('contacts-output').innerHTML = \n\t\t\tdocument.getElementById('contacts-output').innerHTML +\n console.log(\"Display Name = \" + contacts[i].displayName);\n \t//show first five contacts\n\t\t\t \"<br/>Contact \" + (i+1) + \" is <strong>\" +\n\t\t\t contacts[i].name.formatted + \"</strong>\";\n\t\t\t \"<br/>Contact \" + (i+2) + \" is <strong>\" +\n\t\t\t contacts[i].name.formatted + \"</strong>\";\n\t\t\t \"<br/>Contact \" + (i+3) + \" is <strong>\" +\n\t\t\t contacts[i].name.formatted + \"</strong>\";\n\t\t\t \"<br/>Contact \" + (i+4) + \" is <strong>\" +\n\t\t\t contacts[i].name.formatted + \"</strong>\";\n\t\t\t \"<br/>Contact \" + (i+5) + \" is <strong>\" +\n\t\t\t contacts[i].name.formatted + \"</strong>\";\n\t\t\t break;\n }\n }", "function updateContactDetailsSection()\n{\n\t// Contact Name\n\tdocument.getElementById(\"contactFullName\").innerHTML = contactArray[contactListSettings.currentContactIndex].firstName + \" \" + contactArray[contactListSettings.currentContactIndex].lastName;\n\n\t// If the Contact is a Favourite\n\tif(contactArray[contactListSettings.currentContactIndex].addToFavourites == true)\n\t{\n\t\tdocument.getElementById(\"favContactStar\").style.display = \"inline\";\n\t}\n\telse\n\t{\n\t\tdocument.getElementById(\"favContactStar\").style.display = \"none\";\n\t}\n\n\t// If Contact Has a Note\n\tif(contactArray[contactListSettings.currentContactIndex].notes.length > 0 && typeof contactArray[contactListSettings.currentContactIndex].notes !== \"undefined\")\n\t{\n\t\tdocument.getElementById(\"contactNotes\").innerHTML = contactArray[contactListSettings.currentContactIndex].notes;\n\t}\n\telse\n\t{\n\t\tdocument.getElementById(\"contactNotes\").parentNode.parentNode.style.display = \"none\";\n\t}\n\n\t// If Contact Has a Date of Birth\n\tif(contactArray[contactListSettings.currentContactIndex].dateOfBirth != false)\n\t{\n\t\t// Pass the date values into the returnReadableDateString to get back a string in the format of dd monthName yyyy\n\t\tdocument.getElementById(\"contactDateOfBirth\").innerHTML = returnReadableDateString(contactArray[contactListSettings.currentContactIndex].dateOfBirth.getDate(), contactArray[contactListSettings.currentContactIndex].dateOfBirth.getMonth(), contactArray[contactListSettings.currentContactIndex].dateOfBirth.getFullYear());\n\t}\n\telse\n\t{\n\t\t// Hide Row\n\t\tdocument.getElementById(\"contactDateOfBirth\").parentNode.parentNode.style.display = \"none\";\n\t}\n\n\t// If the Contact Has a Phone Number\n\tif(contactArray[contactListSettings.currentContactIndex].phoneNumber != \"\")\n\t{\n\t\t// Add Info to the Page\n\t\tdocument.getElementById(\"contactPhoneNumber\").innerHTML = contactArray[contactListSettings.currentContactIndex].phoneNumber;\n\n\t\t// Create Links\n\t\tdocument.getElementById(\"sendTextIcon\").setAttribute(\"href\", \"sms:\" + (contactArray[contactListSettings.currentContactIndex].phoneNumber).toString());\n\t\tdocument.getElementById(\"callPhoneNum\").setAttribute(\"href\", \"tel:\" + (contactArray[contactListSettings.currentContactIndex].phoneNumber).toString());\n\t\tdocument.getElementById(\"callPhoneIcon\").setAttribute(\"href\", \"tel:\" + (contactArray[contactListSettings.currentContactIndex].phoneNumber).toString());\n\t}\n\telse\n\t{\n\t\t// Hide Row\n\t\tdocument.getElementById(\"callPhoneIcon\").parentNode.parentNode.style.display = \"none\";\n\t}\n\n\t// If the Contact Has An Email Address\n\tif(contactArray[contactListSettings.currentContactIndex].emailAddress != \"\")\n\t{\n\t\t// Add Information to the Page\n\t\tdocument.getElementById(\"sendEmail\").innerHTML = contactArray[contactListSettings.currentContactIndex].emailAddress;\n\n\t\t// Create Links\n\t\tdocument.getElementById(\"sendEmail\").setAttribute(\"href\", \"mailto:\" + (contactArray[contactListSettings.currentContactIndex].emailAddress).toString());\n\t\tdocument.getElementById(\"sendEmailIcon\").setAttribute(\"href\", \"mailto:\" + (contactArray[contactListSettings.currentContactIndex].emailAddress).toString());\n\t}\n\telse\n\t{\n\t\t// Hide Rows\n\t\tdocument.getElementById(\"sendEmail\").parentNode.parentNode.style.display = \"none\";\n\t}\n\n}", "function makeDetailsHTML(contactObject) {\n\t\tconst location = contactObject.location;\n\t\tconst birthdate = new Date(contactObject.dob.date);\n\t\tlet html = `\n\t\t\t<span class=\"close\">&times;</span>\n\t\t\t<div class=\"avatar-div\">\n\t\t\t\t<img src=\"${contactObject.picture.large}\" class=\"avatar\" height=\"175\" width=\"175\">\n\t\t\t</div>\n\t\t\t<div class=\"contact-summary\">\n\t\t\t\t<h3>${contactObject.name.first} ${contactObject.name.last}</h3>\n\t\t\t\t<p class=\"username\">${contactObject.login.username}</p>\n\t\t\t\t<p>${contactObject.email}</p>\n\t\t\t\t<p class=\"location\">${contactObject.location.city}</p>\n\t\t\t</div>\n\t\t\t<hr>\n\t\t\t<div class=\"additional-details\">\n\t\t\t\t<p>${contactObject.cell}</p>\n\t\t\t\t<p class=\"address\">${location.street} \n\t\t\t\t<br>${location.city}, ${location.state} ${location.city} ${location.postalcode}</p>\n\t\t\t\t<p>Birthday: ${birthdate.toLocaleDateString(\"en-US\")}</p>\n\t\t\t</div>\n\t\t`;\n\t\tif (hasPrevious(contactObject.id)) {\n\t\t\thtml += `<div id=\"previous\" class=\"button\" display=\"inline-block\">&#8249;</div>`;\n\t\t}\n\t\tif (hasNext(contactObject.id)) {\n\t\t\thtml += `<div id=\"next\" class=\"button\" display=\"inline-block\">&#8250;</div>`;\n\t\t}\n\t\treturn html;\n\t}", "function SaveUpdatedContactToPhonebook()\n{\n\tTi.API.info(\"SaveUpdatedContactToPhonebook\");\n\t\n\t// TODO: Replace this with return statement\n\tif(contact == null) alert(\"Contact must be initialized ya beheema !\");\n\t\n\tif(OS_IOS) {\n\t\tTitanium.Contacts.save();\n\t} \n\telse if(OS_ANDROID) {\n\t\t/* Titanium APIs or Android OS has a bug, which is saving a contact after editing it causes another contact got edited.\n\t\t * A workaround is to delete the exisiting contact with id and then add a new contact having each and every detail the\n\t\t * deleted contact had.\n\t\t */\n\t\t\n\t\tTitanium.Contacts.removePerson(contact);\n\t\t\n\t\tTi.Contacts.createPerson({\n\t\t\taddress : contact.address ? contact.address : null,\t// Dictionary\n\t\t\tbirthday : contact.birthday ? contact.birthday : \"\",\t// String\n\t\t\tdate : contact.date ? contact.date : null,\t// Dictionary\n\t\t\temail : contact.email ? contact.email : null,\t// Dictionary\n\t\t\tfirstName : contact.firstName ? contact.firstName : contact.fullName ? contact.fullName : \"\",\t// String\n\t\t\t// TODO: The image is not copied\n\t\t\timage : contact.image ? contact.image : null,\t// Image blob\n\t\t\t\n\t\t\tinstantMessage : contact.instantMessage ? contact.instantMessage : null,\t// Dictionary\n\t\t\tkind : Ti.Contacts.CONTACTS_KIND_PERSON,\n\t\t\tlastName : contact.lastName ? contact.lastName : \"\",\t// String\n\t\t\tmiddleName : contact.middleName ? contact.middleName : \"\",\t// String\n\t\t\tnickname : contact.nickname ? contact.nickname : \"\",\t// String\n\t\t\tnote : contact.note ? contact.note : \"\",\t// String\n\t\t\torganization : contact.organization ? contact.organization : \"\",\t// String\n\t\t\tphone : contact.phone ? contact.phone : null,\t// Dictionary\n\t\t\trelatedNames : contact.relatedNames ? contact.relatedNames : null,\t// Dictionary\n\t\t\turl : contact.url ? contact.url : null,\t// Dictionary\n\t\t});\n\t}\n\t\n\tcontact = null;\t// To avoid wrong use in future.\n\talert(\"Contact Updated in Phonebook !\");\n}", "function formatAddresses() {\n var output = ss.getSheetByName(\"Formatted Addresses\");\n var values = input.getDataRange().getValues();\n var name = values[0].indexOf(\"NAME\");\n var street1 = values[0].indexOf(\"Street\");\n var street2 = values[0].indexOf(\"Street #2\");\n var city = values[0].indexOf(\"CITY\");\n var state = values[0].indexOf(\"STATE\");\n var zip = values[0].indexOf(\"ZIP\");\n var destRange = output.getDataRange();\n destRange.clear();\n var nameArr = [];\n var stArr = [];\n var cityArr = [];\n var stackedAddress = [];\n\n values.filter (function (row) {\n return (row[name] !== \"\");\n })\n .forEach(function (row) {\n nameArr.push(row[name]);\n if(row[street2] !== \"\") {\n stArr.push(row[street1] + \" \" + row[street2]);\n }\n else {\n stArr.push(row[street1]);\n };\n cityArr.push(row[city] + \", \" + row[state] + \" \" + row[zip]);\n });\n stackedAddress.push([nameArr],[stArr], [cityArr]);\n var nameRange = output.getRange(1, 1, 1, stackedAddress[0][0].length);\n var stRange = output.getRange(2, 1, 1, stackedAddress[0][0].length);\n var cityRange = output.getRange(3, 1, 1, stackedAddress[0][0].length);\n nameRange.setValues(stackedAddress[0]);\n stRange.setValues(stackedAddress[1]);\n cityRange.setValues(stackedAddress[2]);\n}", "function toRenderContactView() {\n ContactView.render({\n model: contact,\n bindings: bindings\n });\n }", "function onSaveContact(e) {\n \n var toSave;\n if (activeContact) {\n toSave = activeContact;\n } else {\n toSave = navigator.contacts.create();\n }\n \n // name saving:\n initName();\n \n // nickname saving:\n toSave.nickname = contactForm.getNickname();\n \n // phones saving:\n initContactFieldVals(\"phoneNumbers\", contactForm.getPhoneNumbers());\n \n // emails saving:\n initContactFieldVals(\"emails\", contactForm.getEmails());\n \n // ims saving:\n initContactFieldVals(\"ims\", contactForm.getIMs());\n \n // urls saving:\n initContactFieldVals(\"urls\", contactForm.getURLs());\n \n // addresses saving:\n initContactFieldVals(\"addresses\", contactForm.getAddresses());\n \n // organizations saving:\n initContactFieldVals(\"organizations\", contactForm.getOrganizations());\n \n // note saving:\n var note = contactForm.getNote();\n if (!isEmptyOrBlank(note)) {\n toSave.note = note;\n }\n \n // photo saving:\n initContactFieldVals(\"photos\", contactForm.getPhotos());\n \n toSave.save(onSuccess,onError);\n \n function onSuccess(contact) {\n alert(\"The contact was successfully saved\");\n displContactList.updateList();\n $.mobile.changePage(\"#cont_list_page\", { transition: \"pop\" });\n };\n\n function onError(contactError) {\n alert(\"The contact cannot be saved: error: \" + contactError.code);\n };\n \n function initName() {\n \n if (!toSave.name) {\n toSave.name = new ContactName();\n }\n var nameData = contactForm.getNames();\n toSave.name.givenName = nameData.givenName;\n toSave.name.familyName = nameData.familyName;\n toSave.name.middleName = nameData.middleName;\n toSave.name.honorificPrefix = nameData.honorificPrefix;\n toSave.name.honorificSuffix = nameData.honorificSuffix;\n };\n \n function initContactFieldVals(contactFieldName, contactFieldValsArray) {\n \n if (!toSave[contactFieldName] && (contactFieldValsArray.length > 0)) {\n toSave[contactFieldName] = [];\n } \n for (var i = 0; i < contactFieldValsArray.length; i++) {\n if (!toSave[contactFieldName][i]) {\n if (contactFieldName == \"addresses\") {\n toSave[contactFieldName][i] = new ContactAddress();\n } else if (contactFieldName == \"organizations\") {\n toSave[contactFieldName][i] = new ContactOrganization();\n } else {\n toSave[contactFieldName][i] = new ContactField();\n }\n }\n for (var key in contactFieldValsArray[i]) {\n toSave[contactFieldName][i][key] = contactFieldValsArray[i][key];\n }\n }\n if (toSave[contactFieldName]) {\n for (var i = contactFieldValsArray.length; i < toSave[contactFieldName].length; i++) {\n if (toSave[contactFieldName][i]) {\n for (var key in toSave[contactFieldName][i]) {\n if (key.toLowerCase() != \"id\") {\n toSave[contactFieldName][i][key] = \"\";\n }\n }\n }\n }\n }\n };\n}", "fillContactFields(contactData) {\n this.fillContactWithAllFieldsAndSave(this.contactInformation, contactData);\n }", "function saveContact(){\n\n saveButton.style.display = 'none';\n cancelButton.style.display = 'none';\n\n var email = document.getElementById('emailBlock').getElementsByTagName('input')[0];\n var phone = document.getElementById('phoneBlock').getElementsByTagName('input')[0];\n var im = document.getElementById('imBlock').getElementsByTagName('input')[0];\n var address = document.getElementById('addressBlock').getElementsByTagName('input')[0];\n var url = document.getElementById('urlBlock').getElementsByTagName('input')[0];\n var other = document.getElementById('otherBlock').getElementsByTagName('input')[0];\n var name = document.getElementById('selctedContactName');\n\n name = name.value.split(' ')\n\n //a temp object to save the details.\n\n var tempContactObj = {\n \"name\":{'first':name[1],'last':name[2],'title':name[0]},\n \"dob\": other.value,\n \"email\" : email.value,\n \"cell\" : phone.value,\n \"login\" : im.value,\n \"picture\" : {'large':'img/noImage.png','medium':'img/noImage.png','thumbnail':'img/noImage.png'},\n \"location\" : address.value,\n \"url\" : url.value\n }\n\n USER_ARRAY.push(new Contact(tempContactObj));\n USER_ARRAY.sort(compareFirstName);\n generateList();\n\n\n // Rest the body after saving the contact.\n resetBody();\n}", "tostring() {\n return \"First Name :\" + this.first_Name + \", \\n Name :\" + this.last_Name + \",\\nCity : \" + this.city + \",\\nState : \" + this.state + \", \\n Zip : \" + this.zip + \", \\n Phone Number : \" + this.phone_Number + \", \\nEmail : \" + this.email;\n}", "getContactInfo(e) {\r\n Contact.clickedContact = Number(\r\n e.currentTarget.getAttribute(\"data-contactNumber\")\r\n );\r\n console.log(Contact.clickedContact);\r\n document.querySelector(\"#name\").value =\r\n Contact.list[Contact.clickedContact].name;\r\n document.querySelector(\"#phone\").value =\r\n Contact.list[Contact.clickedContact].phone_number;\r\n document.querySelector(\"#website\").value =\r\n Contact.list[Contact.clickedContact].website;\r\n document.querySelector(\"#description\").value =\r\n Contact.list[Contact.clickedContact].description;\r\n UI.openForm(\"update\");\r\n saveContactButton.textContent = \"update\";\r\n deleteContactButton.style.display = \"block\";\r\n }", "function handleUpdate(contact,event) {\n contact.name = event.detail.name;\n setContacts(contacts);\n }", "function formatCitationData(citationData) {\r\n const getField = field => (citationData[field] || '').trim() // safe access which wont return undefined\r\n const dateInfo = new Date().toDateString().split(' ')\r\n switch (getField('format') || 'MLA') {\r\n default:\r\n return `${getField('Authors')}.` +\r\n ` \"${getField('Title')}.\"` +\r\n ` _${getField('Container')}_,` +\r\n ` ${getField('Publish Date')},` +\r\n ` ${getField('Reference')}. Accessed ${+dateInfo[2]} ${dateInfo[1]} ${dateInfo[3]}.`\r\n }\r\n}", "function formatAddress(address) {\n if (conf.hasOwnProperty(address)) {\n if (conf[address].hasOwnProperty('nickname')) {\n return conf[address]['nickname'] + \":\" + address;\n }\n }\n return address;\n}", "function Contact() {\n\n this.name = '';\n this.gender = '';\n this.dateOfBirth = null;\n }", "function formatPhoneNumber(value) {\n\tvar format = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'National';\n\n\treturn (0, _custom.formatNumber)(value, format, _metadataMin2.default);\n}", "function makeContactHTML(contactObject) {\n\t\tif (contactObject.filteredFor) {\n\t\tlet html = `\n\t\t\t<div id=\"${contactObject.id}\" class=\"contact\">\n\t\t\t\t<div class=\"thumb-div\">\n\t\t\t\t\t<img src=\"${contactObject.picture.large}\" class=\"thumbnail\">\n\t\t\t\t</div>\n\t\t\t\t<div class=\"contact-summary\">\n\t\t\t\t\t<h3>${contactObject.name.first} ${contactObject.name.last}</h3>\n\t\t\t\t\t<p>${contactObject.email}</p>\n\t\t\t\t\t<p class=\"location\">${contactObject.location.city}</p>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t`;\n\t\treturn html;\n\t\t}\n\t}", "function createContact(name,phoneNumber){\n\n}", "function formatarFone(foneentrada) {\n //Coloca os telefones no formato XX XXXX XXXX ou XX XXXXX XXXX (para DDD 11)\n var fone = foneentrada.replace(/[^\\d]+/g,'');\n\n if (fone.length > 10) {\n if (fone.substring(0,2) == \"55\") {\n fone = fone.substring(2,fone.length);\n }\n if (fone.substring(0,1) == \"0\") {\n fone = fone.substring(1,fone.length);\n }\n return fone.substring(0,fone.length-8) + \" \" + fone.substring(fone.length-8,fone.length-4) + \" \" + fone.substring(fone.length-4);\n\n } else if (fone.length == 10) {\n return fone.substring(0,fone.length-8) + \" \" + fone.substring(fone.length-8,fone.length-4) + \" \" + fone.substring(fone.length-4);\n } else if (fone.length == 8) {\n return \"XX \" + fone.substring(0,fone.length-4) + \" \" + fone.substring(fone.length-4);\n } else if (fone.length == 0) {\n return \"\";\n } else {\n return \"Telefone pendente: \" + foneentrada;\n }\n}", "function contact_title(input){\r\n\tvar result = new Object();\r\n\tvar error;\r\n\tresult.flgname = [];\r\n\tresult.flgs = [];\r\n\tresult.flgvalue = [];\r\n\tresult.flgmsg = [];\r\n\tresult.pass = true;\t\r\n\tif (!check_allowed_char(input, \"alphabetic\", \"conf1\")){\r\n\t\terror = \"E40_1\"\r\n\t\tresult.flgname.push(flags[error].name);\r\n\t\tresult.flgs.push(flags[error].flag);\r\n\t\tresult.flgvalue.push(flags[error].value);\r\n\t\tresult.flgmsg.push(flags[error].msg);\r\n\t\t}\r\n\tif (!presence_check(input)){\r\n\t\terror = \"E40_2\"\r\n\t\tresult.flgname.push(flags[error].name);\r\n\t\tresult.flgs.push(flags[error].flag);\r\n\t\tresult.flgvalue.push(flags[error].value);\r\n\t\tresult.flgmsg.push(flags[error].msg);\r\n\t\t}\t\r\n\tif (result.flgname.length>0){\r\n\t\tresult.pass = false;\r\n\t}\r\n\treturn result;\r\n}", "function formatPhone(phone) {\n var str = String(phone).replace(/ /g, '');\n str = str.replace(/O/g, '0');\n str = str.replace(/-/g, '');\n return str;\n}", "function print_contact_list(list)\n\t {\t \n\t\t console.log(\"print_contact_list\");\n\t //clean then write\n\t document.getElementById('contactList1').innerHTML = \"\";\t \n\t if (list.length > 0)\n\t {\n\t for ( var i = 0; i < list.length; i++)\n\t {\n\t console.log(\"list=\" ,list[i]);\n\t var contactString = \" <b>Display Name: </b>\";\n\t var displayName = (list[i].displayName == \"\" ? \"<b>Anonymous</b>\" :list[i].displayName );\n\t contactString += displayName +\"<br>\";\n\t //onclick='setPage(\\\"person.html\\\")\\'\n\t contactString += ((list[i].nickname == undefined || list[i].nickname == \"\") ? \"\" : \"<b>Nickname: </b>\" +\n\t list[i].nickname + \"<br>\");\n\t //name\n\t contactString += (list[i].name.formatted == \"\" ? \"<b>Anonymous</b></br>\" : \"<b>Name: </b>\" +\n\t list[i].name.formatted + \"<br>\");\n\n\t if ((list[i].emails instanceof Array) && list[i].emails.length > 0)\n\t {\n\t contactString += \"<b>Emails:</b><br>\";\n\t for ( var j = 0; j < list[i].emails.length; j++)\n\t contactString += \"&nbsp;&nbsp;\" + (list[i].emails[j].pref ? \"* \" : \"&nbsp;&nbsp;\") +\n\t list[i].emails[j].type + \": <a href=\\\"mailto:\" + list[i].emails[j].value + \"\\\">\" +\n\t list[i].emails[j].value + \"</a><br>\";\n\t }\n\t if ((list[i].addresses instanceof Array) && list[i].addresses.length > 0)\n\t {\n\t contactString += \"<b>Addresses:</b><br>\";\n\t for ( var j = 0; j < list[i].addresses.length; j++)\n\t contactString += \"&nbsp;&nbsp;\" + (list[i].addresses[j].pref ? \"* \" : \"&nbsp;&nbsp;\") +\n\t (list[i].addresses[j].type == \"\" ? \"other\" : list[i].addresses[j].type) + \": \" +\n\t list[i].addresses[j].formatted + \"<br>\";\n\t }\n\t if ((list[i].phoneNumbers instanceof Array) && list[i].phoneNumbers.length > 0)\n\t {\n\t contactString += \"<b>Phones:</b><br>\";\n\t for ( var j = 0; j < list[i].phoneNumbers.length; j++)\n\t contactString += \"&nbsp;&nbsp;\" + (list[i].phoneNumbers[j].pref ? \"* \" : \"&nbsp;&nbsp;\") +\n\t list[i].phoneNumbers[j].type + \": \" + list[i].phoneNumbers[j].value + \"<br>\";\n\t }\n\t if ((list[i].ims instanceof Array) && list[i].ims.length > 0)\n\t {\n\t contactString += \"<b>Messengers:</b><br>\";\n\t for ( var j = 0; j < list[i].ims.length; j++)\n\t contactString += \"&nbsp;&nbsp;\" + (list[i].ims[j].pref ? \"* \" : \"&nbsp;&nbsp;\") + list[i].ims[j].type +\n\t \": \" + list[i].ims[j].value + \"<br>\";\n\t }\n\t if ((list[i].organizations instanceof Array) && list[i].organizations.length > 0)\n\t {\n\t contactString += \"<b>Organizations:</b><br>\";\n\t for ( var j = 0; j < list[i].organizations.length && list[i].organizations[j].name != undefined; j++)\n\t contactString += \"&nbsp;&nbsp;\" + (list[i].organizations[j].pref ? \"* \" : \"&nbsp;&nbsp;\") +\n\t list[i].organizations[j].type + \": \" + list[i].organizations[j].name + \"<br>\";\n\t }\n\t console.log(\"Photoes=\" + list[i].photos);\n\n\t if ((list[i].photos instanceof Array) && list[i].photos.length > 0)\n\t {\n\t contactString += \"<b>Picture:</b><br>\";\n\t for ( var j = 0; j < list[i].photos.length; j++)\n\t {\n\t if(list[i].photos[j].type==\"file\") //is base64 string\n\t contactString += \"<img src=\\\"data:image/png;base64,\" + list[i].photos[j].value+\"\\\" alt=\\\"Image\\\"><br>\";\n\n\t else if(list[i].photos[j].type == \"url\") //is an URL\n\t contactString += \"<img src=\\\"\" + list[i].photos[j].value + \"\\\" alt=\\\"Image\\\"><br>\";\n\n\t //TODO: quick and dirty solution for android issue. Photos arrays starts as array and get here as object\n\t else { //if (/*(list[i].photos instanceof Object) &&*/ list[i].photos.value) {\n\t var photo = list[i].photos[j].value;\n\t contactString += \"<img alt=\\\"Image\\\" , src=\\\"data:image\\/png;base64, \" + photo + \"\\\" /><br>\";\n\t }\n\t }\n\t }\n\n\t if ((list[i].urls instanceof Array) && list[i].urls.length > 0)\n\t {\n\t contactString += \"<b>Websites:</b><br>\";\n\t for ( var j = 0; j < list[i].urls.length; j++)\n\t contactString += \"&nbsp;&nbsp;\" + (list[i].urls[j].pref ? \"* \" : \"&nbsp;&nbsp;\") + list[i].urls[j].type +\n\t \": <a href=\\\"\" + list[i].urls[j].value + \"\\\">\" + list[i].urls[j].value + \"</a><br>\";\n\t }\n\n\t contactString += \"<br>\";\n\t $('#contactList1').append(contactString);\n\t console.log(\"HERE!!!\");\n\t // console.log(\"contactList1\", $('#contactList1'));\n\t // document.getElementById('contactList1').innerHTML = contactString;\n\t //$('#contactList1').append(\"<br>\");\n\t } \n\t }\n\t else\n\t $('#contactList1').append(\"<font color='#FF0000'><b>NO CONTACTS!</b></font>\");\n\t }", "function contact_title(input){\r\n\tvar result = new Object();\r\n\tvar error;\r\n\tresult.flgname = [];\r\n\tresult.flgflag = [];\r\n\tresult.flgvalue = [];\r\n\tresult.flgmsg = [];\r\n\tresult.pass = true;\r\n\t\r\n\tif (!check_allowed_char(input, \"alphabetic\", \"conf1\")){\r\n\t\terror = \"E40_1\"\r\n\t\tresult.flgname.push(flags[error].name);\r\n\t\tresult.flgflag.push(flags[error].flag);\r\n\t\tresult.flgvalue.push(flags[error].value);\r\n\t\tresult.flgmsg.push(flags[error].msg);\r\n\t\t}\r\n\tif (!presence_check(input)){\r\n\t\terror = \"E40_2\"\r\n\t\tresult.flgname.push(flags[error].name);\r\n\t\tresult.flgflag.push(flags[error].flag);\r\n\t\tresult.flgvalue.push(flags[error].value);\r\n\t\tresult.flgmsg.push(flags[error].msg);\r\n\t\t}\r\n\t\r\n\tif (result.flgname.length>0){\r\n\t\tresult.pass = false;\r\n\t}\r\n\treturn result;\r\n}", "function makeContactList() {\n /*\n * You need something here to hold contacts. See length api for a hint:\n */\n var contacts = [];\n \n return {\n // we implemented the length api for you //\n length: function() {\n return contacts.length;\n },\n addContact: function(contact) {\n contacts.push(contact);\n return contacts;\n },\n findContact: function(fullName) {\n for (var i = 0; i < contacts.length; i++) {\n if (fullName === contacts[i].nameFirst + \" \" + contacts[i].nameLast) { return contacts[i];\n } else {\n return undefined;\n } \n }\n },\n removeContact: function(contact) {\n for (var i = 0; i < contacts.length; i++) {\n if (contacts[i] === contact) {\n contacts.splice(i, 1);\n }\n }\n \n }, printAllContactNames: function() {\n var returnedNames = \" \";\n for (var i = 0; i < contacts.length; i++) {\n returnedNames += \"\\n\" + contacts[i].nameFirst + \" \" + contacts[i].nameLast; \n } return returnedNames.trim();\n }\n \n };\n \n \n }", "function load_contact(data) {\n // contact_item is a list of attribute name:\n // ['address', 'phone', 'email', 'city', 'suburb']\n for (const item of contact_item) {\n let p = item.getElementsByTagName('p')[0];\n addr[p.id] = data[p.id];\n p.innerHTML = data[p.id];\n }\n}", "function showContactInfo(results) {\n $('#email').toggle();\n $('#phone-num').toggle();\n $('#company').toggle();\n $('#notes').toggle();\n $('#edit-fields').toggle();\n $('#contactEvents').toggle();\n $('#toggleEditButton').toggle();\n $('#contactEmail').html(results.email);\n $('#contactPhone').html(results.phone);\n $('#contactCompany').html(results.company);\n $('#contactNotes').html(results.notes);\n}", "function fields() {\n personal_data = {\n 'my_name': ['Tim Booher'],\n 'grade': ['O-5'],\n 'ssn': ['111-22-2222'],\n 'address_and_street': ['200 E Dudley Ave'],\n 'b CITY': ['Westfield'],\n 'c STATE': ['NJ'],\n 'daytime_tel_num': ['732-575-0226'],\n 'travel_order_auth_number': ['7357642'],\n 'org_and_station': ['US CYBER JQ FFD11, MOFFETT FLD, CA'],\n 'e EMAIL ADDRESS': ['[email protected]'],\n 'eft': ['X'],\n 'tdy': ['X'],\n 'house_hold_goodies': ['X'],\n 'the_year': ['2018']\n }\n trip_data = { 'a DATERow3_2': ['07/19'], 'reason1': ['AT'], 'a DATERow5_2': ['07/19'], 'reason2': ['AT'], 'reason3': ['TD'], 'a DATERow7_2': ['07/21'], 'a DATERow9_2': ['07/15'], 'b NATURE OF EXPENSERow81': ['Capital Bikeshare'], 'a DATERow1_2': ['07/15'], 'b NATURE OF EXPENSERow41': ['Travel from summit to BOS'], 'b NATURE OF EXPENSERow1': ['Travel from IAD to Hotel'], 'from1': ['07/15'], 'to2': ['07/15'], 'to1': ['07/15'], 'from4': ['07/19'], 'to4': ['07/19'], 'to3': ['07/19'], 'from5': ['07/21'], 'from2': ['07/15'], 'to6': ['07/21'], 'from3': ['07/19'], 'to5': ['07/21'], 'reason4': ['TD'], 'reason5': ['AT'], 'from6': ['07/21'], 'reason6': ['MC'], 'c AMOUNTRow8': ['25.0'], 'c AMOUNTRow7': ['45.46'], 'c AMOUNTRow6': ['11.56'], 'c AMOUNTRow5': ['38.86'], 'c AMOUNTRow9': ['23.0'], 'b NATURE OF EXPENSERow7': ['Travel from EWR to HOR'], 'b NATURE OF EXPENSERow3': ['Travel between meetings'], 'a DATERow10_2': ['07/18'], 'c AMOUNTRow4': ['28.4'], 'c AMOUNTRow3': ['21.1'], 'c AMOUNTRow2': ['23.77'], 'c AMOUNTRow1': ['43.5'], 'mode6': ['CA'], 'a DATERow2_2': ['07/15'], 'mode5': ['CP'], 'mode4': ['CP'], 'a DATERow4_2': ['07/19'], 'mode3': ['CP'], 'ardep6': ['HOR'], 'a DATERow6_2': ['07/19'], 'a DATERow8_2': ['07/21'], 'b NATURE OF EXPENSERow6': ['Travel from hotel to IAD'], 'ardep1': ['EWR'], 'd ALLOWEDRow10': ['6.25'], 'b NATURE OF EXPENSERow2': ['Travel from BOS to Meeting'], 'ardep5': ['EWR'], 'ardep4': ['Arlington VA'], 'ardep3': ['BOS'], 'ardep2': ['Arlington VA'], 'c AMOUNTRow10': ['6.25'], 'mode2': ['CP'], 'mode1': ['CA'], 'b NATURE OF EXPENSERow9': ['Metro'], 'b NATURE OF EXPENSERow5': ['Travel from hotel to DCA'], 'd ALLOWEDRow1': ['43.5'], 'b NATURE OF EXPENSERow1': ['Travel from HOR to EWR'], 'd ALLOWEDRow3': ['21.1'], 'd ALLOWEDRow2': ['23.77'], 'd ALLOWEDRow5': ['38.86'], 'd ALLOWEDRow4': ['28.4'], 'd ALLOWEDRow7': ['45.46'], 'd ALLOWEDRow6': ['11.56'], 'd ALLOWEDRow9': ['23.0'], 'd ALLOWEDRow8': ['25.0'] }\n return Object.assign({}, personal_data, trip_data);\n}", "onChange(contactInfo) {\n if (this.props.onChange) {\n // Set default values for the event (not present or visible in the form or ever changed,\n // so no need to represent these within the state).\n const value = {\n type: 'contactInfo',\n ...(contactInfo || {})\n };\n this.props.onChange((0, _event.createEvent)('change', {\n name: this.props.name || '',\n value\n }));\n }\n }", "function Contact(firstName, lastName, phoneNumber, emailAddress, address) {\n this.firstName = firstName;\n this.lastName = lastName;\n this.phoneNumber = phoneNumber;\n this.addresses = {};\n}", "function _formatBorrower(state, activeReservation) {\n if (state === 'available') {\n return {\n name: 'N/A',\n color: 'checkit-text'\n };\n } else if (activeReservation) { //if this device is reserved\n var borrower = activeReservation.borrower;\n if (borrower.name.first === 'You') {\n return {\n name: 'You',\n color: 'owner-text'\n };\n } else if (vm.isAdmin) {\n return {\n name: borrower.name.first + ' ' +\n borrower.name.last,\n color: 'owner-text'\n };\n } else {\n return {\n name: borrower.name.first + ' ' +\n borrower.name.last,\n color: 'dangerzone' // Not current user, so text is red\n };\n }\n }\n }", "function Contact(values) {\r\n\t\tvalues = values || {};\r\n\t\tthis.id = values.id || generateGUID();\r\n\t\tthis.picguid = values.picguid;\r\n\t\tthis.createdOn = values.createdOn || new Date();\r\n\r\n\t\tthis.nombre = values.nombre || '';\r\n\t\tthis.apellidos = values.apellidos || '';\r\n\t\tthis.cargo = values.cargo || '';\r\n\t\tthis.entidad = values.entidad || '';\r\n\t\tthis.telf = values.telf || '';\r\n\t\tthis.email1 = values.email1 || '';\r\n\t\tthis.city = values.city || '';\r\n\t\tthis.isFavorite = values.isFavorite || false;\r\n }//fin objeto contact", "toString() \n {\n return \"\\nfirstName='\" + this.firstName + '\\'' +\n \", \\nlastName='\" + this.lastName + '\\'' +\n \", \\naddress='\" + this.address + '\\'' +\n \", \\ncity='\" + this.city + '\\'' +\n \", \\nstate='\" + this.state + '\\'' +\n \", \\nzipCode='\" + this.zip + '\\'' +\n \", \\nemail='\" + this.email + '\\'' +\n \", \\nphoneNumber='\" + this.phoneNumber;\n }", "function formatData(data) {\n let address = buildAddress([data.house, data.street, data.suburb, data.town]);\n let obj = {photo: data.photo, roadid: data.roadid, erp: data.erp, footpathid: data.footpathid, \n side: data.side, latitude: data.latitude, longitude: data.longitude, dist: data.dist, address: address, ramm: data.ramm};\n return obj;\n}", "formatAddresses(recipients){\n\t\treturn recipients.map(({ email }) => {\n\t\t\treturn new helper.Email(email);\n\t\t});\n\t}", "formatAddresses(recipients) {\n return recipients.map(({ email }) => {\n return new helper.Email(email);\n });\n }", "function formatPhoneNumber( fieldOrValue, displayName) \n {\n if ( fieldOrValue==UNDEFINED ) return(fieldOrValue);\n \n s = (fieldOrValue.value==UNDEFINED) ? (\"\"+fieldOrValue) : fieldOrValue.value;\n if ( s.length==0 ) return(s); \n s = s.replace(/[^\\d]*/gi,\"\"); // strip out all non-digits before imposing the mask\n s = (s.length>9) ? s.replace(/^([\\d]{3})([\\d]{3})([\\d]{4})([\\d]*)$/gi,\"$1-$2-$3\").replace(/[ex]$/,\"\") : PHONEMASK;\n\n if (s==PHONEMASK)\n {\n\t\tvar tempDispName='';\n\t\tif (displayName.length==0)\n\t\t{\n\t\t\ttempDispName=fieldOrValue.name;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttempDispName=displayName;\n\t\t}\n\t \talert(\"Please check the \"+ tempDispName + \" #\" );\n\t \ts=fieldOrValue.value; \n\t \tfieldOrValue.focus();\n }\n return( (fieldOrValue.value==UNDEFINED) ? fieldOrValue=s : fieldOrValue.value=s );\n }", "function searchByCity(contact) {\n return contact.city + \" \" + contact.firstName + \" \" + contact.lastName;\n }", "function customerInfo(name,cardNum){\n var firstLetter = name.slice(0,1).toUpperCase();\n var restOfName = name.slice(1).replaceAll(/[a-zA-Z]/gi,'*');\n var specialChars = '\\n************';\n var last4Digits = cardNum.slice(12,16);\n return ( firstLetter + restOfName + specialChars + last4Digits);\n }", "handleCChange() {\n let fnamec = document.getElementById(\"fname\")\n let lnamec = document.getElementById(\"lname\")\n let typec = document.getElementById(\"contacttype\")\n let phonec = document.getElementById(\"phone\")\n let emailc = document.getElementById(\"email\")\n let fnamec2 = document.getElementById(\"fname2\")\n let lnamec2 = document.getElementById(\"lname2\")\n let typec2 = document.getElementById(\"contacttype2\")\n let phonec2 = document.getElementById(\"phone2\")\n let emailc2 = document.getElementById(\"email2\")\n let contact = {...this.state.contact}\n \n if (typec2.value.length !== 0 || fnamec2.value.length !== 0 || lnamec2.value.length !== 0 || phonec2.value.length !== 0 || emailc2.value.length !== 0)\n {\n contact = [{firstName: fnamec.value,\n lastName: lnamec.value, \n type: typec.value, \n phone: phonec.value, \n email: emailc.value},\n\n {\n firstName: fnamec2.value,\n lastName: lnamec2.value, \n type: typec2.value, \n phone: phonec2.value, \n email: emailc2.value}]\n } else{\n contact = [{firstName: fnamec.value,\n lastName: lnamec.value, \n type: typec.value, \n phone: phonec.value, \n email: emailc.value}]\n }\n \n this.setState({contact}); \n }", "format() {\n return `${this.recipient} is owed #${this.amount} for ${this.details}`;\n }", "function formatObject () {\n\tfor (var i = 0; i < newData.length; i++) {\n\t\tnewData[i].name = preparingObj(newData[i].name);\n\t\tnewData[i].description = preparingObj(newData[i].description);\n\t\tnewData[i].date = formatDate(newData[i].date);\n\t}\n}", "function Contact(label, value) {\n this.label = label;\n this.value = value;\n}", "function formatAddressComponent(component) {\n let formattedComponent = component.replace(/[-_]/g, \" \");\n\n // Capitalize the first letter of each word\n const componentWords = formattedComponent.toLowerCase().split(\" \");\n formattedComponent = componentWords.map((word) => {\n return word.charAt(0).toUpperCase() + word.substring(1);\n }).join(' ');\n\n return formattedComponent;\n }", "function formatPhoneNumber(s) {\n var s2 = (\"\"+s).replace(/\\D/g, '');\n var m = s2.match(/^(\\d{3})(\\d{3})(\\d{4})$/);\n return (!m) ? null : \"\" + m[1] + \"\" + m[2] + \"\" + m[3];\n}", "function processPersonDetails(response){\n if(response.birthday !== undefined && response.birthday !== null){\n p_details['birthday'] = 'Birth: ' + response.birthday;\n }\n if(response.place_of_birth !== undefined && response.place_of_birth !== null){\n p_details['birth_place'] = 'Birth Place: ' + response.place_of_birth;\n }\n if(response.gender !== undefined && response.gender !== null){\n p_gender = \"Undefined\";\n if(response.gender === 1){\n p_gender = \"Female\";\n }\n if(response.gender === 2){\n p_gender = \"Male\";\n }\n p_details['gender'] = 'Gender: ' + p_gender;\n }\n if(response.known_for_department !== undefined && response.known_for_department !== null){\n p_details['known_for'] = 'Known for: ' + response.known_for_department;\n }\n if(response.name !== undefined && response.name !== null){\n p_details['name'] = response.name;\n }\n if(response.homepage !== undefined && response.homepage !== null){\n p_details['homepage'] = response.homepage;\n }\n if(response.also_known_as !== undefined && response.also_known_as !== null){\n if(response.also_known_as.length > 0){\n p_details['also_known_as'] = 'Also Known as: ' + response.also_known_as.join(\",\");\n }\n }\n if(response.biography !== undefined && response.biography !== null){\n p_details['biography'] = response.biography;\n }\n return p_details;\n}", "function formatEntryString(obj) {\n\n let dateStr;\n obj.date != '' ? dateStr = `<b style=\"font-size: 20px;\">${obj.date}</b>` : dateStr = '';\n\n return `${dateStr}\\n\\n<span style=\"font-weight: 400; font-size: 16px; color: #fff; padding: 6px; background: rgba(156, 16, 16, 0.66);\">${obj.time}</span>\\n\\n<span style=\"font-weight: 400;\">${obj.type.toUpperCase()} &mdash; ${obj.text}</span><br />`;\n\n\n}", "function filterContact(contacts) {\n return _.chain(contacts).groupBy((contact) => {\n // group contact to detect contact that are the same\n const contactCopy = {\n lastName: contact.lastName,\n firstName: contact.firstName,\n };\n if (contact.address) {\n contactCopy.address = {\n country: contact.address.country,\n line1: contact.address.line1,\n zip: contact.address.zip,\n city: contact.address.city,\n };\n }\n return JSON.stringify(contactCopy);\n }).map(groups => groups[0]).filter(contact => _.get(contact, 'address') && ['BE', 'FR', 'CH'].indexOf(contact.address.country) > -1)\n .value();\n }", "function formatCertification(certification) { \n\n\n\tvar name = certification.companyName; \n\tvar region = certification.region; \n\tvar country = certification.country; \n\tvar status = certification.status; \n\tvar solution = certification.solution; \n\tvar certificationScenario = certification.certificationScenario; \n\n\tvar outputText = 'Certification for, ' + name; \n\toutputText += '. It is in region, ' + region; \n\toutputText += ' and country, ' + country; \n\toutputText += '. The certification status is, ' + translateCertificationStatus(status); \n\toutputText += ' and the scenario is, ' + certificationScenario + '. '; \n\n\treturn(outputText); \n\n}", "function Contact(firstName, lastName, phoneNumber) {\n this.firstName = firstName;\n this.lastName = lastName;\n this.phoneNumber = phoneNumber;\n }", "function Contact(firstName, lastName, phoneNumber) {\n this.firstName = firstName,\n this.lastName = lastName,\n this.phoneNumber = phoneNumber\n}" ]
[ "0.63130903", "0.62241745", "0.6199052", "0.6186122", "0.6171605", "0.58700246", "0.58234555", "0.5822236", "0.5800665", "0.57151634", "0.5708914", "0.5675894", "0.5675191", "0.5667201", "0.56052315", "0.55989873", "0.5587502", "0.55674446", "0.55618584", "0.5540813", "0.55387104", "0.55149925", "0.546467", "0.5446298", "0.5436309", "0.54219276", "0.5416016", "0.53817284", "0.5358696", "0.53577054", "0.5345344", "0.53448254", "0.53395534", "0.5336165", "0.53331256", "0.5309671", "0.5309671", "0.53050625", "0.5304717", "0.5300889", "0.52985", "0.52655524", "0.5264832", "0.52460676", "0.5245075", "0.52311766", "0.5218582", "0.5205314", "0.5204617", "0.52017504", "0.51904905", "0.51851094", "0.51843625", "0.51774", "0.5177221", "0.5174788", "0.51740915", "0.51733106", "0.51731986", "0.5161568", "0.5151463", "0.51512873", "0.51511437", "0.5150013", "0.5143715", "0.5139663", "0.51391953", "0.51174563", "0.50959647", "0.5089192", "0.50778824", "0.50777227", "0.50591934", "0.5055028", "0.5034169", "0.5032207", "0.50286615", "0.5024566", "0.501578", "0.5010795", "0.5010754", "0.49972677", "0.49967143", "0.4994701", "0.49895388", "0.4977362", "0.4971434", "0.49638948", "0.49612498", "0.49573568", "0.4948328", "0.4947165", "0.49469027", "0.49468657", "0.4946433", "0.49386585", "0.49384522", "0.49320635", "0.4931825", "0.4927516" ]
0.7048042
0
get the list of contacts (each index is an entry)
function getContacts() { return contacts; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getContacts() {\n return contacts;\n }", "contactList() {\n\t if (Session.get(\"searchName\") != \"\") {\n\t\tvar searchString = Session.get(\"searchName\");\n\t\treturn Template.contacts.__helpers[\" findContact\"](searchString);\n\t }\n\t else\n\t\treturn Contacts.findOne(\"Contacts\")[\"contacts\"];\n\t}", "function makeContactList() {\n /*\n * You need something here to hold contacts. See length api for a hint:\n */\n var contacts = [];\n \n return {\n // we implemented the length api for you //\n length: function() {\n return contacts.length;\n },\n addContact: function(contact) {\n contacts.push(contact);\n return contacts;\n },\n findContact: function(fullName) {\n for (var i = 0; i < contacts.length; i++) {\n if (fullName === contacts[i].nameFirst + \" \" + contacts[i].nameLast) { return contacts[i];\n } else {\n return undefined;\n } \n }\n },\n removeContact: function(contact) {\n for (var i = 0; i < contacts.length; i++) {\n if (contacts[i] === contact) {\n contacts.splice(i, 1);\n }\n }\n \n }, printAllContactNames: function() {\n var returnedNames = \" \";\n for (var i = 0; i < contacts.length; i++) {\n returnedNames += \"\\n\" + contacts[i].nameFirst + \" \" + contacts[i].nameLast; \n } return returnedNames.trim();\n }\n \n };\n \n \n }", "get contacts() {\r\n return new Contacts(this);\r\n }", "get contacts() {\r\n return new Contacts(this);\r\n }", "function getContacts() {\n\t\t$.get('/api/contacts', function(data) {\n\t\t\tvar rowsToAdd = [];\n\t\t\tfor (var i = 0; i < data.dbContacts.length; i++) {\n\t\t\t\trowsToAdd.push(createContactsRow(data.dbContacts[i]));\n\t\t\t}\n\t\t\trenderContactsList(rowsToAdd);\n\t\t\tnameInput.val('');\n\t\t});\n\t}", "async findContacts() {\n // The model is used to retrieve data!\n const contacts = await new Contact().getContacts();\n // The service is used for shaping, formatting and more!\n return contacts.map(contact => ({\n firstName: contact.firstName,\n lastName: contact.lastName\n }))\n }", "static async findAllContacts() {\n const ContactList = await Contact.find({});\n return ContactList;\n }", "contactListNames() {\n\t var contactObjectList = Contacts.findOne(\"Contacts\")[\"contacts\"];\n\t var contactNameList = [];\n\t for (id in contactObjectList) {\n\t\tvar first_name = contactObjectList[id][\"name\"][\"first\"];\n\t\tvar middle_name = contactObjectList[id][\"name\"][\"middle\"];\n\t\tvar last_name = contactObjectList[id][\"name\"][\"last\"];\n\t\tvar key = \"\";\n\t\t(first_name != \"\")? key += first_name + \" \" : key = key;\n\t\t(middle_name != \"\")? key += middle_name + \" \" : key = key;\n\t\t(last_name != \"\")? key += last_name : key = key;\n\t\tcontactNameList.push(key);\n\t }\n\t return contactNameList;\n\t}", "function getContacts() {\n let retContacts = JSON.stringify(contacts);\n console.log(\"Returning contacts: \", retContacts);\n return retContacts;\n}", "function _get_site_contacts_list(db){\n try{\n var rows = db.execute('SELECT * FROM my_'+_type+'_site_contact WHERE status_code=1 and '+_type+'_id=?',_selected_job_id);\n var b = 0;\n if(rows.getRowCount() > 0){\n while(rows.isValidRow()){\n var row = Ti.UI.createTableViewRow({\n filter_class:'site_contact',\n className:'site_contact_list_data_row_'+b,\n hasChild:true,\n source:_source,\n job_id:_selected_job_id,\n contact_id:rows.fieldByName('id'),\n title:rows.fieldByName('first_name')+' '+rows.fieldByName('last_name'),\n mobile:rows.fieldByName('phone_mobile'),\n email:rows.fieldByName('email')\n }); \n if(b === 0){\n row.header = 'Site Contacts';\n }\n self.data.push(row);\n rows.next();\n b++;\n }\n }\n rows.close();\n }catch(err){\n self.process_simple_error_message(err,window_source+' - _get_site_contacts_list');\n return;\n } \n }", "function list() {\n var contactsLength = contacts.length; \n for (i = 0; i < contacts.length; i++){\n printPerson(contacts[i]);\n }\n}", "function list() {\n var contactsLength = contacts.length;\n for (var i = 0; i < contactsLength; i++){\n printPerson(contacts[i]);\n }\n}", "GetContactList() {\n return this.m_contactManager.m_contactList;\n }", "function _get_client_contacts_list(db){\n try{ \n var rows = db.execute('SELECT * FROM my_client_contact WHERE status_code=1 and client_id in ('+\n 'select a.client_id from my_'+_type+' as a where a.id=?) and '+\n 'id in (select b.client_contact_id from my_'+_type+'_client_contact as b where b.'+_type+'_id=? and b.status_code=1)',_selected_job_id,_selected_job_id);\n var b = 0;\n if(rows.getRowCount() > 0){\n while(rows.isValidRow()){\n var row = Ti.UI.createTableViewRow({\n filter_class:'client_contact',\n className:'client_contact_list_data_row_'+b,\n hasChild:true,\n source:_source,\n job_id:_selected_job_id,\n client_id:rows.fieldByName('client_id'),\n contact_id:rows.fieldByName('id'),\n title:rows.fieldByName('first_name')+' '+rows.fieldByName('last_name'),\n mobile:rows.fieldByName('phone_mobile'),\n email:rows.fieldByName('email')\n }); \n if(b === 0){\n row.header = 'Client Contacts';\n }\n self.data.push(row);\n rows.next();\n b++;\n }\n }\n rows.close();\n }catch(err){\n self.process_simple_error_message(err,window_source+' - _get_client_contacts_list');\n return;\n } \n }", "function listcontacts(all)\n{\n if (typeof (webphone_api.plhandler) !== 'undefined' && webphone_api.plhandler !== null)\n return webphone_api.plhandler.ListContacts(all);\n}", "findContact(contactName) {\n\t var contactObjectList = Contacts.findOne(\"Contacts\")[\"contacts\"];\n\t var findResult = [];\n\t for (id in contactObjectList) {\n\t\tvar first_name = contactObjectList[id][\"name\"][\"first\"];\n\t\tvar middle_name = contactObjectList[id][\"name\"][\"middle\"];\n\t\tvar last_name = contactObjectList[id][\"name\"][\"last\"];\n\t\tvar key = \"\";\n\t\t(first_name != \"\")? key += first_name + \" \" : key = key;\n\t\t(middle_name != \"\")? key += middle_name + \" \" : key = key;\n\t\t(last_name != \"\")? key += last_name : key = key;\n\t\tif (key == contactName)\n\t\t findResult.push(contactObjectList[id]);\n\t }\n\t return findResult;\n\t}", "function getPhoneContacts(){\r\n\tvar options = new ContactFindOptions();\r\n\toptions.filter=\"\"; // empty search string returns all contacts\r\n\toptions.multiple=true; // return multiple results\r\n\tfilter = [\"displayName\", \"name\", \"phoneNumbers\",\"photos\",\"emails\"];\r\n\t// find contacts\r\n\tnavigator.contacts.find(filter, getPhoneContactsSuccess, null, options);\r\n}", "function getAllContacts(){\n\tvar uri_param = \"GET <b>/api/contacts</b> HTTP/1.1\";\n\t$(\".request-preview-param-uri\").html(uri_param);\n\t$(\".request-preview-param-body\").html('');\n\t\n\tvar list = getStorageContacts(false,0);\n\tvar json = JSON.stringify({\"status\":200,\"contacts\":list});\n\t$(\"#response-preview .text\").jJsonViewer(json);\n\t\n\t\n\tsyncViewTable();\n\t\n\t$.notify(\"Request successful\", \"success\");\n\t$.notify(\"Preview updated\", \"success\");\n\t\n}", "function getContact(){\r\n var mycontact = getContacts();\r\n return mycontact;\r\n}", "function getAllContacts() {\n defer = $q.defer();\n\n $http({\n method: 'GET',\n url: DATASERVICECONSTANTS.BASE_URL + '/contacts',\n timeout: 5000\n }).then(function successCallback(response) {\n defer.resolve(response);\n }, function errorCallback(response) {\n defer.reject(response);\n });\n\n return defer.promise;\n }", "async getAllContacts() {\n return await axios.get(endpoint + \"contacts\");\n }", "static list() {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const contactEmailAddress = (yield db_1.db.read.columns('*').tables('ContactEmailAddresses').get()).rows;\n return contactEmailAddress;\n }\n catch (err) {\n throw new Error(err);\n }\n });\n }", "function searchContact() {\n let searchResultList = search()\n console.log(`The person are ${searchResultList.map(contact => contact.firstName)}`)\n}", "function getContacts(req, res) {\n\n\tdb.child('/contacts').once('value')\n\t.then((snapshot) => {\n\n\t\tlet database = snapshot.val();\n\n\t\tlet data = {};\n\t\tdata[\"contacts\"] = new Array();\n\n\t\tfor(let category in database) {\n\n\t\t\tlet type = {};\n\t\t\ttype[\"section\"] = category;\n\t\t\ttype[\"people\"] = new Array();\n\n\t\t\tfor(let person in database[category]) {\n\n\t\t\t\ttype[\"people\"].push(database[category][person]);\n\t\t\t}\n\n\t\t\tdata[\"contacts\"].push(type);\n\t\t}\n\n\t\tres.set('Cache-Control', 'public, max-age=3600 , s-maxage=7200');\n\t\treturn res.status(200).json({\n\t\t\tdata: data,\n\t\t\tsuccess: true\n\t\t});\n\t})\n\t.catch(() => {\n\n\t\treturn res.status(500).json({\n\t\t\tsuccess: false,\n\t\t\tmessage: 'could not fetch contacts'\n\t\t});\n\t})\n\n}", "async _getContacts () {\n try {\n var contacts = await profile.getContacts();\n this.setState({ contacts: contacts });\n } catch (e) {\n console.error(e, e.stack);\n }\n }", "function getCustomers(contacts) {\n\t\tcontactsId = contacts || '';\n\t\tif (contactsId) {\n\t\t\tcontactsId = '/?contacts_id=' + contactsId;\n\t\t}\n\t\t$.get('/api/contacts' + contactsId, function(data) {\n\t\t\tconsole.log('customers', data);\n\t\t\tcustomers = data;\n\t\t\tif (!customers || !customers.length) {\n\t\t\t\tdisplayEmpty(contacts);\n\t\t\t} else {\n\t\t\t\tinitializeRows();\n\t\t\t}\n\t\t});\n\t}", "getAll(){\n\n return this.contactos;\n\n }", "function getFriends() {\n var friends = [], friend;\n for (var i = 0, length = user.contacts.length; i < length; i++) {\n if (user.contacts[i].removed == 0) {\n friend = usersFactory.getUserByUsername(user.contacts[i].username);\n if (!Methods.isNullOrEmpty(friend)) {\n user.contacts[i].givenName = friend.givenName;\n user.contacts[i].surname = friend.surname;\n friends.push(user.contacts[i]);\n }\n }\n }\n return friends;\n }", "static getAllCampusContacts() {\n let serviceUrl = Config.REST_URL + Config.SERVICESTART + \"/odata/GetAllCampusContacts?$orderby=FirstName,LastSurname\";\n return new Promise((resolve, reject) => {\n fetch(serviceUrl, { \n method: \"get\",\n mode: 'cors',\n cache: 'no-cache',\n credentials: 'include'\n })\n .then(function (response) {\n resolve(response.json());\n })\n .catch(function (error) {\n reject(error);\n });\n });\n }", "function getContacts() {\n $scope.phoneContacts = [];\n\n $cordovaContacts.find({}).then(function(contacts) {\n //On success callback function.\n console.log(JSON.stringify(contacts));\n\n for (var i = 0; i < contacts.length; i++) {\n var contact = contacts[i];\n\n //window.alert(JSON.stringify(contact.photos));\n if (contacts[i].phoneNumbers !== null) {\n\n if (contact.displayName === null) {\n if (contact.name.givenName !== null)\n contact.displayName = contact.name.givenName;\n else \n contact.displayName = \"Unknown Name\";\n }\n\n $scope.phoneContacts.push(contact);\n }\n }\n\n //Sort function alphabetically.\n //http://stackoverflow.com/questions/6712034/sort-array-by-firstname-alphabetically-in-javascript\n $scope.phoneContacts.sort(function(a, b){\n if(a.displayName < b.displayName) return -1;\n if(a.displayName > b.displayName) return 1;\n return 0;\n });\n }, function(Error) {\n //On failure callback function\n MyCareMakerPopups.showAlert(\"Error\" ,\n \"There was an problem loading your contacts. \", null);\n });\n\n }", "function requestExternalContacts() {\n let apiInstance = new platformClient.ExternalContactsApi();\n let opts = {\n pageSize: 6,\n pageNumber: 1\n };\n return apiInstance.getExternalcontactsContacts(opts)\n .then(data => {\n return data;\n });\n }", "function parseContacts(response) {\n return response.rows.map(function(row) {\n return {\n lastName: row.key[0],\n otherNames: row.key[1],\n status: row.key[2],\n lga: row.value.lga,\n state: row.value.state,\n _id: row.value._id,\n daysSinceLastContact: dateParser.daysFromToday(\n row.value.dateLastContact, row.value.dateFirstVisit),\n includingDetailedInfo: false\n };\n });\n }", "function genMockContacts () {\n var chance = new Chance();\n var contacts = [];\n\n for(var i =0;i<10;i++){\n var contact = {};\n var name = chance.name().split(' ');\n contact.id = chance.guid();\n contact.firstName = name[0];\n contact.lastName = name[1];\n contact.zip = chance.zip();\n contact.email = chance.email();\n contacts.push(contact);\n }\n// console.log(contacts);\n return contacts;\n}", "function getAddressBookContacts() {\n // apro due XMLHttprequest rispettivamente per contatti e gruppi\n var contactRequest = new XMLHttpRequest();\n var groupRequest = new XMLHttpRequest();\n contactRequest.open(\"POST\", commandURL, false);\n contactRequest.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n contactRequest.send(\"operation=getContacts\");\n contacts = JSON.parse(contactRequest.responseText);\n groupRequest.open(\"POST\", commandURL, false);\n groupRequest.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n groupRequest.send(\"operation=getGroups\");\n groups = JSON.parse(groupRequest.responseText);\n }", "function afficherContact() { \n contactLists.forEach(function(contactList){ \n console.log(contactList.decrire());\n });\n}", "function getContact(id) {\n return contacts[id];\n }", "function getContacts () {\n\t\t\t$.ajax({\n\t\t\t\turl: \"retailerData.json\",\n\t\t\t\tdataType: \"json\",\n\t\t\t\ttype: \"get\",\n\t\t\t\tsuccess: function (data) {\n\t\t\t\t\tcontactInfoCallback(data);\n\t\t\t\t},\n\t\t\t\terror: function (xhr, ajaxOptions, thrownError) {\n\t \t\t\tconsole.log(xhr.status);\n\t \t\t\tconsole.log(thrownError);\n\t \t\t\t}\n\t\t\t});\n\t\t}", "async function listContacts(app,argv) {\n const db = new dbstore.DynamoContactStore(await app.getVariables())\n console.log(await db.getAllContacts())\n}", "async function importContact() {\n const { data } = await Contacts.getContactsAsync({\n });\n \n if (data.length > 0) {\n const contact = data[0];\n console.log(data);\n }\n \n }", "function addContactsToListView()\n{\n\t//Create \"FROM CONTACTS\" section header\n contactsSections.push(createSection('FROM CONTACTS', data));\n\n\t//Loop through people array and create appropriate listView sections\n\tfor (var i = 0; i < people.length; i++)\n\t{\n\t\t\tif(!sectionTitle)\n\t\t\t{\n\t\t\t\tsectionTitle = people[i].fullName.charAt(0).toLowerCase();\n\t\t\t}\n\t\t\telse if(sectionTitle !== people[i].fullName.charAt(0).toLowerCase())\n\t\t\t{\n\t\t\t\t// Add a section\n\t\t\t\tcontactsSections.push(createSection(sectionTitle.toUpperCase(), data));\n\t\t\t\tdata = [];\n\t\t\t\t\t\t\n\t\t\t\t// New section title\n\t\t\t\tsectionTitle = people[i].fullName.charAt(0).toLowerCase();\n\t\t\t}\n\t\t\t\t\t\n\t\t\t\tdata.push({\n\t\t\t\t\t\tcontact:\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttext: people[i].fullName\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\tproperties: \n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\titemId: people[i].identifier,\n\t\t\t\t\t\t\tphone: people[i].mobile,\n\t\t\t\t\t\t\tsearchableText: people[i].fullName,\n\t\t\t\t\t\t\tfirstName: people[i].firstName,\n\t\t\t\t\t\t\tlastName: people[i].lastName\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\ttemplate: 'contact',\n\t\t\t\t\t\tselected: false\n\t\t\t\t});\n\t\t\t\t\t\n\t\t\t\t// Add the last section\n\t\t\t\t\tif(i == people.length - 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tcontactsSections.push(createSection(sectionTitle.toUpperCase(), data));\n\t\t\t\t\t\t}\n\t}//end of loop through people array for loop\n\t\n\tif(friends.length > 0)\n\t{\n\t\tlistView.insertSectionAt(1,contactsSections);\n\t}else{\n\t\tlistView.insertSectionAt(0,contactsSections);\n\t}\n}", "function pathContacts(options, args) {\n return '/' + this.version() + '/user/' + this.yahooGuid() + '/contacts';\n}", "function getContactData() {\n return contactData;\n }", "function findContact(searchTerm){\n searchResults = [];\n\n var list = contacts.find().fetch();\n console.log(list);\n for(var i=0; i < list.length; i++)\n {\n obj = list[i];\n if(obj.firstname == searchTerm || obj.lastname === searchTerm || obj.gender === searchTerm || obj.email === searchTerm || obj.number === searchTerm || obj.latitude === searchTerm || obj.longitude === searchTerm)\n {\n searchResults.push(obj);\n }\n }\n Session.set(\"searchRes\",searchResults);\n}", "function getStoredContacts() {\n return JSON.parse(localStorage.contacts);\n}", "function getStoredContacts() {\n return JSON.parse(localStorage.contacts);\n}", "async function getContacts(){\n const contacts = await loadContacts('[DB_NAME]','[COLLECTION]','[MONGO_CONNECTION_STRING]'); //CONNECT TO MONGO\n const res = await contacts.find().toArray(); //GET THE CONTACTS\n return res\n}", "getAllContacts(callback) {\n var db = DB.getDB()\n db.collection(COLLECTION).find().toArray(function(err,doc){\n callback(err,doc)\n })\n }", "async _fetchContact() {\n const { id, emailaddress1, contactid } = await this.store.queryRecord('contact', { me: true });\n\n return { id, emailaddress1, contactid };\n }", "function onSuccess(contacts) {\n for (var i=0; i<contacts.length; i++) {\n if(null != contacts[i].phoneNumbers)\n {\n for(var j=0;j<contacts[i].phoneNumbers.length;j++)\n {\n $('#lst').append(\"<li><a href='#display'>\"+contacts[i].displayName+\"</a></li>\");\n $('#lst').listview('refresh'); \n\n\n }\n }\n }\n }", "function onSuccess(contacts) {\n\t\t\t//console.log(JSON.stringify(contacts))\n\t\t\tvar li = '';\n\t\t\t$.each(contacts, function(key, value) {\n\t\t\t\tif (value.name) {\n\t\t\t\t\t$.each(value.name, function(key, value) {\n\t\t\t\t\t\tif (key == 'formatted') {\n\t\t\t\t\t\t\tname = value;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (value.phoneNumbers) {\n\t\t\t\t\t$.each(value.phoneNumbers, function(key, value) {\n\t\t\t\t\t\tphone = value.value;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tli += '<li style=\"text-decoration:none;\">' + name + ' ' + phone + '</li>';\n\t\t\t});\n\t\t\talert('sdj');\n\t\t\talert(li);\n\t\t\t$(\"#contact\").html(li);\n\t\t}", "contactListFirst (query) {\n return this\n .contactList(query)\n .then(contacts => contacts[0] ? contacts[0] : null)\n ;\n }", "function getContacts(un, cName, cEmail, cPhone, cAddress){\n\tconsole.log(\"getContacts running\");\n\n\tvar obj = {\n \t\tcontactName: cName,\n \t\temailAddress: cEmail,\n \t\tphoneNumber: cPhone,\n \t\taddress: cAddress,\n \t\tusername: un\n\t};\n\tvar jsonPayload = JSON.stringify(obj);\n\n var xhr = new XMLHttpRequest();\n\txhr.open(\"POST\",\"http://iburch.pythonanywhere.com/contactsget\", false);\n\txhr.setRequestHeader(\"Content-type\", \"application/json; charset=UTF-8\");\n\n\ttry{\n\t\txhr.send(jsonPayload);\n\t\tvar jsonObject = JSON.parse(xhr.responseText);\n\n\t\t//console.log(jsonObject);\n\t\treturn jsonObject;\n\t}\n\tcatch(err){\n\t\tconsole.log(err);\n\t}\n}", "fetchContacts() {\n Contacts.getAll((err, contacts) => {\n if (err && err.type === 'permissionDenied'){\n console.log('permission denied!')\n this.setState({\n loaded: true,\n permission: 'no',\n });\n } else if (err) {\n console.log(err);\n // should probably show an error message in the ui\n } else {\n // add more dummy entries for testing purposes only\n // if (contacts.length < 10) {\n // contacts = contacts.concat(_.map(contacts, c => {\n // var d = _.clone(c); d.recordID *= 100; return d;\n // }));\n // }\n // add test entry\n var testEntry = _.clone(contacts[0]);\n testEntry.givenName = 'Venkat';\n testEntry.familyName = 'Quone Test';\n testEntry.phoneNumbers[0].number = myPhone;\n testEntry.recordID = 19642;\n contacts = contacts.concat([testEntry]);\n\n this.setState({\n loaded: true,\n permission: 'yes',\n contacts: this.getContactsRows(contacts)\n });\n console.log(this.state.contacts);\n }\n })\n }", "function displayContacts(){\n\n\tsection.innerHTML ='';\n\tarrayOfContacts.sort(sortArrayOfContacts);\n\tfor (contactItem of arrayOfContacts){\n\n\t\tlet contactContainer = createElement(section, 'div', '', 'class', 'contact-container');\n\t\tlet contactLogo = createElement(contactContainer, 'div', '<img src=\"./person-logo.png\">', 'class', 'contact-logo');\n\t\tlet removeContactButton = createElement(contactContainer, 'div', '', 'class', 'remove-contact-button');\n\t\t\tremoveContactButton.setAttribute('id',contactItem.id);\n\t\tlet editContactButton = createElement(contactContainer, 'div', '', 'class', 'edit-contact-button');\n\t\t\teditContactButton.setAttribute('id',contactItem.id);\n\t\tlet contactName = createElement(contactContainer, 'p', contactItem.name, 'class', 'contact-name');\t\t\n\t\tlet contactUl1 = createElement(contactContainer, 'ul', '', 'class', 'phonenumber-list');\n\t\tfor(phoneNumber of contactItem.phoneNumbers ){\n\t\t\tlet li = createElement(contactUl1, 'li', phoneNumber, 'class', '');\n\t\t}\n\t\tlet contactUl2 = createElement(contactContainer, 'ul', '', 'class', 'email-list');\n\t\tfor(email of contactItem.emails ){\n\t\t\tlet li = createElement(contactUl2, 'li', email, 'class', '');\n\t\t}\n\t}\t\n}", "getContactsFromSalesforce() {\n getContactsApex()\n .then(contacts => {\n //console.log(JSON.stringify(contacts))\n console.log('Got Contacts: ' + contacts.length);\n })\n .catch(error => {\n console.log(error)\n });\n }", "function Contacts() {\n\t\n}", "function filterContact(contacts) {\n return _.chain(contacts).groupBy((contact) => {\n // group contact to detect contact that are the same\n const contactCopy = {\n lastName: contact.lastName,\n firstName: contact.firstName,\n };\n if (contact.address) {\n contactCopy.address = {\n country: contact.address.country,\n line1: contact.address.line1,\n zip: contact.address.zip,\n city: contact.address.city,\n };\n }\n return JSON.stringify(contactCopy);\n }).map(groups => groups[0]).filter(contact => _.get(contact, 'address') && ['BE', 'FR', 'CH'].indexOf(contact.address.country) > -1)\n .value();\n }", "function onSuccess(contacts) {\n \tdocument.getElementById('contacts-output').innerHTML = \n\t\t\t \"<strong>You have \" + contacts.length + \"</strong> contacts.\";\n for (var i=0; i<contacts.length; i++) {\n \tif (contacts[i].name && contacts[i].name.formatted)\n \tdocument.getElementById('contacts-output').innerHTML = \n\t\t\tdocument.getElementById('contacts-output').innerHTML +\n console.log(\"Display Name = \" + contacts[i].displayName);\n \t//show first five contacts\n\t\t\t \"<br/>Contact \" + (i+1) + \" is <strong>\" +\n\t\t\t contacts[i].name.formatted + \"</strong>\";\n\t\t\t \"<br/>Contact \" + (i+2) + \" is <strong>\" +\n\t\t\t contacts[i].name.formatted + \"</strong>\";\n\t\t\t \"<br/>Contact \" + (i+3) + \" is <strong>\" +\n\t\t\t contacts[i].name.formatted + \"</strong>\";\n\t\t\t \"<br/>Contact \" + (i+4) + \" is <strong>\" +\n\t\t\t contacts[i].name.formatted + \"</strong>\";\n\t\t\t \"<br/>Contact \" + (i+5) + \" is <strong>\" +\n\t\t\t contacts[i].name.formatted + \"</strong>\";\n\t\t\t break;\n }\n }", "function populateContacts(contacts) {\n\t\tfor(var i = 0; i < contacts.length; i++){\n\t\t\tvar node = template.cloneNode(true);\n\t\t\tnode.id = contacts[i].id;\n\t\t\tvar str = node.innerHTML.replace(\"1\", i+1);\n\t\t\tnode.innerHTML = str;\n\t\t\tvar str2 = node.innerHTML.replace(/index/g, i + node.id);\n\t\t\tnode.innerHTML = str2;\n\t\t\tvar str3 = node.innerHTML.replace('name=\"name\"', 'value=\"' + contacts[i].name + '\" name=\"name\"');\n\t\t\tnode.innerHTML = str3;\n\t\t\tvar str4 = node.innerHTML.replace('name=\"email\"', 'value=\"' + contacts[i].email + '\" name=\"email\"');\n\t\t\tnode.innerHTML = str4;\n\t\t\t\n\t\t\tdocument.getElementsByClassName(\"card-body\")[0].append(node);\n\t\t}\n\t}", "function listAllContacts(keyword){\n list = getAllContacts(keyword);\n if (list.length === 0) {\n $('#contact-list-wrap').text(\"No contact found\");\n } else{\n buildTable(list);\n }\n }", "async function fetchContacts() {\n const contactData = await API.get('formapi', '/contact');\n console.log({ contactData });\n}", "function display() {\n document.querySelector(\"#contact_list\").innerHTML = \"\";\n addressBook.contacts.forEach((contact, index) => {\n const newEntry = document.createElement(\"div\");\n newEntry.classList.add(\"contact_box\");\n newEntry.innerHTML = `\n <p>Name: ${contact.name}</p>\n <p>Email: ${contact.email}</p>\n <p>Phone: ${contact.phone}</p>\n <p>Relation: ${contact.relation}</p>\n <i class=\"fa fa-trash\" data-index-numbers=\"${index}\"\n aria-hidden= \"true\"></li>\n `;\n document.querySelector(\"#contact_list\").appendChild(newEntry);\n });\n}", "function refreshContactList (contacts) {\n pageContents.contacts = contacts;\n\n if (contacts.length === 0) {\n $(\".rolodex\").addClass(\"block\");\n }\n else {\n $(\".rolodex\").removeClass(\"block\");\n }\n $(\".rolodex\").html(listTemplate(pageContents));\n }", "function appendToLists(contact) {\n updatePhoto(contact);\n var ph = createPlaceholder(contact);\n var groups = [ph.dataset.group];\n if (isFavorite(contact)) {\n groups.push('favorites');\n }\n\n var nodes = [];\n\n for (var i = 0, n = groups.length; i < n; ++i) {\n ph = appendToList(contact, groups[i], ph);\n nodes.push(ph);\n ph = null;\n }\n\n selectedContacts[contact.id] = selectAllPending;\n\n return nodes;\n }", "function readContacts(json) {\n\t// So, I was having errors testing this on the file level. The fix is to force the MIME type to a JSON\n\t$.ajaxSetup({\n\t\tasync:true,\n\t\tbeforeSend: function(xhr){\n\t\t\tif (xhr.overrideMimeType) {\n\t\t\t\txhr.overrideMimeType(\"application/json\");\n\t\t\t}\n\t\t}\n\t});\n\n\t$.getJSON(json, function(data) {\n\t\t$.each(data, function(index,value) {\n\t\t\tvar entry = new Object();\n\t\t\tentry.name = value.name;\n\t\t\tentry.phoneNum = value.phoneNum; \n\t\t\tentry.group = value.group;\n\t\t\tentry.email = value.email;\n\t\t\tentry.address = value.address;\n\t\t\tentry.birthday = value.birthday;\n\t\t\tentry.note = value.note;\n\t\t\tcontacts[contacts.length] = entry;\n\t\t});\n\n\t\tconsole.log(\"Populated\");\n\t\talert(contacts.length);\n\t});\n}", "function ContactService() {\n\n this.contacts = data.map(function (contact) {\n return new Contact(contact.id, contact.lastName, contact.firstName, contact.address, contact.phone);\n });\n\n /**\n * La méthode get renvoie le tableau de contacts\n */\n this.get = function () {\n return this.contacts;\n };\n\n /*\n * La méthode print ne fait appel qu'à la méthode get définie précédemment\n * en définissant l'action que nous désirons exécuter sur les éléments de\n * de notre tableau de contacts\n */\n this.print = function print() {\n console.log(this.get().join(', '));\n };\n}", "function listOptions( theContacts )\r\n{\r\n var s ='';\r\n for( var contact in theContacts )\r\n {\r\n if (s != '') { s = s + \", \" };\r\n s = s + contact + \" (\" + theContacts[ contact ].nameChoices + \")\";\r\n }\r\n return s;\r\n}", "_loadContacts(callback){\n //Define an empty void if no callback specified\n if(callback === undefined){\n callback = _ => {};\n }\n\n var self = this;\n contactsEndpoint.contacts(this.token, function(errors, answer){\n if(errors === null){\n for (let groupAnswer of answer['Groups']){\n //Take only servers\n if(groupAnswer.GroupType == groupsEndpoints.GroupType.Large){\n //Check that server is not already existing\n if(self.servers.has(groupAnswer.GroupID) == false){\n var server = new serverModule.Server(groupAnswer.GroupID, self);\n }\n }\n }\n\n self.friendList = answer['Friends']; //Thoses friends are not useable yet (who needs friends ?)\n callback(null);\n } else {\n callback(errors);\n }\n });\n\n }", "function getContactByContactId(contactId) {\n\n var deferred = new $.Deferred();\n \n var contactList = window.Compass.Helm.LoanContacts;\n var contact = null;\n\n for (var i = 0; i < contactList.length; i++) {\n if (contactList[i] !== null && contactList[i].ContactId === contactId) {\n contact = contactList[i];\n break;\n }\n }\n\n deferred.resolve(contact);\n return deferred.promise();\n\n }", "@wire(searchRecordList, {objectApi: CONTACT_OBJECT, fields:FIELDS, filterVars:'$filterVars', offset:0, limits:100})\n wire_getRecordList({error, data}){\n this.contactList = [];\n this.total = 0;\n if (data){\n console.log('query contacts:');\n \n (data.result || []).forEach(e=>{\n console.log(JSON.stringify(e));\n this.contactList.push(JSON.parse(JSON.stringify(e)));\n });\n this.total = data.count;\n this.renderDropItems();\n console.log(data.count);\n }else if (error){\n this.error = error;\n }\n }", "function onSuccess(contacts) {\n for (var i=0; i<contacts.length; i++) {\n // display phone numbers\n for (var j=0; j<contacts[i].phoneNumbers.length; j++) {\n alert(\"Type: \" + contacts[i].phoneNumbers[j].type + \"\\n\" + \n \"Value: \" + contacts[i].phoneNumbers[j].value + \"\\n\" + \n \"Preferred: \" + contacts[i].phoneNumbers[j].pref);\n }\n }\n }", "function recipientList(query) {\n return api\n .get('recipient', { params: { q: query } })\n .then(response => {\n const options = response.data.recipientList.map(recipient => ({\n value: recipient.id,\n label: recipient.name,\n }));\n return options;\n })\n .catch(error => {\n console.tron.log(error);\n toast.error(\n 'Listagem de clientes não foi carregada. Verifique a sua conexão com o Banco de dados.'\n );\n });\n }", "function getContactsViewWithStatusByName() {\n var d = $q.defer();\n\n /* jshint camelcase: false */\n couchdb.view({_db: DB_NAME, _param:'contacts', _sub_param: 'withStatusByName'}).$promise\n .then(function(response) {\n d.resolve(parseContacts(response));\n })\n .catch(function(error) {\n d.reject(error);\n });\n\n return d.promise;\n }", "function listConnectionNames() {\n gapi.client.people.people.connections.list({\n 'resourceName': 'people/me',\n 'pageSize': 2000,\n 'personFields': 'names,emailAddresses',\n }).then(function (response) {\n var connections = response.result.connections;\n appendPre('Connections:');\n\n console.log(connections, 'connections');\n var googleContacts = [];\n if (connections.length > 0) {\n for (i = 0; i < connections.length; i++) {\n var person = connections[i];\n if (person.emailAddresses && person.emailAddresses.length > 0) {\n var name = (person.names && person.names.length > 0) ? person.names[0].displayName : 'Unnamed';\n var email = person.emailAddresses[0].value;\n var d = {\n name: name,\n email: email\n };\n googleContacts.push(d);\n\n // appendPre(person.emailAddresses[0].value);\n } else {\n // appendPre(\"User has no email.\");\n }\n }\n $scope.googleContacts = googleContacts;\n console.log($scope.googleContacts, 'googleContacts');\n\n } else {\n appendPre('No upcoming events found.');\n }\n });\n }", "function refreshContacts() {\n client.contacts.refresh()\n}", "function GetEMAIL_CONTACT(){\n return enumParams(COLUMN_CONTACT).join();\n}", "function onSuccess(contacts) {\n for (var i=0; i<contacts.length; i++) {\n //alert(\"First Name: \" + contacts[i].name.givenName + \"\\n\" + \n //\"Last Name: \" + contacts[i].name.familyName + \"\\n\" +\n //\"Phone Number :\" + contacts[i].phoneNumbers[i].value + \"\\n\" +\n //\"Email: \" + contacts[i].emails[i].value);\n //console.log(contacts);\n \n var conResults = document.getElementById(\"conResults\");\n //$(\"#conResults\").empty(); \n \tconResults.innerHTML = \"First Name: \" + contacts[i].name.givenName + \"<br/>\" + \n \"Last Name: \" + contacts[i].name.familyName + \"<br/>\" + \n \"Phone Number: \" + contacts[i].phoneNumbers[0].value + \"<br/>\" + \n \"Email: \" + contacts[i].emails[0].value; \n } \n }", "function show(){\n loadData();\n console.log(listContact);\n}", "function populateContacts()\n{\n\t// Temporary array\n\tvar tempArray = null; \n\t\n\t// An array that will hold our contacts\n\tvar contactList = new Array();\t\n\t\n\t// Function to use HTTP to connect to a web server and transfer the data. \n\tvar request1 = Ti.Network.createHTTPClient({ \n\tonerror: function(e){ \t\n\t\tTi.API.debug(e.error); \t\n\t\talert('There was an error during the connection CONTACTS'); \t\n\t}, \t\n\ttimeout:1000, \n\t});\n\n\t// Here you have to change it for your local ip \n\trequest1.open('POST', '52.32.54.34/php/read_contact_list.php'); \n\tvar params = ({ \"USER_ID\": Alloy.Globals.thisUserID }); \n\trequest1.send(params);\n\n\trequest1.onload = function() {\n\t\tvar json = JSON.parse(this.responseText);\n\t\tvar json = json.OTHER_USER_ID;\n\t\t\n\t\t// HOLD USER_ID s of CONTACTS\n\t\ttempArray = json; \n\t\t\n\t\t// Function to use HTTP to connect to a web server and transfer the data. \n\t\tvar request2 = Ti.Network.createHTTPClient({ \n\t\tonerror: function(e){ \t\n\t\t\t\tTi.API.debug(e.error); \t\n\t\t\t\talert('There was an error during the connection CONTACTS'); \t\n\t\t\t}, \t\n\t\t\ttimeout:1000, \n\t\t});\n\t\n\t\t// Here you have to change it for your local ip \n\t\trequest2.open('GET', '52.32.54.34/php/read_user_list.php'); \n\t\trequest2.send();\n\t\t\n\t\t// Called on load of connection\n\t\trequest2.onload = function() {\n\t\t\tvar json = JSON.parse(this.responseText);\n\t\t\tvar json = json.NAME;\t\n\t\t\t\n\t\t\tfor( var i=0; i < json.length; i++) \n\t\t\t{\n\t\t\t\tfor ( var j = 0; j < tempArray.length; j++)\n\t\t\t\t{\n\t\t\t\t\t// Find the contact\n\t\t\t\t\tif ( json[i].USER_ID === tempArray[j].OTHER_USER_ID)\n\t\t\t\t\t{\n\t\t\t\t\t\t//THESE ARE THE USER_ID s that I WANT TO USE FOR CONTACTS\n\t\t\t\t\t\tcontactList.push(json[i]); \n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// ContactList now holds all CONTACT's rows information\n\t\t\t}\n\t\t\t\n\t\t\t// Sort by users' names\n\t\t\tcontactList = _.sortBy(contactList, function(user){\n\t\t\t\treturn user.NAME\n\t\t\t});\n\n\t\t\tif (contactList)\n\t\t\t{\n\t\t\t\t/**\n\t\t\t\t * Setup our Sections Array for building out the ListView components\n\t\t\t\t * \n\t\t\t\t */\n\t\t\t\tvar sections = [];\n\t\t\t\t\n\t\t\t\t/**\n\t\t\t\t * Group the data by first letter of last name to make it easier to create \n\t\t\t\t * sections. (leverages the UndrescoreJS _.groupBy function)\n\t\t\t\t */\n\t\t\t\tvar userGroups = _.groupBy(contactList, function(item){\n\t\t\t\t \treturn item.NAME.charAt(0);\n\t\t\t\t});\n\t\t \n\t\t /**\n\t\t * Iterate through each group created, and prepare the data for the ListView\n\t\t * (Leverages the UnderscoreJS _.each function)\n\t\t */\n\t\t\t\t_.each(userGroups, function(group)\n\t\t\t\t{\n\t\t\t\t\t/**\n\t\t\t\t\t * Take the group data that is passed into the function, and parse/transform\n\t\t\t\t\t * it for use in the ListView templates as defined in the directory.xml file.\n\t\t\t\t\t */\n\t\t\t\t\tvar dataToAdd = preprocessForListView(group);\n\t\t\n\t\t\t\t\t/**\n\t\t\t\t\t * Check to make sure that there is data to add to the table,\n\t\t\t\t\t * if not lets exit\n\t\t\t\t\t */\n\t\t\t\t\tif(dataToAdd.length < 1) return;\n\t\t\n\t\t\t\t\t/**\n\t\t\t\t\t * Create the ListViewSection header view\n\t\t\t\t\t * DOCS: http://docs.appcelerator.com/platform/latest/#!/api/Titanium.UI.ListSection-property-headerView\n\t\t\t\t\t */\n\t\t\t\t\t var sectionHeader = Ti.UI.createView({\n\t\t\t\t\t \tbackgroundColor: \"#ececec\",\n\t\t\t\t\t \twidth: Ti.UI.FILL,\n\t\t\t\t\t \theight: 30\n\t\t\t\t\t });\n\t\t\n\t\t\t\t\t /**\n\t\t\t\t\t * Create and Add the Label to the ListView Section header view\n\t\t\t\t\t */\n\t\t\t\t\t var sectionLabel = Ti.UI.createLabel({\n\t\t\t\t\t \ttext: group[0].NAME.charAt(0),\n\t\t\t\t\t \tleft: 20,\n\t\t\t\t\t \tfont:{\n\t\t\t\t\t \t\tfontSize: 20\n\t\t\t\t\t \t},\n\t\t\t\t\t \tcolor: \"#666\"\n\t\t\t\t\t });\n\t\t\t\t\t sectionHeader.add(sectionLabel);\n\t\t\n\t\t\t\t\t/**\n\t\t\t\t\t * Create a new ListViewSection, and ADD the header view created above to it.\n\t\t\t\t\t */\n\t\t\t\t\t var section = Ti.UI.createListSection({\n\t\t\t\t\t\theaderView: sectionHeader\n\t\t\t\t\t});\n\t\t\n\t\t\t\t\t/**\n\t\t\t\t\t * Add Data to the ListViewSection\n\t\t\t\t\t */\n\t\t\t\t\tsection.items = dataToAdd;\n\t\t\t\t\t\n\t\t\t\t\t/**\n\t\t\t\t\t * Push the newly created ListViewSection onto the `sections` array. This will be used to populate\n\t\t\t\t\t * the ListView \n\t\t\t\t\t */\n\t\t\t\t\tsections.push(section);\n\t\t\t\t});\t// End of each function\n\t\t\t\t\n\t\t\t\t/**\n\t\t\t\t * Add the ListViewSections and data elements created above to the ListView\n\t\t\t\t */\n\t\t\t\t$.listView.sections = sections;\n\t\t\t} // End of if statement\n\t\t\t\n\t\t};\t// End of second onload function\n\t\t\n\t}; // End of first onload function\n\n}", "render() {\n return (\n <div>\n {this.props.contacts.map(contact => (\n <Contact displayConvo={this.props.displayConvo} name={contact} />\n ))}\n {/* Should render an array of Contact components , with the prop \"name\"*/}\n </div>\n )\n }", "function displayEntries() {\n var contactsDiv = document.getElementById(\"contacts\"); \n // i) clear the list by settin innerHTML on the list empty\n contactsDiv.innerHTML = \"\"; \n // ii) (re-)add all entries\n for (var i = 0; i < contacts.length; i++) {\n var entryDiv = document.createElement(\"div\");\n entryDiv.innerHTML = \"<div id=\\\"contact_\" + i + \"\\\" class=\\\"contact\\\">\" \n + contacts[i].display(i) + \"</div>\";\n contactsDiv.appendChild(entryDiv);\n }\n}", "function showContacts() {\n context.setPage({\n prev: pageNames.allMessages,\n curr: pageNames.showContacts,\n });\n }", "function showInfo(contactID, searchCriteria) {\n \n var contInfoContainer = getElement(\"contact_info\");\n var contactFields = [\"*\"];\n var contactFindOptions = new ContactFindOptions();\n contactFindOptions.filter = searchCriteria;\n contactFindOptions.multiple = true;\n navigator.contacts.find(contactFields, contactSuccess, contactError, contactFindOptions);\n \n function contactSuccess(contacts) {\n \n contInfoContainer.innerHTML = \"\";\n for (var i = 0; i < contacts.length; i++) {\n \n if (contacts[i].id == contactID) {\n \n activeContact = contacts[i];\n \n var cNameSection = \"<div class='contactInfo'>\" +\n \"<div>\" + buildDisplayName(contacts[i]) + \"</div>\" +\n \"<div>\" + (!isEmptyOrBlank(contacts[i].nickname) ? ('\"' + contacts[i].nickname + '\"') : \"\") + \"</div>\" +\n \"</div>\";\n \n var cPhotoSection = \"<div class='contactImage'>\" +\n \"<img src='\" + \n ((contacts[i].photos && (contacts[i].photos.length > 0) && !isEmptyOrBlank(contacts[i].photos[0].value) && (contacts[i].photos[0].value.indexOf(\"//:0\") === -1)) \n ? contacts[i].photos[0].value \n : \"resources/nophoto.jpg\") + \n \"' width='50' height='50' />\" +\n \"</div>\";\n \n var cPhoneNumbersSection = \"\";\n if (contacts[i].phoneNumbers && (contacts[i].phoneNumbers.length > 0)) {\n \n var cPhoneNumbersSectionHeader = \"<div class='iSectionTitle'>Phone Numbers</div>\";\n var cPhoneNumbersSectionContent = \"\";\n for (var j = 0; j < contacts[i].phoneNumbers.length; j++) {\n if (contacts[i].phoneNumbers[j] && !isEmptyOrBlank(contacts[i].phoneNumbers[j].value)) {\n cPhoneNumbersSectionContent += \"<div class='iSectionItem'>\" +\n \"<div class='iItemType'>\" + contacts[i].phoneNumbers[j].type + \"</div>\" +\n \"<div class='iItemValue'>\" + contacts[i].phoneNumbers[j].value + \"</div>\" +\n \"</div>\";\n }\n }\n if (!isEmptyOrBlank(cPhoneNumbersSectionContent)) {\n cPhoneNumbersSection = cPhoneNumbersSectionHeader + cPhoneNumbersSectionContent;\n }\n }\n \n var cEmailsSection = \"\";\n if (contacts[i].emails && (contacts[i].emails.length > 0)) {\n \n var cEmailsSectionHeader = \"<div class='iSectionTitle'>Emails</div>\";\n var cEmailsSectionContent = \"\";\n for (var j = 0; j < contacts[i].emails.length; j++) {\n if (contacts[i].emails[j] && !isEmptyOrBlank(contacts[i].emails[j].value)) {\n cEmailsSectionContent += \"<div class='iSectionItem'>\" +\n \"<div class='iItemType'>\" + contacts[i].emails[j].type + \"</div>\" +\n \"<div class='iItemValue'>\" + contacts[i].emails[j].value + \"</div>\" +\n \"</div>\";\n }\n }\n if (!isEmptyOrBlank(cEmailsSectionContent)) {\n cEmailsSection = cEmailsSectionHeader + cEmailsSectionContent;\n }\n }\n \n var cIMsSection = \"\";\n if (contacts[i].ims && (contacts[i].ims.length > 0)) {\n \n var cIMsSectionHeader = \"<div class='iSectionTitle'>IMs</div>\";\n var cIMsSectionContent = \"\";\n \n for (var j = 0; j < contacts[i].ims.length; j++) {\n if (contacts[i].ims[j] && !isEmptyOrBlank(contacts[i].ims[j].value)) {\n cIMsSectionContent += \"<div class='iSectionItem'>\" +\n \"<div class='iItemType'>\" + contacts[i].ims[j].type + \"</div>\" +\n \"<div class='iItemValue'>\" + contacts[i].ims[j].value + \"</div>\" +\n \"</div>\";\n }\n }\n \n if (!isEmptyOrBlank(cIMsSectionContent)) {\n cIMsSection = cIMsSectionHeader + cIMsSectionContent;\n }\n }\n \n var cUrlsSection = \"\";\n if (contacts[i].urls && (contacts[i].urls.length > 0)) {\n \n var cUrlsSectionHeader = \"<div class='iSectionTitle'>Urls</div>\";\n var cUrlsSectionContent = \"\";\n \n for (var j = 0; j < contacts[i].urls.length; j++) {\n if (contacts[i].urls[j] && !isEmptyOrBlank(contacts[i].urls[j].value)) {\n cUrlsSectionContent += \"<div class='iSectionItem'>\" +\n \"<div class='iItemType'>\" + contacts[i].urls[j].type + \"</div>\" +\n \"<div class='iItemValue'>\" + contacts[i].urls[j].value + \"</div>\" +\n \"</div>\";\n }\n }\n if (!isEmptyOrBlank(cUrlsSectionContent)) {\n cUrlsSection = cUrlsSectionHeader + cUrlsSectionContent;\n }\n }\n \n var cAddressesSection = \"\";\n if (contacts[i].addresses && (contacts[i].addresses.length > 0)) {\n \n var cAddressesSectionHeader = \"<div class='iSectionTitle'>Addresses</div>\";\n var cAddressesSectionContent = \"\";\n \n for (var j = 0; j < contacts[i].addresses.length; j++) {\n if (contacts[i].addresses[j] && (!isEmptyOrBlank(contacts[i].addresses[j].streetAddress) || !isEmptyOrBlank(contacts[i].addresses[j].locality) ||\n !isEmptyOrBlank(contacts[i].addresses[j].region) || !isEmptyOrBlank(contacts[i].addresses[j].country))) {\n \n var atypeSubsection = ((!isEmptyOrBlank(contacts[i].addresses[j].type) && (contacts[i].addresses[j].type != \"undefined\")) ? (\"<div class='iItemType'>\" + contacts[i].addresses[j].type + \"</div>\") : \"\");\n var strSubsection = ((!isEmptyOrBlank(contacts[i].addresses[j].streetAddress) && (contacts[i].addresses[j].streetAddress != \"undefined\")) ? (\"<div>\" + contacts[i].addresses[j].streetAddress + \"</div>\") : \"\");\n var locSubsection = ((!isEmptyOrBlank(contacts[i].addresses[j].locality) && (contacts[i].addresses[j].locality != \"undefined\")) ? (\"<div>\" + contacts[i].addresses[j].locality + \"</div>\") : \"\");\n var regSubsection = ((!isEmptyOrBlank(contacts[i].addresses[j].region) && (contacts[i].addresses[j].region != \"undefined\")) ? contacts[i].addresses[j].region : \"\");\n var postSubsection = ((!isEmptyOrBlank(contacts[i].addresses[j].postalCode) && (contacts[i].addresses[j].postalCode != \"undefined\")) ? contacts[i].addresses[j].postalCode : \"\");\n if (regSubsection != \"\") {\n if (postSubsection != \"\") {\n regSubsection += \", \";\n }\n }\n regSubsection += postSubsection;\n var countrySubsection = ((!isEmptyOrBlank(contacts[i].addresses[j].country) && (contacts[i].addresses[j].country != \"undefined\")) ? (\"<div>\" + contacts[i].addresses[j].country + \"</div>\") : \"\");\n \n cAddressesSectionContent += \"<div class='iSectionItem'>\" +\n atypeSubsection +\n \"<div class='iItemValue'>\" + \n strSubsection +\n locSubsection +\n (\"<div>\" + regSubsection + \"</div>\") +\n countrySubsection +\n \"</div>\" +\n \"</div>\";\n }\n }\n if (!isEmptyOrBlank(cAddressesSectionContent)) {\n cAddressesSection = cAddressesSectionHeader + cAddressesSectionContent;\n }\n }\n \n var sectionHeading = \"\";\n var sectionContent = \"\";\n if (contacts[i].organizations && (contacts[i].organizations.length > 0)) {\n for (var j = 0; j < contacts[i].organizations.length; j++) {\n var typeSubsection = ((!isEmptyOrBlank(contacts[i].organizations[j].type) && (contacts[i].organizations[j].type != \"undefined\")) ? (\"<div class='iItemType'>\" + contacts[i].organizations[j].type + \"</div>\") : \"\");\n var deptSubsection = ((!isEmptyOrBlank(contacts[i].organizations[j].department) && (contacts[i].organizations[j].department != \"undefined\")) ? (contacts[i].organizations[j].department) : \"\");\n var orgSubsection = ((!isEmptyOrBlank(contacts[i].organizations[j].name) && (contacts[i].organizations[j].name != \"undefined\")) ? contacts[i].organizations[j].name : \"\");\n var orgLine = orgSubsection;\n if (deptSubsection != \"\") {\n if (orgSubsection != \"\") {\n orgLine += \", \";\n } \n orgLine += deptSubsection;\n }\n var titleSubsection = ((!isEmptyOrBlank(contacts[i].organizations[j].title)) ? (\"<div>\" + contacts[i].organizations[j].title + \"</div>\") : \"\");\n \n if ((orgLine != \"\") || (titleSubsection != \"\")) {\n sectionContent += \"<div class='iSectionItem'>\" +\n typeSubsection +\n \"<div class='iItemValue'>\" + \n (\"<div>\" + orgLine + \"</div>\") +\n titleSubsection +\n \"</div>\" +\n \"</div>\";\n }\n }\n if (!isEmptyOrBlank(sectionContent)) {\n sectionHeading = \"<div class='iSectionTitle'>Organizations</div>\";\n }\n }\n var cOrganizationsSection = sectionHeading + sectionContent;\n \n var cNoteSection = \"\";\n if (!isEmptyOrBlank(contacts[i].note)) {\n cNoteSection += \"<div class='iSectionTitle'>Note</div>\" +\n \"<div class='iSectionItem'>\" +\n \"<div class='iItemValue'>\" + contacts[i].note + \"</div>\" +\n \"</div>\";\n }\n \n contInfoContainer.innerHTML += cPhotoSection + cNameSection + cPhoneNumbersSection + cEmailsSection + \n cIMsSection + cUrlsSection + cAddressesSection + cOrganizationsSection + \n cNoteSection;\n $.mobile.changePage(\"#cont_info_page\", { transition: \"pop\" });\n break;\n }\n }\n }\n \n function contactError(contactError) {\n \n contInfoContainer.innerHTML = \"Contacts are unavailable\";\n $.mobile.changePage(\"#cont_info_page\", { transition: \"pop\" });\n }\n}", "function listContactsForm(event, myTag) {\n\n\n // get the contacts\n $.getJSON(\"/contacts\", handlers.receiveContacts);\n\n }", "function getContactsList(groupID) {\n updateDisplayPanel('contactsWrp');\n\n if (groupID == -1) {\n currentGroup = root;\n }\n else {\n changeCurrentGroup(root, groupID)\n }\n\n if (deletedGroupID != groupID) {\n updateSelectedGroup(groupID);\n }\n\n updateContactsPanel();\n }", "function getPeople() {\n return ['Arpan', 'Moni', 'Sandeep', 'Tejas'];\n}", "function listCarnetContact(){ \n checkLocalStorage() /* appel à la fonction \"checkLocalStorage\" */\n $('#contactList').html('<ul>') /* Création d'une ul pour y insérer les li correspondant à nos contacts enregistrés */\n for(i=0; i < liste.length; i++){ /* pour chaque objets contenus dans le tableau \"liste\" */\n $(\"#contactList ul\").append(\"<li>\" + '<a href=\"#\" data-index=\"' +i+ '\">'+ liste[i].prenom + \" \" + liste[i].nom + \"</a>\" + \"</li>\") /* Affiche le prénom suivi du nom dans une li et attribut à chaque li un index qui sera utilisé pour afficher le détail du contact lorsqu'on clic sur son nom.*/\n }\n}", "getPhoneNums() {\n let mapping = {};\n for (let contact of this.props.contacts) {\n mapping[contact.name] = contact.phone;\n }\n return mapping;\n }", "render() {\n return (\n <ListWrapper>\n <List>\n {Array.prototype.map.call(this.state.arr, (contact, index) => {\n if (index < 100) return <ContactItem key={index} contact={contact} index={index} onDeleteContact={()=>this.onDeleteContact(contact.id)}></ContactItem>\n }\n )}\n </List>\n </ListWrapper>\n );\n }", "function getAll() {\r\n $.getJSON(\"http://localhost:8080/api/contacts\", (data) => {\r\n if (data !== undefined && data.length !== 0) {\r\n updateContacts(data);\r\n }\r\n }).fail((err) => console.log(\"Couldn't contacts \", err));\r\n}", "watchGetContactList() {\n this.socket.on(\"GetContactListRequest\", async () => {\n try {\n let contactList = await ContactController.findContactsByUser(\n this.socket.request.user.id\n );\n\n let contactPromiseList = contactList.map(contact => {\n ContactController.subscribeToContact(contact, this.socket);\n\n return ContactController.getContactData(\n contact,\n this.socket.request.user.id\n );\n });\n\n const contacts = await Promise.all(contactPromiseList);\n this.socket.emit(\"GetContactListDone\", contacts);\n } catch (error) {\n console.error(error.message);\n }\n });\n }", "function getPeople() {\n\treturn [ 'John', 'Beth', 'Mike'];\n}", "get contactFolders() {\r\n return new ContactFolders(this);\r\n }", "function loadCities(contacts) {\n if (contacts.length <= 0) return;\n var filterOptions = document.querySelector(\"#filterOptions\");\n var trackingList = [];\n\n var _iterator = _createForOfIteratorHelper(contacts),\n _step;\n\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var contact = _step.value;\n var city = contact.address.city;\n\n if (!trackingList.includes(city)) {\n trackingList.push(city);\n filterOptions.innerHTML += \"<option value ='\".concat(city, \"'>\").concat(city, \"</option>\");\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n}", "async getCustomers() {\n const customers = await this.request('/vehicles', 'GET');\n let customersList = [];\n if (customers.status === 'success' && customers.data !== undefined) {\n customersList = customers.data\n .map(customer => customer.ownerName)\n .filter((value, index, self) => self.indexOf(value) === index)\n .map(customer => ({\n label: customer,\n value: customer\n }));\n }\n return customersList;\n }", "function getAllSearchedContacts() {\n var searchInput = document.getElementById(\"searchbar\").value;\n ContactsController.Search(searchInput, onSearchContacts);\n}", "function viewContact() {\n let searchResultList = search()\n console.log(`The person are ${searchResultList}`)\n}", "function displayContacts() {\n let clickContact = document.getElementsByClassName('contact');\n let displayList = document.getElementsByClassName(\"addressInput\");\n let displayEditButtons = document.getElementsByClassName(\"editButton\");\n let displayDeleteButtons = document.getElementsByClassName(\"deleteButton\");\n let contact_div = document.getElementsByClassName(\"contactName\");\n\n for (let x = 0; x < clickContact.length; x++) {\n let item = clickContact[x];\n item.onclick = function (event) {\n if (displayList[x].style.display === 'none') {\n displayList[x].style.display = 'block';\n displayEditButtons[x].style.display = 'inline-block';\n displayDeleteButtons[x].style.display = 'inline-block';\n contact_div[x].style.padding = \"16px 5px\";\n\n } else {\n displayList[x].style.display = 'none';\n displayEditButtons[x].style.display = 'none';\n displayDeleteButtons[x].style.display = 'none';\n contact_div[x].style.padding = \"0\";\n\n }\n }\n\n }\n }", "function loadContacts() {\n// clear the previous list\n// grab the tbody element that will hold the new list of addresss\n// Make an Ajax GET call to the 'addresss' endpoint. Iterate through\n// each of the JSON objects that are returned and render them to the\n// summary table.\n $.ajax({\n url: \"address\"\n }).success(function (data, status) {\n fillAddressTable(data, status);\n });\n}" ]
[ "0.83700484", "0.79109913", "0.76827186", "0.7411142", "0.7411142", "0.73865044", "0.72450215", "0.71513414", "0.71374464", "0.7053995", "0.70517385", "0.7032372", "0.7021278", "0.69623154", "0.6917967", "0.68560165", "0.6765175", "0.6759798", "0.6744462", "0.6718358", "0.67055136", "0.6669391", "0.66587067", "0.6654417", "0.6603052", "0.6552451", "0.65514016", "0.6524267", "0.6417054", "0.64166933", "0.6402915", "0.63368195", "0.63366795", "0.63321835", "0.6253462", "0.62443155", "0.624426", "0.6240502", "0.62309176", "0.6204018", "0.6185965", "0.61673224", "0.61637414", "0.61387795", "0.6090224", "0.6090224", "0.60771495", "0.60757667", "0.60755944", "0.60585576", "0.6043098", "0.6042161", "0.6010083", "0.60099626", "0.59908766", "0.5982307", "0.59731054", "0.59677815", "0.5936291", "0.5934812", "0.5931232", "0.59139717", "0.59020466", "0.59017557", "0.589688", "0.58189815", "0.58114356", "0.57944196", "0.5787147", "0.5783287", "0.5776619", "0.5774518", "0.5771517", "0.5769739", "0.57598853", "0.5757401", "0.57454145", "0.57251793", "0.571971", "0.5715678", "0.57080764", "0.5698497", "0.5697106", "0.5692035", "0.56835526", "0.5667855", "0.56655777", "0.56463313", "0.5639229", "0.56278837", "0.56132674", "0.560884", "0.5607357", "0.5601151", "0.55933726", "0.5592618", "0.5592281", "0.5572793", "0.557275", "0.5568872" ]
0.8267165
1
SEARCHES FOR THE CONTACT WITH THE ALIAS ENTERED
function find() { console.log(getContacts()); var alias = $('#contactAlias').val(); //if valid alias if (alias && alias != '' && alias != undefined) { $.getJSON(uri + '/' + alias) .done(function (data) { $('#contact').text(formatItem(data)); }) .fail(function (jqXHR, textStatus, err) { $('#contact').text('Error: ' + err); }); } //if INVALID value for alias, output error message else { $('#contact').text('Error: Cannot search for invalid or no alias.') } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function searchName(name){\n var nameABC = change_alias(name).toLowerCase();\n for(let contact of listContact)\n {\n if(change_alias(contact.Name).toLowerCase().indexOf(nameABC)!== -1)\n console.log(contact);\n }\n}", "function searchContact(ev) {\n setContacts(contacts.filter((_) => _.name.toLowerCase().match(ev.toLowerCase())));\n }", "function searcContactName() {\r\n $('.search-contact').keyup( function() {\r\n // Inserisco il valore da cercare\r\n var searchQuery = $('input.search-contact').val().toLowerCase();\r\n\r\n // Lista di tutti i contati\r\n var allContacts = $('li.contact-js');\r\n\r\n // Il ciclo di verifica per tutti i contatti\r\n allContacts.each( function() {\r\n\r\n // Seleziono il nome del contatto ('.contact-name')\r\n var contactName = $(this).find('.contact-name').text().toLowerCase();\r\n\r\n if( contactName.includes(searchQuery) ) {\r\n // Viusalizzo il contatto se contiene il valore inserito nella search\r\n $(this).show();\r\n } else {\r\n // Nascondo altri contatti\r\n $(this).hide();\r\n }\r\n }); // End each\r\n }); // End keyup function\r\n } // End searcContactName() function", "function findContact(searchTerm){\n searchResults = [];\n\n var list = contacts.find().fetch();\n console.log(list);\n for(var i=0; i < list.length; i++)\n {\n obj = list[i];\n if(obj.firstname == searchTerm || obj.lastname === searchTerm || obj.gender === searchTerm || obj.email === searchTerm || obj.number === searchTerm || obj.latitude === searchTerm || obj.longitude === searchTerm)\n {\n searchResults.push(obj);\n }\n }\n Session.set(\"searchRes\",searchResults);\n}", "function searchNames() {\r\n\r\n Word.run(function (context) {\r\n\r\n // Mettez en file d'attente une commande pour obtenir la selection actuelle, puis\r\n // creez un objet de plage proxy avec les resultats.\r\n var body = context.document.body;\r\n context.load(body, 'text');\r\n\r\n // Empties the politicians already found since we \"relaunch\" the search.\r\n alreadyFoundPoliticians = {};\r\n\r\n $('#politicians').empty(); // Empties all the content of the panel.\r\n\r\n return context.sync().then(function () {\r\n\r\n var wholeText = body.text; // Get the whole text of the body as a String\r\n\r\n // Launch the search\r\n inspectText(wholeText, context);\r\n\r\n }).then(context.sync);\r\n })\r\n .catch(errorHandler);\r\n\r\n }", "function search( input ){\n // select chat list -> contacts -> each( user name ? search input )\n $('.chat-list .contact').each( function() {\n //var filter = this.innerText; // < - You, Me , I ( for log user )\n //var _val = input[0].value.toUpperCase();\n\n if ( this.innerText.indexOf( input[0].value.toUpperCase() ) > -1)\n this.style.display = \"\";\n else this.style.display = \"none\";\n\n });\n\n}", "function searchByName(name) {\n removeAllChild(\"search_display\");\n for (var i = 0; i < lst.length; i++) {\n if (lst[i].name.includes(name))\n addOneSubject(lst[i]);\n }\n}", "function searchTerm(){\n \n }", "function searchContactName(txt) {\n var container = $(\".box-contatto\");\n for (var i = 0; i < container.length; i++) {\n if ($(container[i]).find(\".title\").html().toLowerCase().includes(txt) == false) {\n $(container[i]).hide();\n } else {\n $(container[i]).show();\n }\n }\n}", "function searchContact() {\n let searchResultList = search()\n console.log(`The person are ${searchResultList.map(contact => contact.firstName)}`)\n}", "function searchContact() {\n let searchVal = document.getElementById('txtFilter').value.toLowerCase();\n subADDRESSES = [];\n\n for (i=0; i<ADDRESSES.length; i++) {\n\n let name = ADDRESSES[i].name.toLowerCase();\n let surname = ADDRESSES[i].surname.toLowerCase();\n let phone = ADDRESSES[i].phone.toLowerCase();\n let address = ADDRESSES[i].address.toLowerCase();\n\n if (name.includes(searchVal) || surname.includes(searchVal) ||\n phone.includes(searchVal) || address.includes(searchVal)) {\n subADDRESSES.push(ADDRESSES[i]);\n }\n\n };\n displayTbl(subADDRESSES);\n}", "static async search(name) {\n if (name.trim() === \"\") {\n throw new Error(\"Please enter a name.\");\n }\n\n let searchTerms = name.trim().split(' ');\n if (searchTerms.length === 2) {\n\n let searchFirst = `%${searchTerms[0]}%`;\n let searchLast = `%${searchTerms[1]}%`;\n\n const results = await db.query(\n `SELECT id, \n first_name AS \"firstName\", \n last_name AS \"lastName\", \n phone, \n notes\n FROM customers\n WHERE (first_name ILIKE $1 AND last_name ILIKE $2)\n OR (first_name ILIKE $2 AND last_name ILIKE $1)\n ORDER BY last_name, first_name`,\n [searchFirst, searchLast]\n );\n if (results.rows.length === 0) {\n throw new Error(\"Customer not found.\")\n }\n return results.rows.map(c => new Customer(c));\n }\n\n else if (searchTerms.length === 1) {\n let searchTerm = `%${searchTerms[0]}%`;\n\n const results = await db.query(\n `SELECT id, \n first_name AS \"firstName\", \n last_name AS \"lastName\", \n phone, \n notes\n FROM customers\n WHERE first_name ILIKE $1 OR last_name ILIKE $1\n ORDER BY last_name, first_name`,\n [searchTerm]\n );\n if (results.rows.length === 0) {\n throw new Error(\"Customer not found.\")\n }\n return results.rows.map(c => new Customer(c));\n }\n\n else {\n throw new Error('Please enter one or two search terms.');\n }\n }", "function matchDiplom(params, data) {\n params.term = params.term || '';\n // If there are no search terms, return all of the data\n if (params.term.replace(/\\s+/g, '') === '') {\n return data;\n }\n // Do not display the item if there is no 'text' property\n if (typeof data.text === 'undefined') {\n return null;\n }\n if (data.text.toUpperCase().replace(/\\s+/g, '').indexOf(params.term.toUpperCase().replace(/\\s+/g, '')) > -1) {\n return data;\n }\n return null;\n}", "handlerSearch(search){\n const filterContacts = this.state.contacts.filter( contact =>\n contact.name.toLowerCase().includes(search.toLowerCase())\n || contact.email.toLowerCase().includes(search.toLowerCase())\n || contact.website.toLowerCase().includes(search.toLowerCase())\n || checkPhone(contact.phone, search)\n || contact.company.name.toLowerCase().includes(search.toLowerCase())\n || contact.address.country.toLowerCase().includes(search.toLowerCase())\n );\n this.setState({filterContacts});\n }", "function searchingFor(term){\n return function(x){\n return x.post_content.toLowerCase().includes(term.toLowerCase()) || !term;\n }\n}", "function searchCoffeeNames(e) {\n e.preventDefault();\n var userCoffeeName = document.getElementById(\"user-search\").value;\n var filteredNames = [];\n coffees.forEach(function(coffee) {\n\n if(coffee.name.toLowerCase().includes(userCoffeeName.toLowerCase())){\n filteredNames.push(coffee);\n\n }\n });\n divBody.innerHTML = renderCoffees(filteredNames);\n}", "function searchContacts() {\n contactsList = web.get_lists().getByTitle(\"WingtipAppContacts\");\n\n var textToSearch = $(\"#textToSearch\").val();\n var camlQuery = new SP.CamlQuery();\n var q = '<View><Query><Where><Contains><FieldRef Name=\"WingtipAppContactDescription\" /><Value Type=\"Text\">' + textToSearch + '</Value></Contains></Where></Query></View>';\n camlQuery.set_viewXml(q);\n listItems = contactsList.getItems(camlQuery);\n clientContext.load(listItems);\n\n clientContext.executeQueryAsync(onSearchQuerySucceeded, onSearchQueryFailed);\n}", "function searchRecom() {\n\t// store keyword in localSession\n\twindow.localStorage.setItem('kw', keyWord);\n\t// Fuse options\t\t\t\t\n\tvar options = {\n\t\tshouldSort: true,\n\t\ttokenize: true,\n\t\tthreshold: 0.2,\n\t\tlocation: 0,\n\t\tdistance: 100,\n\t\tincludeScore: true,\n\t\tmaxPatternLength: 32,\n\t\tminMatchCharLength: 2,\n\t\tkeys: [\"title.recommendation_en\",\n\t\t\t \"title.title_recommendation_en\",\n\t\t\t \"topic.topic_en\"]\n\t};\n\t//Fuse search\n\tvar fuse = new Fuse(recommends, options); //https://fusejs.io/\n\tconst results = fuse.search(keyWord);\n\treturn results;\n}", "function search() {\n\t\n}", "function searchEmployee(e) {\r\n\r\n e.preventDefault();\r\n\r\n // get the term that a user typed \r\n var term = form.elements[0].value.toUpperCase();\r\n\r\n // console.log(term);\r\n\r\n // get all element whose class name is card\r\n var employees = document.querySelectorAll('.card');\r\n\r\n // traverse all element of employees to find matching employee\r\n employees.forEach(emp => {\r\n\r\n // get the name of employee\r\n const name = emp.querySelector('.card-name').innerText.toUpperCase();\r\n\r\n // if the name includes the term\r\n if (name.indexOf(term) > -1) {\r\n // show the employee\r\n emp.style.display = 'flex';\r\n\r\n } else { // if the name does not include the term\r\n // set the employee unvisible\r\n emp.style.display = 'none';\r\n }\r\n })\r\n}", "onSearch(value) {\n let tempPhones = [];\n for (let i = 0; i < this.state.phonesTemp.length; i++) {\n // If the phone's name contains the name entered then add it\n if (this.state.phonesTemp[i].name.toLowerCase().includes(value.toLowerCase())) {\n tempPhones.push(this.state.phonesTemp[i]);\n }\n }\n this.setState({ phones: tempPhones }); // Render phones mathing criteria\n }", "function findMatches(wordToMatch, names){\n\t\treturn names.filter(restaurants => {\n\t\t\tconst regex = new RegExp (wordToMatch, 'gi');\n\t\t\treturn restaurants.name.match(regex)\n\t\t});\n\t}", "function findAcronyms() {\n// Searches text for defined acronyms by looking for text that contains capitalized letters that then are \n// repeated following the text (or that precede the text), for example: \n// \"we observed White Dwarf Stars (WDS), ...\" or \"we observed WDS (White Dwarf Stars), ....\"\n// If such are identified, the acronym is placed in a special category within the index that is not used as\n// an ordinary index word, but rather as a \"re-router\" to the words for which the acronym stands for. In the\n// index, the acronym is entered as an entry but with a type=acro, and another field that no other entry has,\n// \"acroDef\", will hold the words that the acronym takes the place of. The words are delimited by \"_\" with\n// the abbreviated paper ID in front, ie \"454|white_dwarf_star\". Every time the acronym is found in that paper,\n// the all the words in standsFor will be uodated with the location information. If the acronym is found in\n// another paper that does NOT have its own acronym entry, let's say for example that paper 334 also mentioned\n// WDS but fails to define them. If WDS has **no** alternative meaning in the xLtr, but a match is made (but\n// from the acronum of another paper), then that paper will inherit the knowledge of paper 454 and have all occurances\n// of \"WDS\" be indexed to \"white_dwarf_star\". KIf there are multiple definitions of WDS within the \"acronum\" index\n// entry and the paper fails to have its own definition, then the characters will remain un-identified. OK, the\n// function here is just to find those acronyms with their definitions ... the main program will make sense of it all! \n xLtr.push({\"type\":\"acro\", \"priority\":\"1\",\n \"indx\":function(text, startPos) {\n this.endMatch = \"-1\";\n this.startDef = \"-1\";\n this.endDef = \"-1\";\n var smallWords = ['aka','al','am','an','and','are','as','at','be','by','do','eg','et','etal','etc',\n 'go','he','ie','if','in','io','is','it','me','my','no','ok','on','or','ox','pi',\n 'qi','so','to','we','xi'];\n var linkedTo = [];\n var from = [];\n var i = 0;\n var j = 0;\n var k = 0;\n var a1 = 0;\n var a2 = 0;\n var w1 = 0;\n var w2 = 0;\n var tst = '';\n var t = '';\n var endMatch = -1;\n var acroPos1 = [];\n var wordsPos1 = [];\n var acroPos2 = [];\n var wordsPos2 = [];\n var acroPos = [];\n var wordsPos = [];\n var aPos = [];\n var wPos = [];\n var aTmp = '';\n var wTmp = '';\n var dist = [];\n var alength = [];\n var acro = '';\n var acroDef = '';\n var fullAcro = false;\n var twoWordMin = false;\n var noCherryPicking = true;\n var noSkippedWords = true;\n var caseMatch = false;\n var acroCase = false;\n var twoChars = false;\n var notShortWord = false;\n var notSymbol = false;\n var startSentence = false;\n// Strip out text starting from startPos to the location of a period, question mark, exclamation mark to the right\n// of startPos.\n var txt = text.slice(startPos);\n var tmp = txt.match(/(?:[\\.\\?\\!])(?:(?: [A-Z])|(?: $)|(?:$))/);\n if (tmp) {txt = txt.slice(0,tmp.index); }\n// filter the text, eliminating everything exept alpha-numeric and whitespace\n tmp = JSON.parse(filterTheText('Aa0 ',txt));\n txt = tmp[0];\n txtPos = tmp[1];\n// Convert text to an array of characters.\n txt = txt.split('');\n// make another array of same length as txt that assigns a word id to each letter. Any non-alphanumeric characters\n// take on the word ID of the character that is to the left of them.\n var wordIds = [];\n wordIds.push(0);\n for (i = 1; i < txt.length; i++) {\n if (txt[i-1].match(/ /) && txt[i].match(/[^ ]/)) {\n wordIds.push(wordIds[i-1]+1); // start new word\n } else {\n wordIds.push(wordIds[i-1]); } // retain same word id as prev. character\n }\n// construct an array similar to wordIds, but one that records the position where the word started rather than \n// a sequence of incrementing values\n var wordStarts = [];\n wordStarts.push(0);\n for (i = 1; i < txt.length; i++) {\n if (txt[i-1].match(/ /) && txt[i].match(/[^ ]/)) {\n wordStarts.push(i); // start new word\n } else {\n wordStarts.push(wordStarts[i-1]); } // retain same value as prev. character\n }\n for (i = 0; i < txt.length-1; i++) {\n if (txt[i].match(/[A-Za-z0-9]/)) {\n// get all the text to the right of the ith character\n tmp = txt.slice(i+1).reduce(function(x1,x2,x3) {\n// locate all the matches in the text with this ith character. At this point, the match is case-insensitive\n if (x2.match(/[A-Za-z0-9]/) && wordStarts[x3+i+1] > wordStarts[i] &&\n x2.toLowerCase() == txt.slice(i,i+1)[0].toLowerCase()) {x1.push(x3+i+1);} return x1;},[]); \n if (tmp.length > 0) {\n linkedTo.push(tmp);\n from.push(i); }\n }\n }\n// - - - - - - - - - - - - - - - - - - - - - - - -\n if (linkedTo.length == 0) {return ''; }\n// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\n// Now map out all the possible \"paths\" by which an acronym's letters could be matched up with \n// legitimate characters from preceeding word definitions:\n for (i = 0; i < linkedTo[0].length; i++) {\n if (wordStarts[linkedTo[0][i]] == linkedTo[0][i]) {\n acroPos1.push([linkedTo[0][i]]);\n wordsPos1.push([from[0]]); }\n }\n for (i = 1; i < linkedTo.length; i++) { // step through each character in the test, from left to right\n aPos = [];\n wPos = [];\n for (j = 0; j < linkedTo[i].length; j++) {\n for (k = 0; k < acroPos1.length; k++) {\n// need to make combinations for each of these with all the acroPos that has been rolled up \n// to this point. In order to be included, the jth value in the ith linkedTo needs to meet\n// the following criteria: \n// * characters associated with the acronym must be all be associated with the same \"word\" AND occur sequentially. \n// * all definition words must have their first letter involved in the acronym (which may be upper or lowercase).\n// * if there are uppercase letters somewhere in the middle of a word, those letters must also appear the acronym\n// as well as the first character of that word.\n// * letters other than the first letter and uppercase letters within definition words are allowed so long as the\n// letter(s) to the left of them in the word are also present in the acronym.\n aTmp = acroPos1[k];\n aTmp = aTmp[aTmp.length-1];\n wTmp = wordsPos1[k];\n wTmp = wTmp[wTmp.length-1];\n if ( (wordStarts[linkedTo[i][j]] == wordStarts[aTmp] && // acronym within single word\n linkedTo[i][j] == aTmp + 1 && // sequential acronym letters\n wordStarts[from[i]] < wordStarts[aTmp] && // different location from acronym\n from[i] > wTmp) && // char in def must be right of prev char\n ((wordStarts[from[i]] == from[i]) || // first letter of a word ... or ...\n (txt.slice(from[i],from[i]+1)[0].match(/[A-Z0-9]/) && // is uppercase char or number that ...\n wordStarts[from[i]] == wordStarts[wTmp]) || // is part already-represented word ... or...\n (from[i] == wTmp + 1)) ) { // is part of sequence w/ one of the above 2 cases \n aPos.push(acroPos1[k].concat([linkedTo[i][j]]));\n wPos.push(wordsPos1[k].concat([from[i]])); }\n }\n }\n if (aPos.length > 0) {\n acroPos1 = acroPos1.concat(aPos);\n wordsPos1 = wordsPos1.concat(wPos); }\n }\n acroPos2 = [];\n wordsPos2 = [];\n for (i = 0; i < linkedTo[0].length; i++) {\n if (wordStarts[linkedTo[0][i]] == linkedTo[0][i]) {\n wordsPos2.push([linkedTo[0][i]]);\n acroPos2.push([from[0]]); }\n }\n for (i = 1; i < linkedTo.length; i++) { // step through each character in the test, from left to right\n aPos = [];\n wPos = [];\n for (j = 0; j < linkedTo[i].length; j++) {\n for (k = 0; k < acroPos2.length; k++) {\n aTmp = acroPos2[k];\n aTmp = aTmp[aTmp.length-1];\n wTmp = wordsPos2[k];\n wTmp = wTmp[wTmp.length-1];\n if ( (wordStarts[from[i]] == wordStarts[aTmp] && // acronym is one word\n from[i] == aTmp + 1 && // sequential acronym letters\n wordStarts[linkedTo[i][j]] > wordStarts[aTmp] && // different location from acronym\n linkedTo[i][j] > wTmp) && // the next char in def to right of last one\n ((wordStarts[linkedTo[i][j]] == linkedTo[i][j]) || // first letter of a word ... or ...\n (txt.slice(linkedTo[i][j],linkedTo[i][j]+1)[0].match(/[A-Z0-9]/) && // is uppercase char or number that ... \n wordStarts[linkedTo[i][j]] == wordStarts[wTmp]) || // is part of already-represented word ... or ...\n (linkedTo[i][j] == wTmp + 1))) { // is part of sequence w/ one of the above 2 cases \n aPos.push(acroPos2[k].concat([from[i]]));\n wPos.push(wordsPos2[k].concat([linkedTo[i][j]]) ); }\n }\n }\n if (aPos.length > 0) {\n acroPos2 = acroPos2.concat(aPos);\n wordsPos2 = wordsPos2.concat(wPos); }\n } \n// combine the findings from both kinds of searches\n acroPos = acroPos1.concat(acroPos2);\n wordsPos = wordsPos1.concat(wordsPos2);\n// We can immediately weed out any 1-element entries:\n acroPos = acroPos.filter(z => z.length > 1);\n wordsPos = wordsPos.filter(z => z.length > 1);\n// Now test any found matches to insure compliance with other constraints:\n// * [fullAcro] each character within the group of chars associated with the acronym must have a counterpart in the def words\n// * [twoWordMin] there must be at least 2 definition words\n// * [noCherryPicking] there cannot be any words larger than 3 letters laying between def words\n// * [noSkippedWords] there cannot be more than 3 words of length greater than 3 characters between the end of the\n// definition words and the beginning of the acro\n// * [caseMatch] If the acronym has a mixture of lower/upper case characters, then there must be an exact case match\n// to those corresponding letters in the definition words. Likewise, if the definition words has a mixture of \n// cases, then the acronym must provide an exact character-to-character case match, with the following exception:\n// if the only uppercase letter in the definition words is the very first letter (e.g., likely the beginning of\n// a sentence), and the acronym does NOT have a case-mixture, then a case-match is irrelevant. If the acronym\n// has all caps or all lowercase characters, a case-match is irrelevant so long as the definition words do \n// not have a case-mixture (disregarding the case of the first letter in the def. words). \n// * [acroCase] If the acronym has any uppercase letters, there must be more uppercase than lowercase. If the \n// acronym has only 2 characters, both must be uppercase if one of them is.\n// * [twoChars] if the acronym is only 2 letters, special precautions must be taken to insure that it is not just an ordinary\n// 2-letter word (like \"to\" or \"so\" or \"at\"). The 2-letter acronym must either consist of all consonants or \n// all vowels. Note that this constraint could likely remove viable acronyms from the index, but the risk of \n// false-positive matches is just too high to accept without imposing such rules.\n// * [notShortWord] acronym can't be among the hardwired list of common \"small words\" (like \"etc\")\n// * [notSymbol] acronym can't be mistaken for a chemical symbol (like \"Ne\" or \"He\")\n for (i = 0; i < acroPos.length; i++) {\n wTmp = wordsPos[i].map(z => txt.slice(z,z+1)[0]).join('');\n aTmp = acroPos[i].map(z => txt.slice(z,z+1)[0]).join('');\n fullAcro = false;\n twoWordMin = false;\n noCherryPicking = true;\n caseMatch = false;\n acroCase = false;\n twoChars = false;\n notShortWord = false;\n notSymbol = false;\n noSkippedWords = true;\n startSentence = false;\n// get the length of the character grouping associated with the acronym itself by finding in the word ID all matches\n// to the word ID value that the acronym characters have:\n tmp = wordIds.reduce(function(x1,x2,x3) {\n if (x2 == wordIds[acroPos[i][0]] && txt.slice(x3,x3+1)[0].match(/[A-Za-z0-9]/)) {x1.push(x2);} return x1;},[]);\n if (tmp.length == acroPos[i].length) {fullAcro = true; }\n// See if an uppercase letter exists in the original text just before or just after the identified acro. If so, and it was skipped\n// over, then fullAcro gets turned back to false:\n if (startPos > 0 && text.charAt(txtPos[acroPos[i]]).match(/[A-Z]/)) {fullAcro = false; }\n if (startPos < text.length-1 && text.charAt(txtPos[Math.max(... acroPos[i])]).match(/[A-Z]/)) {fullAcro = false; }\n// get a list of all the word IDs associated with the definition words:\n tmp = wordsPos[i].map(z => wordIds[z]);\n if (tmp !== undefined && tmp && tmp.length > 0 && ([... new Set(tmp)]).sort().length >= 2) {twoWordMin = true;}\n// If these definition word IDs are not consequetive, determine how long the words are that are missing from this list\n tst = [];\n if (twoWordMin) {\n for (j = Math.min(... tmp)+1; j < Math.max(... tmp); j++) {\n if (tmp.indexOf(j) == -1) {tst.push(j); }\n }\n }\n for (j = 0; j < tst.length; j++) {\n tmp = wordIds.reduce(function(x1,x2,x3) {\n if (x2 == j && txt.slice(x3,x3+1)[0].match(/[A-Za-z0-9]/)) {x1.push(x2);} return x1;},[]);\n if (tmp.length <= 3) {noCherryPicking = false; }\n }\n// determine the range of characters between the end of the definition words and the acronym:\n tmp = acroPos[i].length;\n a1 = acroPos[i][tmp-1];\n w1 = wordsPos[i][0];\n a2 = acroPos[i][0];\n tmp = wordsPos[i].length;\n w2 = wordsPos[i][tmp-1];\n tmp = '';\n if (wordIds[a1] < (wordIds[w1]-1)) {\n tmp = txt.reduce(function(x1,x2,x3) {\n if (wordIds[x3] > wordIds[a1] && wordIds[x3] < wordIds[w1]) {x1.push(x2);} return x1;},[]);\n tmp = tmp.join('').replace(/[^A-Za-z0-9 ]/g,'').replace(/ +/g,' ').trim();\n } else if (wordIds[w2] < (wordIds[a2]-1)) {\n tmp = txt.reduce(function(x1,x2,x3) {\n if (wordIds[x3] > wordIds[w2] && wordIds[x3] < wordIds[a2]) {x1.push(x2);} return x1;},[]);\n tmp = tmp.join('').replace(/[^A-Za-z0-9 ]/g,'').replace(/ +/g,' ').trim(); }\n// If any of the in-between words had uppercase letters, then the test is failed:\n if (tmp.match(/[A-Z]/)) {noSkippedWords = false;}\n tmp =tmp.split(' ');\n tmp = tmp.filter(z => z.length > 3); // don't count words of 3 characters or less\n if (tmp.length > 3) {noSkippedWords = false; } // if more than 3 substantial words lay between acro and def, fail the test\n// For the below tests, need to determine if the definition words start at the beginning of sentence.\n if (startPos == 0) {\n startSentence = true;\n } else if (text.slice(0,startPos).trim() == '') {\n startSentence = true; \n } else if (startPos >= 2 && text.slice(startPos-2,startPos).trim() == '\\.') {\n startSentence = true; }\n if (aTmp == wTmp) {caseMatch = true; }\n if (aTmp.match(/^[A-Z0-9]+$/) && wTmp.match(/^[a-z0-9]+$/)) {caseMatch = true;}\n// If the definition words is a mix of cases that involves more than a capitalization of the start of a sentence,\n// do definition word characters case-match with the acronym characters?\n if (startSentence && aTmp.slice(1) == wTmp.slice(1)) {caseMatch = true; }\n// check the case of the acronym characters, make sure there is consistency\n if (aTmp.match(/^[A-Z0-9]+$/) || aTmp.match(/^[a-z0-9]+$/)) {acroCase = true; }\n if (aTmp.match(/[A-Z]/) && aTmp.match(/[a-z]/) && aTmp.match(/[A-Z]/g).length > aTmp.match(/[a-z]/g).length) {\n acroCase = true; }\n// Now check the acronym length:\n if (aTmp.length > 2) {twoChars = true;}\n if (!twoChars) {\n// If the acronym consists of all consonants or of all vowels, then it passes the twoChar test:\n tmp = acroPos[i].reduce(function(x1,x2,x3) {\n if (txt.slice(x3,x3+1)[0].match(/[aeiou]/i)) {x1.push('v')} else {x1.push('c')}; return x1;},[]);\n if (tmp.length > 0 && ([... new Set(tmp)]).length == 1) {twoChars = true;} }\n// Make sure that acronym does not match any of the common short words:\n if (smallWords.indexOf(aTmp) == -1) {notShortWord = true;}\n// Now check that the acronym is not actually a chemical symbol!\n tmp = xLtr.findIndex(z => z.reg !== undefined && z.symbol !== undefined && z.indx(aTmp,0) != '');\n if (tmp == -1) {notSymbol = true;} \n// Now tally up the scores and see if this acronym candidate failed ANY of the tests:\n if (!(fullAcro*twoWordMin*noCherryPicking*noSkippedWords*caseMatch*acroCase*twoChars*notShortWord*notSymbol)) {\n acroPos[i] = [-1];\n wordsPos[i] = [-1]; }\n }\n// Remove any -1 values:\n acroPos = acroPos.filter(z => z[0] != -1);\n wordsPos = wordsPos.filter(z => z[0] != -1);\n// If by now, there are more than 1 possibility for acronym and corresponding definition, then select whichever has the longest acronym.\n// If the acronym length is the same for all the matches, then select the one for which the words and the acronym are closest together. \n dist = [];\n alength = [];\n for (i = 0; i < acroPos.length; i++) {\n tmp = acroPos[i].map(z => txt.slice(z,z+1)[0]).join('');\n alength.push(tmp.length);\n if (acroPos[i][0] > wordsPos[i][0]) {\n tmp = wordsPos[i].length;\n dist.push(txt.slice(wordsPos[i][tmp-1]+1,acroPos[i][0]+1).join('').replace(/[^A-Za-z0-9 ]/g,'').length);\n } else {\n tmp = acroPos[i].length;\n dist.push(txt.slice(acroPos[i][tmp-1]+1,wordsPos[i][0]+1).join('').replace(/[^A-Za-z0-9 ]/g,'').length); }\n }\n for (i = 0; i < acroPos.length; i++) {\n if (alength[i] < Math.max(... alength)) {\n acroPos[i] = [-1];\n wordsPos[i] = [-1];\n alength[i] = -1;\n dist[i] = -1; }\n }\n acroPos = acroPos.filter(z => z[0] != -1);\n wordsPos = wordsPos.filter(z => z[0] != -1);\n dist = dist.filter(z => z != -1);\n alength = alength.filter(z => z != -1);\n tmp = dist.findIndex(z => z == Math.min(... dist)); // returns the first one to meet criteria \n acro = '';\n acroDef = '';\n if (tmp != -1) {\n acroPos = acroPos[tmp];\n wordsPos = wordsPos[tmp];\n acro = acroPos.map(z => txt.slice(z,z+1)[0]).join('');\n tmp = [... new Set(wordsPos.map(z => wordStarts[z]))];\n tmp = [Math.min(... tmp), Math.max(... tmp)];\n tmp[1] = tmp[1] + wordStarts.filter(z => z == tmp[1]).length;\n acroDef = txt.slice(tmp[0],tmp[1]).join('').replace(/[^A-Za-z0-9]/g,' ').trim();\n this.startDef = '' + (txtPos[tmp[0]] + startPos);\n this.endDef = '' + (txtPos[tmp[1]-1] + 1 + startPos);\n acroDef = acroDef.replace(/ +/,' ').trim();\n if (acroPos[0] > wordsPos[0]) {\n this.endMatch = \"\" + (txtPos[Math.max(... acroPos)] + 1 + startPos);\n } else {\n this.endMatch = this.endDef; }\n return acro + ' ' + acroDef.replace(/ /g,'\\_');\n } else {return ''; }\n } });\n return;\n }", "function doubleSearch () {}", "function performSearch(searchInput, names) {\r\n console.log(searchInput);\r\n console.log(names);\r\n var searchInput;\r\n\r\n for (let i = 0; i < names.length; i++) {\r\n names[i].classList.remove(\"match\");\r\n\r\n let match = searchInput.value.toLowerCase();\r\n\r\n\r\n if (searchInput.value.length !== 0 && names[i].textContent.toLowerCase().includes(match)) {\r\n names[i].classList.add(\"match\");\r\n }\r\n }\r\n}", "function searchEntries() {\n var search = document.getElementById(\"search\").value;\n // iterate through all entries\n for (var i = 0; i < contacts.length; i++) {\n // entry i is in div id=\"contact_{i}\"\n var entryDiv = document.getElementById(\"contact_\" + i); \n if (search.length > 0 && !contacts[i].contains(search)) {\n entryDiv.style.display = \"none\";\n }\n else {\n entryDiv.style.display = \"\"; \n } \n }\n}", "function viewContact() {\n let searchResultList = search()\n console.log(`The person are ${searchResultList}`)\n}", "function search(dataSet, searchWord) {\r\n\r\n //if is not email, capitalize name\r\n if ( !searchWord.includes(\"@\") ) {\r\n searchWord = capitalize(searchWord);\r\n }\r\n\r\n for(let row of dataSet) {\r\n for(let item in row) {\r\n let position = row[item].indexOf( searchWord );\r\n\r\n //if nothing is found returns -1\r\n if(position > -1) {\r\n return row;\r\n }\r\n }\r\n }\r\n}", "function search() {\n const text = this.value;\n if (text === '') {\n rows.forEach(row => row.style.display = null);\n return;\n }\n const length = names.length;\n const regex = new RegExp(text, 'gi');\n for (let i = 0; i < length; i++) {\n if (names[i].match(regex)) rows[i].style.display = null;\n else rows[i].style.display = 'none';\n }\n}", "function npcInRoomByAlias (id, alias) {\n var returnDescription;\n alias = alias.toLowerCase();\n for (var i = 0; i < npcs.length; i++) {\n if (npcs[i].roomid === id) {\n if(npcs[i]['name'].search(alias) != -1){\n returnDescription = npcs[i].description;\n }\n if(npcs[i]['alias'] == undefined){\n break;\n }\n if(npcs[i]['alias'][alias]){\n returnDescription = npcs[i].description;\n }\n }\n }\n\n return returnDescription;\n\n}", "function search() {\r\n\t\tlet query = $(\"#searchText\").val();\r\n\t\tquery = query.toLowerCase().trim();\r\n\r\n\t\tlet matches = [];\r\n\t\t\tfor(let course of COURSES) {\r\n\t\t\t\tlet coursetitle = course.course_title;\r\n\t\t\t\tcoursetitle = course.course_title.toLowerCase(); \r\n\r\n\t\t\t\tif(coursetitle.includes(query)) {\r\n\t\t\t\t\tmatches.push(course)\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\tdisplayCourses(matches);\r\n}", "function searchProduct(){\r\n \r\n var go = \"Thing(?i)\";\r\n \r\n submitProduct(go); \r\n \r\n }", "function doneTyping(){\n var cityInput = document.getElementById(\"city\");\n var results = [];\n for(var i = 0; i < dataObj.ponudjene.length; i++)\n {\n if(dataObj.ponudjene[i].toLowerCase().indexOf(cityInput.value.toLowerCase()) !== -1){\n results.push(dataObj.ponudjene[i]);\n }\n }\n showAutoComplete(results);\n}", "function query() {\n //reset text area\n $('#searchResults').text(\"\");\n\n contacts = getContacts(); //get existing list of contacts\n var searchCat = $('#selectSearch').val(); //search category (ie. Name)\n var query = $('#selectQuery').val().toLowerCase(); //user query\n var temp = 0; //counter to indicate if matches found\n if (query && query != '' && query != undefined) {\n for (var i = 0; i < contacts.length; i++) {\n var contact = contacts[i][searchCat]; //go through each contact\n if (contact.toLowerCase().indexOf(query) >= 0) {\n $('<ul>', { text: formatItem(contacts[i]) }).appendTo($('#searchResults'));\n temp++;\n }\n //end of loop\n }\n if (temp == 0) { $('#searchResults').text(\"No matches found\"); }\n } else {\n $('#searchResults').text('ERROR: query not valid.');\n }\n}", "function findSearch(searchTerm) {\r\n\r\nfor (var i = 0; i < jobList.length; i++) {\r\n if (jobList[i].JobTitle.toLowerCase().includes(searchTerm.toLowerCase()) || jobList[i].Category.toLowerCase().includes(searchTerm.toLowerCase() ) || jobList[i].Location.toLowerCase().includes(searchTerm.toLowerCase() ) ) {\r\n document.getElementById(i).style.display = \"block\"\r\n }\r\n else{\r\n document.getElementById(i).style.display = \"none\"\r\n }\r\n } \r\n}", "static async search(name) {\n const results = await db.query(\n `SELECT id, \n first_name AS \"firstName\", \n middle_name AS \"middleName\",\n last_name AS \"lastName\", \n phone, \n notes \n FROM customers\n WHERE UPPER(first_name) = $1 OR UPPER(middle_name) = $1 OR UPPER(last_name) = $1`,\n [name.toUpperCase()]\n );\n return results.rows.map(c => new Customer(c));\n }", "function suggestFilter(msg, arg){\r\n\t\tstate = 3;\r\n\t\thasTheWord = arg;\r\n\t\topenPanel(msg);\r\n\t}", "function searchByText(cGroup, textSearch) {\n cGroup.items.forEach(function (item, index) {\n switch (item.type) {\n case \"Contact\":\n if (item.firstName.toUpperCase() == textSearch ||\n item.lastName.toUpperCase() == textSearch ||\n (item.phoneNumbers.indexOf(textSearch) > -1)) {\n var htmlString = '<tr>';\n htmlString += '<td>' + item.firstName + '</td>';\n htmlString += '<td>' + item.lastName + '</td>';\n htmlString += '<td>' + item.phoneNumbers + '</td>';\n htmlString += '</tr>';\n document.getElementById('foundContactsTbody').innerHTML += htmlString;\n document.getElementById('alertWrp').className = 'hide';\n }\n break;\n case \"Group\":\n if (item.name.toUpperCase() == textSearch) {\n var htmlString = '<tr>';\n htmlString += '<td>' + item.name + '</td>';\n htmlString += '</tr>';\n document.getElementById('foundGroupsTbody').innerHTML += htmlString;\n document.getElementById('alertWrp').className = 'hide';\n }\n else {\n searchByText(item, textSearch);\n }\n break;\n }\n });\n }", "function searchNameText(e) {\n\tcardsList.innerHTML = ''; // clear the container for the new filtered cards\n\tbtnLoadMore.style.display = 'none';\n\tlet keyword = e.target.value;\n\tlet arrByName = dataArr.filter(\n\t\t(card) => { \n\t\t\treturn( \n\t\t\t\tcard.name.toLowerCase().indexOf(keyword.toLowerCase()) > -1 ||\n\t\t\t\tcard.artist.toLowerCase().indexOf(keyword.toLowerCase()) > -1 ||\n\t\t\t\tcard.setName.toLowerCase().indexOf(keyword.toLowerCase()) > -1 \n\t\t\t\t)\n\t\t}\t\n\t);\n\trenderCardList(arrByName);\n\tconsole.log(arrByName);\n}", "function searchUserLocal()\n {\n var typed = this.value.toString().toLowerCase(); \n var results = document.getElementById(\"results-cont\").children;\n\n if(typed.length >= 2)\n { \n for(var j=0; j < results.length; j++)\n {\n if(results[j].id.substr(0, typed.length).toLocaleLowerCase() !== typed)\n results[j].style.display = \"none\";\n else\n results[j].style.display = \"flex\";\n }\n } \n else\n {\n for(var i=0; i < results.length; i++)\n results[i].style.display = \"flex\";\n } \n }", "function substringMatcher(guests) {\n return function findMatches(q, cb) {\n var matches = [];\n\n guests.forEach(function (guest) {\n var searchParts = q.split(' ').map(lowercase);\n var hasSubstring = searchParts.some(function (searchTerm) {\n return (guest.fio.toLowerCase().indexOf(searchTerm) !== -1);\n });\n\n if (hasSubstring) {\n matches.push(guest);\n }\n });\n\n cb(matches);\n };\n }", "searchByName(string){\n \n const searchName = string.toLowerCase()\n const artists = this.artistas.filter( function(artista) { return artista.name.toLowerCase().includes(searchName)} );\n const albums = this.albums.filter( function(album) { return album.name.toLowerCase().includes(searchName)} );\n const tracks = this.tracks.filter( function(track) { return track.name.includes(searchName)} );\n const playlists = this.playsLists.filter( function(playlist) { return playlist.name.includes(searchName) } );\n \n \n return {artists: artists, albums: albums, tracks: tracks, playlists: playlists};\n \n }", "function countrySearch() {\n // Get the input element\n const ctryInput = document.getElementById(\"ctry\");\n\n //Add Event listener\n ctryInput.addEventListener(\"keyup\", e => {\n const ctryClone = ctryInput.value.toLowerCase();\n const names = document.querySelectorAll(\"main h1\");\n const content = document.querySelector(\".display-wrapper\");\n\n // Loop through each country name to see if it contains user search\n names.forEach(name => {\n const nameConverted = name.textContent.toLowerCase();\n if(nameConverted.indexOf(ctryClone) !== -1) {\n name.parentElement.parentElement.style.display = \"block\";\n } else {\n name.parentElement.parentElement.style.display = \"none\";\n }\n }); \n });\n}", "function lposearchUtil(item,toSearch)\n{\n /* Search Text in all 3 fields */\n\n return (item.companyname.toLowerCase().indexOf(toSearch.toLowerCase()) > -1 || item.lponum.toLowerCase().indexOf(toSearch.toLowerCase()) > -1 ) \n ? true : false ;\n}", "function findContact(){\n var name = readLineSync.question(\"Nhap vao thu ban muon tim kiem: \");\n if(isNaN(name) === false){\n searchPhone(name);\n }\n else{\n searchName(name);\n } \n }", "function searchAlts(keyword) {\n keyword = keyword.toLowerCase().trim();\n\n let contained = false;\n Object.keys(alts).forEach((key) => {\n if (key === keyword) {\n contained = true;\n }\n });\n\n let choice = [];\n if (contained) {\n choice = alts[keyword];\n } else {\n choice = [\"No results found for query '\" + keyword + \"'\"];\n }\n\n result = \"\";\n choice.forEach((i) => {\n result += \"<li>\" + i + \"</li>\";\n });\n\n document.getElementById(\"results\").innerHTML = result;\n}", "function search(trm) {\n\n \tterm = trm;\n //re-extend the search results holder, to show the results to the user\n $('#search_results_holder').height(300);\n //use the httpget function to grab the custom google search\n //JSON DATA\n //var json_dta = httpGet('https://www.googleapis.com/customsearch/v1?key=AIzaSyDM8_gZ-5DQVcBUt1y7qq_wAjUDbr4YSTA&cx=009521426283403904660:drg6vvs6o2a&q=' + trm);\n add_results('https://www.googleapis.com/customsearch/v1?key=AIzaSyDM8_gZ-5DQVcBUt1y7qq_wAjUDbr4YSTA&cx=009521426283403904660:drg6vvs6o2a&q=' + trm);\n }", "function searchCoffees() {\n var searchRoast = searchBox.value.toUpperCase(); //can be upper or lower case so it can detect all words inserted\n var filteredCoffees = []; //has to create an empty array so it can push whatever the search value is\n coffees.forEach(function(coffee) {\n if (coffee.name.toUpperCase().includes(searchRoast)) {\n filteredCoffees.push(coffee);\n console.log(filteredCoffees);\n }\n });\n tbody.innerHTML = renderCoffees(filteredCoffees);\n}", "handleSearch(e) {\n const searchQuery = e.target.value.toLowerCase();\n\n const displayedHeroes = HEROES.filter(hero => {\n const searchString = hero.name.toLowerCase() + hero.firstAppearance.toLowerCase();\n\n return searchString.indexOf(searchQuery) !== -1;\n });\n\n this.setState({\n displayedHeroes,\n });\n }", "function search_method(){\n var name = \"Jose Carlos Cruz Santiago\";\n var search = name.search(\"Cruz\");\n document.getElementById(\"search_method\").innerHTML=search;\n}", "function search(res, value) {\n\tres = res.filter(res => res.name.toLowerCase().includes(value.toLowerCase()) ||\n\t\tres.employeeId.toString().includes(value.toLowerCase()));\n\treturn res;\n}", "function searchEmployees(input) {\n let searchTerm = input.toLowerCase();\n let $employees = $('p:contains(' + searchTerm + ')').closest('li');\n $('li').hide();\n $employees.show();\n}", "function highlightLinkMatches(searchString) {\r\n var linksMatched = [];\r\n for (var i = 0; i < hintMarkers.length; i++) {\r\n var linkMarker = hintMarkers[i];\r\n if (linkMarker.getAttribute(\"hintString\").indexOf(searchString) == 0) {\r\n if (linkMarker.style.display == \"none\")\r\n linkMarker.style.display = \"\";\r\n var childNodes = linkMarker.childNodes;\r\n for (var j = 0, childNodesCount = childNodes.length; j < childNodesCount; j++)\r\n childNodes[j].className = (j >= searchString.length) ? \"\" : \"matchingCharacter\";\r\n linksMatched.push(linkMarker.clickableItem);\r\n } else {\r\n linkMarker.style.display = \"none\";\r\n }\r\n }\r\n return linksMatched;\r\n }", "findItem(query) {\n if (query === '') {\n return this.dataSearch.slice(0, 5);\n }\n const regex = new RegExp(`${query.trim()}`, 'i');\n return this.dataSearch.filter(film => film.name.search(regex) >= 0);\n }", "function getWord(word) {\n for (let i = 0; i < notes.length; i++) {\n if (notes[i].content.indexOf(word) != - 1) {\n console.log(`You are looking for id:${notes[i].id} ${notes[i].content}`);\n };\n }\n console.log(`You do not have any task including ${word}`);\n}", "function search_actor(search){\n\tvar sResult = [];\n\tfor(let films in search_results){\n\t\tvar film = search_results[films];\n\t\tif(film.folk){\n\t\tif(film.folk.toLowerCase().includes(search.toLowerCase())){\n\t\t\tactor.innerHTML+= \"<li><a href= \\\"show_movie.html?id=\" + films + \"\\\">\" + film.otitle + \"</a> </li> <br>\";\n\t\t}\n\t\t\t\n\t\t}\n\t}\n\tconsole.log(sResult);\n\t\n}", "function searchBarInputEventHandler()\n{\n\tvar\tsearchBarId = document.getElementById(\"searchBar\");\n\tsearchResults = [];\n\tvar searchFor = searchBarId.value.toLowerCase();\n\n\t// If there is actually something typed in the searchbar\n\tif(searchFor.length > 0)\n\t{\n\t\tsearching = true;\n\n\t\tcontactObjectLoop: for(contactObject in contactArray)\n\t\t{\n\t\t\t// If First and Last Name Both Match\n\t\t\tif((contactArray[contactObject].firstName.toLowerCase() + \" \" + contactArray[contactObject].lastName.toLowerCase()).search(searchFor) > -1)\n\t\t\t{\n\t\t\t\tsearchResults.push(contactArray[contactObject]);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// If Only One Property Matches\n\t\t\t\tcontactPropertyLoop: for(contactProperty in contactArray[contactObject])\n\t\t\t\t{\n\t\t\t\t\tif(typeof contactArray[contactObject][contactProperty] === \"string\")\n\t\t\t\t\t{\n\t\t\t\t\t\tif(contactArray[contactObject][contactProperty].toLowerCase().search(searchFor) > -1 && contactProperty != \"notes\")\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Add the contact that contained the property to the searchResults Array\n\t\t\t\t\t\t\t// as long as that property is of type string, and is not the \"notes\" property\n\t\t\t\t\t\t\tsearchResults.push(contactArray[contactObject]);\n\t\t\t\t\t\t\tbreak contactPropertyLoop;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tsearching = false;\n\t}\n\tupdateContactList();\n}", "function searchEmployee(input){\n\n cardsArray.map(card => {\n if (card.children[1].children[0].textContent.toLowerCase().search(input.toLowerCase()) !== -1) {\n card.style.display = \"\";\n } else {\n card.style.display = 'none';\n }\n });\n }", "search(event){\n this.placeService.textSearch({\n query: `${event.target.value}`,\n type: 'airport'\n }, this.handleSuggestions);\n }", "searchFn (haystack, needle) { // search function\r\n return haystack.toLowerCase().indexOf(needle.toLowerCase()) < 0;\r\n }", "function buscar(arg){\n\tquery = \"SELECT * FROM tabla WHERE nombre LIKE '%\"+arg+\"%' OR apellido LIKE '%\"+arg+\"%'\";\n\tloadData(query);\n}", "function filterNames(event) {\n let searchString = event.target.value.toLowerCase()\n\n $lis.forEach((li) => {\n if (li.querySelector('a').innerText.toLowerCase().includes(searchString)) {\n li.style.display = ''\n }\n else {\n li.style.display = 'none'\n }\n })\n}", "function searchPet() {\n var searchText = document.getElementById(\"search-text\").value\n\n document.getElementById(\"pets\").innerHTML=\"\";\n\n for (var i = 0; i < pets.length; i ++) {\n var pet = pets[i];\n\n if (\n pet.name.toLowerCase().includes(searchText.toLowerCase()) ||\n pet.owner.toLowerCase().includes(searchText.toLowerCase()) ||\n pet.phone.includes(searchText)\n \n ) {\n displayPet(pet);\n }\n }\n}", "queryChanged(newValue){\n let searchedItems = _.filter(this.items, i => {\n return i.text.toLowerCase().indexOf(newValue.toLowerCase()) != -1 ||\n i.fullText.toLowerCase().indexOf(newValue.toLowerCase()) != -1;\n });\n\n console.log(searchedItems);\n this.fetchMarkers(searchedItems, self.map);\n }", "function searchingFor(term){\n return function(x){\n return x.first_name.toLowerCase().includes(term.toLowerCase()) || !term;\n };\n}", "function searching() {\n $('.searchboxfield').on('input', function () { // connect to the div named searchboxfield\n var $targets = $('.urbacard'); // \n $targets.show();\n //debugger;\n var text = $(this).val().toLowerCase();\n if (text) {\n $targets.filter(':visible').each(function () {\n //debugger;\n mylog(mylogdiv, text);\n var $target = $(this);\n var $matches = 0;\n // Search only in targeted element\n $target.find('h2, h3, h4, p').add($target).each(function () {\n tmp = $(this).text().toLowerCase().indexOf(\"\" + text + \"\");\n //debugger;\n if ($(this).text().toLowerCase().indexOf(\"\" + text + \"\") !== -1) {\n // debugger;\n $matches++;\n }\n });\n if ($matches === 0) {\n // debugger;\n $target.hide();\n }\n });\n }\n\n });\n\n\n}", "function SearchFunctionality(input, list) {\n const names = document.querySelectorAll(\"h3\");\n const emails = document.querySelectorAll(\"span.email\");\n let searchNamesArray = [];\n for (i = 0; i < list.length; i++) {\n // Check if search bar input contains letters in names or emails arrays ...\n if (names[i].innerHTML.indexOf(input.value) > -1 || emails[i].innerHTML.indexOf(input.value) > -1) {\n searchNamesArray.push(list[i]);\n }\n // ... If not, set the list item to not display\n else {\n list[i].style.display = \"none\";\n }\n }\n ShowPage(searchNamesArray, 1);\n AppendPageLinks(searchNamesArray);\n\n // If there are no results that match the input, show the \"No results found\" message\n if (searchNamesArray.length == 0) {\n noResultsDiv.style.display = \"block\";\n }\n else {\n noResultsDiv.style.display = \"none\";\n }\n}", "function getAllSearchedContacts() {\n var searchInput = document.getElementById(\"searchbar\").value;\n ContactsController.Search(searchInput, onSearchContacts);\n}", "function searchAuthName() {\n let input, filter, table, tr, td, i;\n input = document.getElementById(\"searchAName\");\n filter = input.value.toUpperCase();\n table = document.getElementById('authorsTable');\n tr = table.getElementsByTagName(\"tr\");\n\n // Loop through all list items, and hide those who don't match the search query\n for (i = 0; i < tr.length; i++) {\n td = tr[i].getElementsByTagName('td')[1];\n if (td) {\n if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {\n tr[i].style.display = \"\";\n } else {\n tr[i].style.display = \"none\";\n };\n };\n };\n }", "function searchUtil(item,toSearch)\n{\n /* Search Text in all 3 fields */\n return ( item.name.toLowerCase().indexOf(toSearch.toLowerCase()) > -1 || item.Email.toLowerCase().indexOf(toSearch.toLowerCase()) > -1 || item.EmpId == toSearch\n ) \n ? true : false ;\n}", "function findQuotesMatching(quotes, searchTerm){\n //TODO: you must complete this function\n const result = quotes.filter((each)=>{\n if (each.quote.includes(searchTerm.toLowerCase())){\n return each.quote\n } \n })\n return result\n }", "function initAutoComplete(){\n // jQuery(\"#contact_sphinx_search\")\n // jQuery(\"#account_sphinx_search\")\n // jQuery(\"#campaign_sphinx_search\")\n // jQuery(\"#opportunity_sphinx_search\")\n // jQuery(\"#matter_sphinx_search\")\n jQuery(\"#search_string\").keypress(function(e){\n if(e.which == 13){\n searchInCommon();\n return jQuery(\".ac_results\").fadeOut();\n }\n });\n\n jQuery(\"#lawyer_search_query\").keypress(function(e){\n if(e.which == 13){\n searchLawyer();\n return jQuery(\".ac_results\").fadeOut();\n }\n });\n}", "function runSearch(e) {\n if (e.target.value === \"\") {\n // On empty string, remove all search results\n // Otherwise this may show all results as everything is a \"match\"\n applySearchResults([]);\n } else {\n const tokens = e.target.value.split(\" \");\n const moddedTokens = tokens.map(function (token) {\n // \"*\" + token + \"*\"\n return token;\n })\n const searchTerm = moddedTokens.join(\" \");\n const searchResults = idx.search(searchTerm);\n const mapResults = searchResults.map(function (result) {\n const resultUrl = docMap.get(result.ref);\n return { name: result.ref, url: resultUrl };\n })\n\n applySearchResults(mapResults);\n }\n\n}", "static searchHandler(searchTargetsSelector) {\n\t\tconst searchValue = this.value.trim();\n\t\tconst searchTargets = document.querySelectorAll(searchTargetsSelector);\n\t\tconst regex = new RegExp(searchValue, \"gi\");\n\n\t\tfor (const nameCell of searchTargets) {\n\t\t\tlet name = nameCell.textContent;\n\n\t\t\tif (searchValue === \"\") {\n\t\t\t\tnameCell.innerHTML = name;\n\t\t\t\tnameCell.parentNode.classList.remove(\"hide\");\n\t\t\t} else {\n\t\t\t\tconst searchedName = name.replace(regex, \"<strong class='highlight'>$&</strong>\");\n\t\t\t\tnameCell.innerHTML = searchedName;\n\n\t\t\t\tif (searchedName !== name) {\n\t\t\t\t\tnameCell.parentNode.classList.remove(\"hide\");\n\t\t\t\t} else {\n\t\t\t\t\tnameCell.parentNode.classList.add(\"hide\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "function SearchWrapper () {}", "function searchUser(){\n const searchEntry = [];\n const autoCompleteOptions =[];\n let searchBox = document.getElementById('recipient');\n let autocomplete = document.getElementById('dropdown');\n \n \n // iterate through user name data text to check for user input text match\n searchBox.addEventListener('keydown', function(e) { \n let inputKey = e.key.toLowerCase();\n \n const permittedKeys = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','backspace',' '];\n\n if (permittedKeys.includes(inputKey)){\n \n if (inputKey === 'backspace' && searchEntry.length === 0){\n searchUser();\n } else if (inputKey === 'backspace'){//get proper behaviour of backspace (delete last letter input)\n searchEntry.pop();\n autoCompleteOptions.pop();\n autocomplete.innerHTML = ``;\n } else {\n autocomplete.style.display = 'block';\n searchEntry.push(inputKey);\n let searchValue = searchEntry.join(''); \n autoCompleteOptions.length = 0;\n for (let i=0; i<allMembers.length; i++){\n for (let j=0; j<allMembers[i].name.length;j++){ \n let namePartial = allMembers[i].name.slice(j,j+searchValue.length).toLowerCase();//main part of search; iterate through all name arrays as partials\n if ((searchValue === namePartial) && !autoCompleteOptions.includes(allMembers[i].name)){// check match and not already included \n autocomplete.innerHTML =``;\n autoCompleteOptions.push(allMembers[i].name); \n for (let k=0; k<autoCompleteOptions.length; k++){ \n autocomplete.innerHTML += `<div>${autoCompleteOptions[k]}</div>`;//show the autocomplete suggestions \n } \n }\n } \n } \n }\n }\n });\n\n //Output the selected autocomplete suggestion as User Name address and move focus to message field\n /* --------------------------------------*/ \n\n autocomplete.addEventListener('click', e=>{\n autocomplete.style.display=\"none\";\n searchBox.value = e.target.textContent;\n message.focus(); \n });\n}", "function handleSearch() {\n const searchInput = $('#search-input')[0].value;\n people.forEach(person => {\n const name = `#${person.name.first}-${person.name.last}-card`;\n $(name).css('display', '');\n if (!(person.name.first + ' ' + person.name.last).includes(searchInput)) {\n $(name).css('display', 'none');\n }\n });\n}", "function search(text){\n searchString = text.toLowerCase();\n readerControl.fullTextSearch(searchString);\n }", "function searchGoogle(word) {\r\n var query = word.selectionText;\r\n\r\n}", "function searchByCity(contact) {\n return contact.city + \" \" + contact.firstName + \" \" + contact.lastName;\n }", "function dm_search(d_o1,ev,smId){var s=d_o1.value;d_ce=_dmvi(smId);var fromItem=null;if(ev.keyCode==13){fromItem=d_o1.prevItem;}if(!d_ce||s==\"-\"||d_o1.frase==s&&!fromItem){return;}_dmOOa(d_ce);d_o1.style.backgroundColor=\"\";d_o1.frase=s;if(!s){return;}d_iv=_dmlO(d_ce,s,dmSearch==2,fromItem);if(d_iv&&d_iv==fromItem){d_iv=_dmlO(d_ce,s,dmSearch==2,null);}if(d_iv){_dIO(d_iv);d_o1.prevItem=d_iv;}else{d_o1.style.backgroundColor=\"red\";d_o1.prevItem=null;}}", "function findMatch() {\r\n // take search input and make all lower case (so that we can check case-insensitively)\r\n // also split the word up into space separated bits to check for partial searches\r\n let searchName = document.getElementById(\"search\").value.toString().toUpperCase().trim();\r\n\r\n // build our output of people that match the search\r\n let result = \"\";\r\n\r\n // loop through our JSON object to see if we have name matches from our search\r\n\r\n for(let i = 0; i < people.length; i++) {\r\n if(people[i].name.toString().toUpperCase().startsWith(searchName)) {\r\n result += \"Name: \" + people[i].name + \"<br>\" +\r\n \"Address: \" + people[i].address + \"<br>\" +\r\n \"Age: \" + people[i].age + \"<br>\" +\r\n \"Interests: \" + people[i].interest + \"<br>\" +\r\n \"picture: \" + '<img src=\"'+people[i].img+'\" alt=\"pictures\">' + \"<br>\";\r\n }\r\n }\r\n // display result in the HTML\r\n if(result === \"\") {\r\n document.getElementById(\"result\").innerHTML = \"No match found.\";\r\n } else {\r\n document.getElementById(\"result\").innerHTML = result;\r\n }\r\n}", "function searchByName(people) {\n let firstName = promptFor(\"What is the person's first name?\", chars);\n let lastName = promptFor(\"What is the person's last name?\", chars);\n\n let foundPerson = people.filter(function (person) {\n if (person.firstName.toLowerCase() === firstName.toLowerCase() && person.lastName.toLowerCase() === lastName.toLowerCase()) {\n return true;\n } else {\n return false;\n }\n });\n return foundPerson;\n}", "function search_genomes (search_term) {\n\tcoge.services.search_genomes(search_term, { fast: true })\n\t\t.done(function(result) { // success\n\t\t\tif (result && result.genomes) {\n\t\t\t\tvar transformed = result.genomes.map(function(obj) {\n\t\t\t\t\tvar label = obj.info.replace(/&reg;/g, \"\\u00ae\"); // (R) symbol\n\t\t\t\t\treturn { label: label, value: obj.id };\n\t\t\t\t});\n\t\t\t\tif (focus == 'x') {\n\t\t\t\t\t$('#edit_xgenome')\n\t\t\t\t\t\t.autocomplete({source: transformed})\n\t\t\t\t\t\t.autocomplete(\"search\");\n\t\t\t\t} else if (focus == 'y') {\n\t\t\t\t\t$('#edit_ygenome')\n\t\t\t\t\t\t.autocomplete({source: transformed})\n\t\t\t\t\t\t.autocomplete(\"search\");\n\t\t\t\t} else if (focus == 'z') {\n\t\t\t\t\t$('#edit_zgenome')\n\t\t\t\t\t\t.autocomplete({source: transformed})\n\t\t\t\t\t\t.autocomplete(\"search\");\n\t\t\t\t}\t\t\t\t\n\t\t\t}\n\t\t})\n\t\t.fail(function() { // error\n\t\t\t//TODO\n\t\t});\n}", "function filterContacts(){\n matchedWords=[];\n filterActive=true;\n var value = $('#city-selector').val();\n var valueChecked = true;\n if( $('#show-active:checked').length == 0 ){\n valueChecked = false;\n };\n\n var searchWord = $('#name-search').val().trim();\n var pattern = new RegExp(searchWord, 'gi');\n for(var i=0; i<contactsData.length; i++){\n var testword = contactsData[i]['name'];\n if(testword.match(pattern)!= null){\n var filteredData = contactsData[i];\n if(value == 'none' && valueChecked == true){\n if(contactsData[i]['active'] == true){\n matchedWords.push(filteredData);\n }\n }else if( value == filteredData['city'] && (valueChecked == filteredData['active'] || filteredData['active']== undefined) ){\n matchedWords.push(filteredData);\n }else if(value == 'none' && (valueChecked == filteredData['active'] || filteredData['active']== undefined )) {\n matchedWords.push(filteredData);\n }\n }\n }\n //Perpiesiama nauja lentele su isfiltruotais duomenimis\n createTable(matchedWords);\n }", "function judgeByPartialMatch(word, query, queryStartWithUpper) {\n var _a, _b;\n if (query === \"\") {\n return {\n word: Object.assign(Object.assign({}, word), { hit: word.value }),\n value: word.value,\n alias: false,\n };\n }\n if (lowerStartsWith(word.value, query)) {\n if (queryStartWithUpper &&\n word.type !== \"internalLink\" &&\n word.type !== \"frontMatter\") {\n const c = capitalizeFirstLetter(word.value);\n return { word: Object.assign(Object.assign({}, word), { value: c, hit: c }), value: c, alias: false };\n }\n else {\n return {\n word: Object.assign(Object.assign({}, word), { hit: word.value }),\n value: word.value,\n alias: false,\n };\n }\n }\n const matchedAliasStarts = (_a = word.aliases) === null || _a === void 0 ? void 0 : _a.find((a) => lowerStartsWith(a, query));\n if (matchedAliasStarts) {\n return {\n word: Object.assign(Object.assign({}, word), { hit: matchedAliasStarts }),\n value: matchedAliasStarts,\n alias: true,\n };\n }\n if (lowerIncludes(word.value, query)) {\n return {\n word: Object.assign(Object.assign({}, word), { hit: word.value }),\n value: word.value,\n alias: false,\n };\n }\n const matchedAliasIncluded = (_b = word.aliases) === null || _b === void 0 ? void 0 : _b.find((a) => lowerIncludes(a, query));\n if (matchedAliasIncluded) {\n return {\n word: Object.assign(Object.assign({}, word), { hit: matchedAliasIncluded }),\n value: matchedAliasIncluded,\n alias: true,\n };\n }\n return { word: word, alias: false };\n}", "function searchwords(){var wd=jQuery.trim($('#searchwrods').val()).replace(/\\./g,''); if(''==wd || '客官要点什么'==wd){$('#searchwrods').attr('placeholder','客官还没点呢');return;}querywords(wd);}", "function search(lastName) {\n contactsLength = contacts.length;\n for (var i = 0; i < contactsLength; i++) {\n if (lastName === lastName) {\n printPerson(contacts[i]);\n }\n }\n}", "function search() {\n\t\t// clear the current contacts list\n\t\twhile (parent.lastChild)\n\t\t\tparent.removeChild(parent.lastChild);\n\t\txhttp.open(\"POST\", \"http://students.engr.scu.edu/~adiaztos/resources/contacts.php?query=\" + document.getElementById(\"searchField\").value, true);\n\t\txhttp.send();\t\n\t}", "function search(e)\n{\n const text = e.target.value.toLowerCase()\n let Lis = document.querySelectorAll('.list-item')\n Lis.forEach(function(li)\n {\n if(li.textContent.toLowerCase().indexOf(text) != -1)\n {\n li.style.display='flex'\n }\n else\n {\n li.style.display='none'\n }\n })\n\n}", "function performSearch(search){\n result = [];\n // Search for all users\n for (var i = 0; i < allUsers.results.length; i++) {\n if (allUsers.results[i].name.first.toLowerCase().includes(search) || allUsers.results[i].name.last.toLowerCase().includes(search))\n {\n result.push(allUsers.results[i]);\n }\n }\n if (result.length > 0) {\n // Empty users for search function and call function to display users\n gallery.innerHTML = '';\n displayUsers(result)\n \n } else {\n gallery.innerHTML = 'No results.';\n result = [];\n }\n }", "function searchEmojis() {\n // debugger;\n const getEmoji = emojis\n .filter(g => g.name.includes(searchEmoji.value))\n .map(emoji => `<div class=\"emoji\">${emoji.char}</div>`)\n .join(\"\");\n\n emojimodalbody.innerHTML = getEmoji\n}", "function findAll(){\n\tvar text = document.getElementById('textToFind').value;\n\tif(text == \"\"){\n\t\talert(\"Please enter something to search for!\");\n\t\treturn;\n\t}\n\treturn XPODoc.document.findAllMatches(text, document.findForm.findMatchCase.checked);\n}", "function showOrpNames() {\n\t// console.log(names);\n\tvar textEntered = getValue(\"orpName\");\n\tvar setContent = \"<div class='results'>\";\n\tvar len = 0;\n\tfor (var i = 0; i < names.length; i++) {\n\t\t// console.log(names[i]);\n\t\tif (names[i].toLowerCase().startsWith(textEntered.toLowerCase())) {\n\t\t\tsetContent += \"<a class='col5' onclick='setOrp(this)' value='\"\n\t\t\t\t\t+ names[i] + \"'><p>\" + names[i].split('-')[0] + \", \"\n\t\t\t\t\t+ names[i].split('-')[2] + \"</p></a>\";\n\t\t\tlen++;\n\t\t\t// console.log(names[i].split('-')[0]);\n\t\t}\n\t\tif (len > 5) {\n\t\t\tbreak;\n\t\t}\n\t}\n\tsetContent += \"</div>\";\n\t// console.log(setContent);\n\tdocument.getElementById(\"suggest\").innerHTML = setContent;\n}", "showMatchedLetter(letter) {\n const phraseLis = document.getElementById('phrase').children[0].children;\n\n for(let i = 0; i < phraseLis.length; i++) {\n if(phraseLis[i].textContent.includes(letter)) {\n phraseLis[i].className = 'show';\n }\n }\n }", "search(searchTerm) {\n let results = undefined;\n if (this.props.data) {\n\n if (this.props.caseInsensitive) {\n results = this.props.data.filter(object => this.getObjectText(object).toLowerCase().includes(searchTerm.toLowerCase()));\n } else {\n results = this.props.data.filter(object => this.getObjectText(object).includes(searchTerm));\n }\n }\n return results;\n }", "async function lookForPeople(phonebook, header, searchFields, searchFilter) {\n let noMatch = true; // ali je sploh katera oseba v imeniku najdena?\n phonebook.forEach(person => {\n // Preleti osebe v imeniku, in glede na izbrana iskalna polja in filtre isci in izpisuj\n let personPrint = \"\"; // String katerega sestavljamo za osebo, ce je bilo kaj najdeno\n let personMatch = false; // Ali se iskani niz pojavi pri osebi?\n for (var col in header) {\n let i = header[col]; // index stolpca \n if (searchFields.includes(col)) {\n // Uporabnik zeli iskati po tem polju\n\n // Spremeni v string in indeksiraj stringe\n person[i] = person[i].toString()\n let pos = 0;\n let oldPos = 0;\n let indices = [];\n // Isci po celem stringu kje se nahajajo pozicije\n while ((pos = person[i].indexOf(searchFilter, oldPos)) > -1) {\n indices.push(pos);\n oldPos = pos + searchFilter.length;\n }\n oldPos = 0;\n // Barvaj stringe, kjer so bile najdene pozicije\n for (let j=0; j<indices.length; j++) {\n personMatch = true;\n noMatch = false;\n // Pridobi substr od nepobarvanega dela\n personPrint += person[i].substr(oldPos, indices[j] - oldPos);\n // Pridobi del, ki ga je treba pobarvat\n personPrint += chalk.yellow(\n chalk.underline(\n chalk.bold(\n chalk.bgMagenta(\n person[i].substr(indices[j], searchFilter.length)\n ))));\n // Popravi staro pozicijo na zaden char zapisan v newPerson\n oldPos = indices[j] + searchFilter.length;\n }\n // V kolikor je za zadnjo najdeno pozicijo se kaj, dodaj v string (nepobarvano)\n if (oldPos < person[i].length) {\n personPrint += person[i].substr(oldPos, person[i].length - oldPos);\n }\n personPrint += \" \"\n } else {\n // Vseeno dodaj stolpec v string, v primeru da se isce po ostalih stolpcih\n personPrint += person[i] + \" \";\n }\n }\n if (personMatch) {\n // Izpisi trenuten personPrint kot zadetek (pobarvani deli vkljuceni)\n console.log(personPrint);\n }\n });\n // Obvesti ali je bil kdo najden\n let result = {\"noMatch\": noMatch};\n return result;\n}", "function find() {\n const searchInput = document\n .querySelector('#search-bar')\n .value.toUpperCase();\n const fullList = document.querySelectorAll('.pokedex-list__item');\n\n fullList.forEach(function (entry) {\n if (entry.innerText.toUpperCase().indexOf(searchInput) > -1) {\n entry.style.display = '';\n } else {\n entry.style.display = 'none';\n }\n });\n }", "handleSearch(term) {\n let contactsFiltered = this.state.contacts.filter( (contact) => Object.values(contact).some( (blob) => blob.includes(term)));\n this.setState({\n contactsFiltered: contactsFiltered\n })\n }", "function finder() {\n filter = keyword.value.toUpperCase();\n var li = box_search.getElementsByTagName(\"li\");\n // Recorriendo elementos a filtrar mediante los li\n for (i = 0; i < li.length; i++) {\n var a = li[i].getElementsByTagName(\"a\")[0];\n textValue = a.textContent || a.innerText;\n\n // QUIERO QUE ME APAREZCAN LAS OPCIONES SI TEXTVALUE.STARTSWITH = FILTER \n\n if (textValue.toUpperCase().indexOf(filter) > -1) {\n li[i].style.display = \"flex\";\n box_search.style.display = \"flex\";\n if (keyword.value === \"\") {\n box_search.style.display = \"none\";\n }\n }\n else {\n li[i].style.display = \"none\";\n }\n\n }\n\n}" ]
[ "0.75710016", "0.66473806", "0.65937567", "0.63445574", "0.626788", "0.62500834", "0.6249178", "0.6212356", "0.6195517", "0.6131622", "0.61005646", "0.59662116", "0.5903321", "0.5887522", "0.58268905", "0.5822486", "0.58189625", "0.58171904", "0.5798874", "0.5792916", "0.5787789", "0.5782567", "0.5766049", "0.5748686", "0.57446504", "0.5736525", "0.5730233", "0.5729739", "0.5727628", "0.5722122", "0.57215357", "0.5717554", "0.5716963", "0.57102555", "0.57070047", "0.57037604", "0.56995416", "0.5697225", "0.56966174", "0.5691558", "0.56879354", "0.56876105", "0.567779", "0.56770325", "0.56426126", "0.5640553", "0.5639951", "0.5639583", "0.5632415", "0.563092", "0.5626379", "0.56141424", "0.561301", "0.5608957", "0.5605439", "0.5602791", "0.5599825", "0.559919", "0.5594476", "0.55893886", "0.5585252", "0.55849063", "0.5580879", "0.55800813", "0.5577473", "0.5574981", "0.5573162", "0.55727595", "0.55706346", "0.55666", "0.5566358", "0.55658656", "0.55630994", "0.55617267", "0.55608505", "0.55571395", "0.555595", "0.55516", "0.55494356", "0.55442184", "0.55392295", "0.5537163", "0.55354935", "0.5532221", "0.55311686", "0.5528388", "0.55270606", "0.55246884", "0.5522238", "0.5520249", "0.5507337", "0.5505548", "0.55032766", "0.5495581", "0.54938465", "0.54914993", "0.54899234", "0.54840803", "0.54806775", "0.5477155" ]
0.5978027
11
searches the existing list of contacts in a static setting (no actual querying of data is done)
function query() { //reset text area $('#searchResults').text(""); contacts = getContacts(); //get existing list of contacts var searchCat = $('#selectSearch').val(); //search category (ie. Name) var query = $('#selectQuery').val().toLowerCase(); //user query var temp = 0; //counter to indicate if matches found if (query && query != '' && query != undefined) { for (var i = 0; i < contacts.length; i++) { var contact = contacts[i][searchCat]; //go through each contact if (contact.toLowerCase().indexOf(query) >= 0) { $('<ul>', { text: formatItem(contacts[i]) }).appendTo($('#searchResults')); temp++; } //end of loop } if (temp == 0) { $('#searchResults').text("No matches found"); } } else { $('#searchResults').text('ERROR: query not valid.'); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "contactList() {\n\t if (Session.get(\"searchName\") != \"\") {\n\t\tvar searchString = Session.get(\"searchName\");\n\t\treturn Template.contacts.__helpers[\" findContact\"](searchString);\n\t }\n\t else\n\t\treturn Contacts.findOne(\"Contacts\")[\"contacts\"];\n\t}", "function searchContacts() {\n contactsList = web.get_lists().getByTitle(\"WingtipAppContacts\");\n\n var textToSearch = $(\"#textToSearch\").val();\n var camlQuery = new SP.CamlQuery();\n var q = '<View><Query><Where><Contains><FieldRef Name=\"WingtipAppContactDescription\" /><Value Type=\"Text\">' + textToSearch + '</Value></Contains></Where></Query></View>';\n camlQuery.set_viewXml(q);\n listItems = contactsList.getItems(camlQuery);\n clientContext.load(listItems);\n\n clientContext.executeQueryAsync(onSearchQuerySucceeded, onSearchQueryFailed);\n}", "function findContact(searchTerm){\n searchResults = [];\n\n var list = contacts.find().fetch();\n console.log(list);\n for(var i=0; i < list.length; i++)\n {\n obj = list[i];\n if(obj.firstname == searchTerm || obj.lastname === searchTerm || obj.gender === searchTerm || obj.email === searchTerm || obj.number === searchTerm || obj.latitude === searchTerm || obj.longitude === searchTerm)\n {\n searchResults.push(obj);\n }\n }\n Session.set(\"searchRes\",searchResults);\n}", "function find() {\n console.log(getContacts());\n var alias = $('#contactAlias').val();\n //if valid alias\n if (alias && alias != '' && alias != undefined) {\n $.getJSON(uri + '/' + alias)\n .done(function (data) {\n $('#contact').text(formatItem(data));\n })\n .fail(function (jqXHR, textStatus, err) {\n $('#contact').text('Error: ' + err);\n });\n }\n //if INVALID value for alias, output error message\n else {\n $('#contact').text('Error: Cannot search for invalid or no alias.')\n }\n \n}", "static async findAllContacts() {\n const ContactList = await Contact.find({});\n return ContactList;\n }", "function getContacts() {\n return contacts;\n}", "function getAllSearchedContacts() {\n var searchInput = document.getElementById(\"searchbar\").value;\n ContactsController.Search(searchInput, onSearchContacts);\n}", "function search() {\n\t\t// clear the current contacts list\n\t\twhile (parent.lastChild)\n\t\t\tparent.removeChild(parent.lastChild);\n\t\txhttp.open(\"POST\", \"http://students.engr.scu.edu/~adiaztos/resources/contacts.php?query=\" + document.getElementById(\"searchField\").value, true);\n\t\txhttp.send();\t\n\t}", "function getPhoneContacts(){\r\n\tvar options = new ContactFindOptions();\r\n\toptions.filter=\"\"; // empty search string returns all contacts\r\n\toptions.multiple=true; // return multiple results\r\n\tfilter = [\"displayName\", \"name\", \"phoneNumbers\",\"photos\",\"emails\"];\r\n\t// find contacts\r\n\tnavigator.contacts.find(filter, getPhoneContactsSuccess, null, options);\r\n}", "function getContacts() {\n return contacts;\n }", "function filterContacts(){\n\n var searchBox = document.getElementById(\"searchBox\");\n\n if(searchBox.value.length>1){\n\n var subSetContacts = USER_ARRAY.filter(function(contact){\n return contact.getFullName().toLowerCase().indexOf(searchBox.value.toLowerCase()) > -1;\n });\n\n console.log(\"result of filter\",subSetContacts);\n generateList(subSetContacts);\n\n }else if(searchBox.value.length==0){\n generateList(USER_ARRAY);\n }\n\n}", "function searchContact() {\n let searchVal = document.getElementById('txtFilter').value.toLowerCase();\n subADDRESSES = [];\n\n for (i=0; i<ADDRESSES.length; i++) {\n\n let name = ADDRESSES[i].name.toLowerCase();\n let surname = ADDRESSES[i].surname.toLowerCase();\n let phone = ADDRESSES[i].phone.toLowerCase();\n let address = ADDRESSES[i].address.toLowerCase();\n\n if (name.includes(searchVal) || surname.includes(searchVal) ||\n phone.includes(searchVal) || address.includes(searchVal)) {\n subADDRESSES.push(ADDRESSES[i]);\n }\n\n };\n displayTbl(subADDRESSES);\n}", "function searcContactName() {\r\n $('.search-contact').keyup( function() {\r\n // Inserisco il valore da cercare\r\n var searchQuery = $('input.search-contact').val().toLowerCase();\r\n\r\n // Lista di tutti i contati\r\n var allContacts = $('li.contact-js');\r\n\r\n // Il ciclo di verifica per tutti i contatti\r\n allContacts.each( function() {\r\n\r\n // Seleziono il nome del contatto ('.contact-name')\r\n var contactName = $(this).find('.contact-name').text().toLowerCase();\r\n\r\n if( contactName.includes(searchQuery) ) {\r\n // Viusalizzo il contatto se contiene il valore inserito nella search\r\n $(this).show();\r\n } else {\r\n // Nascondo altri contatti\r\n $(this).hide();\r\n }\r\n }); // End each\r\n }); // End keyup function\r\n } // End searcContactName() function", "function listAllContacts(keyword){\n list = getAllContacts(keyword);\n if (list.length === 0) {\n $('#contact-list-wrap').text(\"No contact found\");\n } else{\n buildTable(list);\n }\n }", "function searchName(name){\n var nameABC = change_alias(name).toLowerCase();\n for(let contact of listContact)\n {\n if(change_alias(contact.Name).toLowerCase().indexOf(nameABC)!== -1)\n console.log(contact);\n }\n}", "findContact(contactName) {\n\t var contactObjectList = Contacts.findOne(\"Contacts\")[\"contacts\"];\n\t var findResult = [];\n\t for (id in contactObjectList) {\n\t\tvar first_name = contactObjectList[id][\"name\"][\"first\"];\n\t\tvar middle_name = contactObjectList[id][\"name\"][\"middle\"];\n\t\tvar last_name = contactObjectList[id][\"name\"][\"last\"];\n\t\tvar key = \"\";\n\t\t(first_name != \"\")? key += first_name + \" \" : key = key;\n\t\t(middle_name != \"\")? key += middle_name + \" \" : key = key;\n\t\t(last_name != \"\")? key += last_name : key = key;\n\t\tif (key == contactName)\n\t\t findResult.push(contactObjectList[id]);\n\t }\n\t return findResult;\n\t}", "function searchContact(ev) {\n setContacts(contacts.filter((_) => _.name.toLowerCase().match(ev.toLowerCase())));\n }", "function listcontacts(all)\n{\n if (typeof (webphone_api.plhandler) !== 'undefined' && webphone_api.plhandler !== null)\n return webphone_api.plhandler.ListContacts(all);\n}", "function loadCities(contacts) {\n if (contacts.length <= 0) return;\n var filterOptions = document.querySelector(\"#filterOptions\");\n var trackingList = [];\n\n var _iterator = _createForOfIteratorHelper(contacts),\n _step;\n\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var contact = _step.value;\n var city = contact.address.city;\n\n if (!trackingList.includes(city)) {\n trackingList.push(city);\n filterOptions.innerHTML += \"<option value ='\".concat(city, \"'>\").concat(city, \"</option>\");\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n}", "function searchByCriteria() {\n \n $.mobile.changePage(\"#cont_list_page\", { transition : \"pop\" });\n if (typeof Contact !== \"undefined\") {\n var searchCriteria = getElement(\"searchby_chooser_input\").options[getElement(\"searchby_chooser_input\").selectedIndex].value;\n var searchVal = getElement(\"search_val_input\").value;\n getElement(\"search_val_input\").value = \"\";\n \n var addF = [];\n addF.push(searchCriteria);\n displContactList.updateList(searchVal, searchCriteria, addF);\n \n var div = getElement(\"full_list_button_container\");\n if (div) {\n div.innerHTML = '<a href=\"#\" id=\"full_list_button\" data-role=\"button\" data-mini=\"true\" class=\"ui-btn-left\" data-theme=\"c\" >Show full list</a>';\n $(\"#full_list_button\").bind(\"click\", function() { displContactList.updateList(); div.innerHTML = \"\"; });\n $(\"#full_list_button\").button();\n }\n }\n}", "function showMyContacts()\n{\n\tdocument.getElementById(\"searchField\").value = \"\";\n\tresetStatus();\n\tcurPage = 1;\n\tshowContacts();\n}", "function filterContacts() {\n\t\tupdateEmployeesHtml(makeEmployeesHTML(employeesData));\n\t}", "function findAutocomplete(contactName) {\n var n = contactName.indexOf(\",\");\n var index = 0;\n index = contactName.substr(n+1,contactName.length-1);\n index = parseInt(index);\n currentContactIndex = index;\n viewCurrentContact();\n }", "_search(){\n const searchTerm = document.getElementById(INVOICE_CONTACTS_SEARCH_INPUT_ID).value;\n const contactsListElem = document.getElementById(INVOICE_CONTACTS_LIST_ID);\n const contactsHeader = document.getElementById(INVOICE_CONTACTS_LIST_HEADER_ID);\n\n if(searchTerm === \"\"){\n\n // Clear everything out\n while(contactsListElem.firstElementChild) contactsListElem.removeChild(contactsListElem.firstElementChild);\n\n // And re-add them so they're ordered correctly\n for(const contact of this._loadedContacts){\n contact.parentElement.htmlObj.removeAttribute(ATTRIBUTE_FOUND_RESULT);\n contactsListElem.appendChild(contact.parentElement.htmlObj);\n }\n\n // Remove that we're in search mode, and update the header\n contactsListElem.removeAttribute(ATTRIBUTE_SEARCH);\n contactsHeader.innerHTML = \"Contacts\";\n return;\n }\n\n const runNum = Math.random();\n this._search.runNum = runNum;\n contactsListElem.setAttribute(ATTRIBUTE_SEARCH, \"\");\n\n // Change the title\n contactsHeader.innerHTML = \"Search Results\";\n\n const results = [];\n\n for(const contact of this._loadedContacts){\n // If it's been called again, stop\n if(this._search.runNum !== runNum) return;\n\n /**\n * @type {Array<Object<likelihood, contact>>}\n */\n const liklihood = [];\n\n const searchWords = searchTerm.split(' ');\n for(const word of searchWords) {\n const values = [\n contact.firstName,\n contact.lastName,\n contact.streetAddress,\n contact.city,\n contact.state,\n contact.zip,\n contact.email\n ];\n\n for(const value of values){\n const likeliness = getLikeliness(value.toString().toLowerCase(), word.toLowerCase());\n if(likeliness >= .5){\n liklihood.push(likeliness);\n break;\n }\n }\n }\n\n if(liklihood.length > 0) {\n const average = liklihood.reduce((a, b) => a + b) / liklihood.length;\n results.push({likelihood: average, contact: contact});\n }\n else{\n contact.parentElement.htmlObj.removeAttribute(ATTRIBUTE_FOUND_RESULT);\n }\n }\n\n results.sort((l, r) => l.likelihood < r.likelihood);\n\n // If it's been called again, stop\n if(this._search.runNum !== runNum) return;\n\n for(const result of results){\n result.contact.parentElement.htmlObj.setAttribute(ATTRIBUTE_FOUND_RESULT, \"\");\n }\n }", "function _get_site_contacts_list(db){\n try{\n var rows = db.execute('SELECT * FROM my_'+_type+'_site_contact WHERE status_code=1 and '+_type+'_id=?',_selected_job_id);\n var b = 0;\n if(rows.getRowCount() > 0){\n while(rows.isValidRow()){\n var row = Ti.UI.createTableViewRow({\n filter_class:'site_contact',\n className:'site_contact_list_data_row_'+b,\n hasChild:true,\n source:_source,\n job_id:_selected_job_id,\n contact_id:rows.fieldByName('id'),\n title:rows.fieldByName('first_name')+' '+rows.fieldByName('last_name'),\n mobile:rows.fieldByName('phone_mobile'),\n email:rows.fieldByName('email')\n }); \n if(b === 0){\n row.header = 'Site Contacts';\n }\n self.data.push(row);\n rows.next();\n b++;\n }\n }\n rows.close();\n }catch(err){\n self.process_simple_error_message(err,window_source+' - _get_site_contacts_list');\n return;\n } \n }", "function refreshContactList (contacts) {\n pageContents.contacts = contacts;\n\n if (contacts.length === 0) {\n $(\".rolodex\").addClass(\"block\");\n }\n else {\n $(\".rolodex\").removeClass(\"block\");\n }\n $(\".rolodex\").html(listTemplate(pageContents));\n }", "async findContacts() {\n // The model is used to retrieve data!\n const contacts = await new Contact().getContacts();\n // The service is used for shaping, formatting and more!\n return contacts.map(contact => ({\n firstName: contact.firstName,\n lastName: contact.lastName\n }))\n }", "function search(entry, onFound = (res)=>{console.log(\"Found [\"+entry+\",\"+res+\"] in phonebook\");}, onNotFound = ()=>{console.error(\"Could not find [\"+entry+\"] in phonebook\");},field=\"name\"){\r\n\r\n\treadFile((res)=>{\r\n\t\tvar found = false;\r\n\t\tvar contactList = JSON.parse(res);\r\n\t\tcontactList.forEach((item,index)=>{\r\n\t\t\t//console.log(\"Comparing \"+item.name.toUpperCase()+\" to \"+entry.toUpperCase());\r\n\t\t\tif(field===\"name\" && item.name.toUpperCase()===entry.toUpperCase()){\r\n\t\t\t\tonFound(item);\r\n\t\t\t\tfound = true;\r\n\t\t\t}\r\n\t\t\telse if(field===\"number\" && item.number===entry){\r\n\t\t\t\tonFound(item);\r\n\t\t\t\tfound = true;\r\n\t\t\t}\r\n\t\t});\r\n\t\tif(found===false) onNotFound();\r\n\t});\r\n}", "function getContacts() {\n\t\t$.get('/api/contacts', function(data) {\n\t\t\tvar rowsToAdd = [];\n\t\t\tfor (var i = 0; i < data.dbContacts.length; i++) {\n\t\t\t\trowsToAdd.push(createContactsRow(data.dbContacts[i]));\n\t\t\t}\n\t\t\trenderContactsList(rowsToAdd);\n\t\t\tnameInput.val('');\n\t\t});\n\t}", "function updateContactList() {\r\n\tsupervisorsStore.load( {params: { method: \"loadSupervisors\"} } );\r\n\texpertsStore.load( {params: { method: \"loadExperts\"} } );\r\n\tpeersStore.load( {params: { method: \"loadPeers\"} } );\r\n agentsStore.load( {params: { method: \"loadFavorites\"} } );\r\n}", "function getContactsAll(type,contact_status) {\n document.location.href = \"/contacts?mode_type=\"+type+\"&contact_status=\"+contact_status;\n}", "function search(query) {\r\n $.getJSON(\"http://localhost:8080/api/contact/search?query=\"+query, (data) => {\r\n if (data !== undefined && data.length !== 0) {\r\n updateContacts(data);\r\n }\r\n }).fail((err) => console.log(\"Couldn't contacts \", err));\r\n}", "function searchContact() {\n let searchResultList = search()\n console.log(`The person are ${searchResultList.map(contact => contact.firstName)}`)\n}", "function makeContactList() {\n /*\n * You need something here to hold contacts. See length api for a hint:\n */\n var contacts = [];\n \n return {\n // we implemented the length api for you //\n length: function() {\n return contacts.length;\n },\n addContact: function(contact) {\n contacts.push(contact);\n return contacts;\n },\n findContact: function(fullName) {\n for (var i = 0; i < contacts.length; i++) {\n if (fullName === contacts[i].nameFirst + \" \" + contacts[i].nameLast) { return contacts[i];\n } else {\n return undefined;\n } \n }\n },\n removeContact: function(contact) {\n for (var i = 0; i < contacts.length; i++) {\n if (contacts[i] === contact) {\n contacts.splice(i, 1);\n }\n }\n \n }, printAllContactNames: function() {\n var returnedNames = \" \";\n for (var i = 0; i < contacts.length; i++) {\n returnedNames += \"\\n\" + contacts[i].nameFirst + \" \" + contacts[i].nameLast; \n } return returnedNames.trim();\n }\n \n };\n \n \n }", "function searchContacts()\r\n{\r\n\t// Collects data from the search bar in the landing page.\r\n\tvar srch = document.getElementById(\"contactsInput\").value;\r\n\tvar contactsList = \"\";\r\n\r\n\t// Clears the table to allow for the construction of a new table\r\n\t// based on the search results.\r\n $(\"#contactsTable tbody tr\").remove(); \r\n\t\r\n\t// Package a JSON payload to deliver to the Search Endpoint with\r\n\t// the UserID in order to display the contacts based on the search input.\r\n\tvar jsonPayload = '{\"UserID\" : \"' + userId + '\", \"Input\" : \"' + srch + '\"}';\r\n\tvar url = urlBase + '/Search.' + extension;\r\n\t\r\n\tvar xhr = new XMLHttpRequest();\r\n\txhr.open(\"POST\", url, false);\r\n\txhr.setRequestHeader(\"Content-type\", \"application/json; charset=UTF-8\");\r\n\r\n\t// Basic try and catch to ensure that any server code errors are \r\n\t// handled properly. \r\n\ttry\r\n\t{ \r\n\t\txhr.send(jsonPayload);\r\n contactList = JSON.parse(xhr.responseText);\r\n }\r\n \r\n\tcatch(err)\r\n\t{\r\n\t\tdocument.getElementById(\"contactsTable\").innerHTML = err.message;\r\n\t}\r\n \r\n\t// For each contact in the JSON array, the contact's\r\n\t// information will be added to the table.\r\n \tfor (var i in contactList)\r\n {\r\n \taddRow(contactList[i]);\r\n }\r\n}", "function showInfo(contactID, searchCriteria) {\n \n var contInfoContainer = getElement(\"contact_info\");\n var contactFields = [\"*\"];\n var contactFindOptions = new ContactFindOptions();\n contactFindOptions.filter = searchCriteria;\n contactFindOptions.multiple = true;\n navigator.contacts.find(contactFields, contactSuccess, contactError, contactFindOptions);\n \n function contactSuccess(contacts) {\n \n contInfoContainer.innerHTML = \"\";\n for (var i = 0; i < contacts.length; i++) {\n \n if (contacts[i].id == contactID) {\n \n activeContact = contacts[i];\n \n var cNameSection = \"<div class='contactInfo'>\" +\n \"<div>\" + buildDisplayName(contacts[i]) + \"</div>\" +\n \"<div>\" + (!isEmptyOrBlank(contacts[i].nickname) ? ('\"' + contacts[i].nickname + '\"') : \"\") + \"</div>\" +\n \"</div>\";\n \n var cPhotoSection = \"<div class='contactImage'>\" +\n \"<img src='\" + \n ((contacts[i].photos && (contacts[i].photos.length > 0) && !isEmptyOrBlank(contacts[i].photos[0].value) && (contacts[i].photos[0].value.indexOf(\"//:0\") === -1)) \n ? contacts[i].photos[0].value \n : \"resources/nophoto.jpg\") + \n \"' width='50' height='50' />\" +\n \"</div>\";\n \n var cPhoneNumbersSection = \"\";\n if (contacts[i].phoneNumbers && (contacts[i].phoneNumbers.length > 0)) {\n \n var cPhoneNumbersSectionHeader = \"<div class='iSectionTitle'>Phone Numbers</div>\";\n var cPhoneNumbersSectionContent = \"\";\n for (var j = 0; j < contacts[i].phoneNumbers.length; j++) {\n if (contacts[i].phoneNumbers[j] && !isEmptyOrBlank(contacts[i].phoneNumbers[j].value)) {\n cPhoneNumbersSectionContent += \"<div class='iSectionItem'>\" +\n \"<div class='iItemType'>\" + contacts[i].phoneNumbers[j].type + \"</div>\" +\n \"<div class='iItemValue'>\" + contacts[i].phoneNumbers[j].value + \"</div>\" +\n \"</div>\";\n }\n }\n if (!isEmptyOrBlank(cPhoneNumbersSectionContent)) {\n cPhoneNumbersSection = cPhoneNumbersSectionHeader + cPhoneNumbersSectionContent;\n }\n }\n \n var cEmailsSection = \"\";\n if (contacts[i].emails && (contacts[i].emails.length > 0)) {\n \n var cEmailsSectionHeader = \"<div class='iSectionTitle'>Emails</div>\";\n var cEmailsSectionContent = \"\";\n for (var j = 0; j < contacts[i].emails.length; j++) {\n if (contacts[i].emails[j] && !isEmptyOrBlank(contacts[i].emails[j].value)) {\n cEmailsSectionContent += \"<div class='iSectionItem'>\" +\n \"<div class='iItemType'>\" + contacts[i].emails[j].type + \"</div>\" +\n \"<div class='iItemValue'>\" + contacts[i].emails[j].value + \"</div>\" +\n \"</div>\";\n }\n }\n if (!isEmptyOrBlank(cEmailsSectionContent)) {\n cEmailsSection = cEmailsSectionHeader + cEmailsSectionContent;\n }\n }\n \n var cIMsSection = \"\";\n if (contacts[i].ims && (contacts[i].ims.length > 0)) {\n \n var cIMsSectionHeader = \"<div class='iSectionTitle'>IMs</div>\";\n var cIMsSectionContent = \"\";\n \n for (var j = 0; j < contacts[i].ims.length; j++) {\n if (contacts[i].ims[j] && !isEmptyOrBlank(contacts[i].ims[j].value)) {\n cIMsSectionContent += \"<div class='iSectionItem'>\" +\n \"<div class='iItemType'>\" + contacts[i].ims[j].type + \"</div>\" +\n \"<div class='iItemValue'>\" + contacts[i].ims[j].value + \"</div>\" +\n \"</div>\";\n }\n }\n \n if (!isEmptyOrBlank(cIMsSectionContent)) {\n cIMsSection = cIMsSectionHeader + cIMsSectionContent;\n }\n }\n \n var cUrlsSection = \"\";\n if (contacts[i].urls && (contacts[i].urls.length > 0)) {\n \n var cUrlsSectionHeader = \"<div class='iSectionTitle'>Urls</div>\";\n var cUrlsSectionContent = \"\";\n \n for (var j = 0; j < contacts[i].urls.length; j++) {\n if (contacts[i].urls[j] && !isEmptyOrBlank(contacts[i].urls[j].value)) {\n cUrlsSectionContent += \"<div class='iSectionItem'>\" +\n \"<div class='iItemType'>\" + contacts[i].urls[j].type + \"</div>\" +\n \"<div class='iItemValue'>\" + contacts[i].urls[j].value + \"</div>\" +\n \"</div>\";\n }\n }\n if (!isEmptyOrBlank(cUrlsSectionContent)) {\n cUrlsSection = cUrlsSectionHeader + cUrlsSectionContent;\n }\n }\n \n var cAddressesSection = \"\";\n if (contacts[i].addresses && (contacts[i].addresses.length > 0)) {\n \n var cAddressesSectionHeader = \"<div class='iSectionTitle'>Addresses</div>\";\n var cAddressesSectionContent = \"\";\n \n for (var j = 0; j < contacts[i].addresses.length; j++) {\n if (contacts[i].addresses[j] && (!isEmptyOrBlank(contacts[i].addresses[j].streetAddress) || !isEmptyOrBlank(contacts[i].addresses[j].locality) ||\n !isEmptyOrBlank(contacts[i].addresses[j].region) || !isEmptyOrBlank(contacts[i].addresses[j].country))) {\n \n var atypeSubsection = ((!isEmptyOrBlank(contacts[i].addresses[j].type) && (contacts[i].addresses[j].type != \"undefined\")) ? (\"<div class='iItemType'>\" + contacts[i].addresses[j].type + \"</div>\") : \"\");\n var strSubsection = ((!isEmptyOrBlank(contacts[i].addresses[j].streetAddress) && (contacts[i].addresses[j].streetAddress != \"undefined\")) ? (\"<div>\" + contacts[i].addresses[j].streetAddress + \"</div>\") : \"\");\n var locSubsection = ((!isEmptyOrBlank(contacts[i].addresses[j].locality) && (contacts[i].addresses[j].locality != \"undefined\")) ? (\"<div>\" + contacts[i].addresses[j].locality + \"</div>\") : \"\");\n var regSubsection = ((!isEmptyOrBlank(contacts[i].addresses[j].region) && (contacts[i].addresses[j].region != \"undefined\")) ? contacts[i].addresses[j].region : \"\");\n var postSubsection = ((!isEmptyOrBlank(contacts[i].addresses[j].postalCode) && (contacts[i].addresses[j].postalCode != \"undefined\")) ? contacts[i].addresses[j].postalCode : \"\");\n if (regSubsection != \"\") {\n if (postSubsection != \"\") {\n regSubsection += \", \";\n }\n }\n regSubsection += postSubsection;\n var countrySubsection = ((!isEmptyOrBlank(contacts[i].addresses[j].country) && (contacts[i].addresses[j].country != \"undefined\")) ? (\"<div>\" + contacts[i].addresses[j].country + \"</div>\") : \"\");\n \n cAddressesSectionContent += \"<div class='iSectionItem'>\" +\n atypeSubsection +\n \"<div class='iItemValue'>\" + \n strSubsection +\n locSubsection +\n (\"<div>\" + regSubsection + \"</div>\") +\n countrySubsection +\n \"</div>\" +\n \"</div>\";\n }\n }\n if (!isEmptyOrBlank(cAddressesSectionContent)) {\n cAddressesSection = cAddressesSectionHeader + cAddressesSectionContent;\n }\n }\n \n var sectionHeading = \"\";\n var sectionContent = \"\";\n if (contacts[i].organizations && (contacts[i].organizations.length > 0)) {\n for (var j = 0; j < contacts[i].organizations.length; j++) {\n var typeSubsection = ((!isEmptyOrBlank(contacts[i].organizations[j].type) && (contacts[i].organizations[j].type != \"undefined\")) ? (\"<div class='iItemType'>\" + contacts[i].organizations[j].type + \"</div>\") : \"\");\n var deptSubsection = ((!isEmptyOrBlank(contacts[i].organizations[j].department) && (contacts[i].organizations[j].department != \"undefined\")) ? (contacts[i].organizations[j].department) : \"\");\n var orgSubsection = ((!isEmptyOrBlank(contacts[i].organizations[j].name) && (contacts[i].organizations[j].name != \"undefined\")) ? contacts[i].organizations[j].name : \"\");\n var orgLine = orgSubsection;\n if (deptSubsection != \"\") {\n if (orgSubsection != \"\") {\n orgLine += \", \";\n } \n orgLine += deptSubsection;\n }\n var titleSubsection = ((!isEmptyOrBlank(contacts[i].organizations[j].title)) ? (\"<div>\" + contacts[i].organizations[j].title + \"</div>\") : \"\");\n \n if ((orgLine != \"\") || (titleSubsection != \"\")) {\n sectionContent += \"<div class='iSectionItem'>\" +\n typeSubsection +\n \"<div class='iItemValue'>\" + \n (\"<div>\" + orgLine + \"</div>\") +\n titleSubsection +\n \"</div>\" +\n \"</div>\";\n }\n }\n if (!isEmptyOrBlank(sectionContent)) {\n sectionHeading = \"<div class='iSectionTitle'>Organizations</div>\";\n }\n }\n var cOrganizationsSection = sectionHeading + sectionContent;\n \n var cNoteSection = \"\";\n if (!isEmptyOrBlank(contacts[i].note)) {\n cNoteSection += \"<div class='iSectionTitle'>Note</div>\" +\n \"<div class='iSectionItem'>\" +\n \"<div class='iItemValue'>\" + contacts[i].note + \"</div>\" +\n \"</div>\";\n }\n \n contInfoContainer.innerHTML += cPhotoSection + cNameSection + cPhoneNumbersSection + cEmailsSection + \n cIMsSection + cUrlsSection + cAddressesSection + cOrganizationsSection + \n cNoteSection;\n $.mobile.changePage(\"#cont_info_page\", { transition: \"pop\" });\n break;\n }\n }\n }\n \n function contactError(contactError) {\n \n contInfoContainer.innerHTML = \"Contacts are unavailable\";\n $.mobile.changePage(\"#cont_info_page\", { transition: \"pop\" });\n }\n}", "function searchEntries() {\n var search = document.getElementById(\"search\").value;\n // iterate through all entries\n for (var i = 0; i < contacts.length; i++) {\n // entry i is in div id=\"contact_{i}\"\n var entryDiv = document.getElementById(\"contact_\" + i); \n if (search.length > 0 && !contacts[i].contains(search)) {\n entryDiv.style.display = \"none\";\n }\n else {\n entryDiv.style.display = \"\"; \n } \n }\n}", "function querySearch (criteria) {\n return criteria ? self.allContacts.filter(createFilterFor(criteria)) : [];\n }", "function getAllContacts(){\n\tvar uri_param = \"GET <b>/api/contacts</b> HTTP/1.1\";\n\t$(\".request-preview-param-uri\").html(uri_param);\n\t$(\".request-preview-param-body\").html('');\n\t\n\tvar list = getStorageContacts(false,0);\n\tvar json = JSON.stringify({\"status\":200,\"contacts\":list});\n\t$(\"#response-preview .text\").jJsonViewer(json);\n\t\n\t\n\tsyncViewTable();\n\t\n\t$.notify(\"Request successful\", \"success\");\n\t$.notify(\"Preview updated\", \"success\");\n\t\n}", "function filterContacts(data, search){\n const result = data.filter(({ contact }) => {\n return !search || contact.name.includes(search)\n })\n //set result of comparing in filter\n setFilterContacts(result)\n }", "filteredContacts() {\n \n this.contacts.forEach((contatto) =>\n {\n const contattoNameLowerCase = contatto.name.toLowerCase();\n const userFilteredLowerCase = this.userFiltered.toLowerCase();\n\n if( contattoNameLowerCase.includes(userFilteredLowerCase) ) {\n contatto.visible = true;\n } else{\n contatto.visible = false;\n }\n console.log(contatto.visible)\n });\n \n }", "handlerSearch(search){\n const filterContacts = this.state.contacts.filter( contact =>\n contact.name.toLowerCase().includes(search.toLowerCase())\n || contact.email.toLowerCase().includes(search.toLowerCase())\n || contact.website.toLowerCase().includes(search.toLowerCase())\n || checkPhone(contact.phone, search)\n || contact.company.name.toLowerCase().includes(search.toLowerCase())\n || contact.address.country.toLowerCase().includes(search.toLowerCase())\n );\n this.setState({filterContacts});\n }", "function onDeviceReady() {\n\t\t var options = new ContactFindOptions();\n\t\t options.filter = \"\";\n\t\t options.multiple = true;\n\t\t fields = [\"*\"];\n\t\t navigator.contacts.find(fields, contactfindSuccess, contactfindError, options);\n\n\t\t \n\t\t\n\t }", "function updateContactsList() {\n const select = document.getElementById('contactDropDown')\n select.innerHTML = ''\n const contacts = client.contacts.getAll()\n var count = 0 \n for (let {} in contacts) {\n count = count + 1;\n }\n if (count > 0){\n for (let contactId in contacts) {\n for (let opt of select.options) {\n if (opt.value === contactId) {\n select.removeChild(opt)\n }\n }\n var opt = document.createElement('option')\n opt.value = opt.text = contactId\n select.appendChild(opt)\n if (select.options.length === 1) {\n renderContact()\n }\n }\n } else {\n renderContact()\n }\n}", "function querySearch (criteria) {\n cachedQuery = cachedQuery || criteria;\n return cachedQuery ? self.allContacts.filter(createFilterFor(cachedQuery)) : [];\n }", "function filterContacts(){\n matchedWords=[];\n filterActive=true;\n var value = $('#city-selector').val();\n var valueChecked = true;\n if( $('#show-active:checked').length == 0 ){\n valueChecked = false;\n };\n\n var searchWord = $('#name-search').val().trim();\n var pattern = new RegExp(searchWord, 'gi');\n for(var i=0; i<contactsData.length; i++){\n var testword = contactsData[i]['name'];\n if(testword.match(pattern)!= null){\n var filteredData = contactsData[i];\n if(value == 'none' && valueChecked == true){\n if(contactsData[i]['active'] == true){\n matchedWords.push(filteredData);\n }\n }else if( value == filteredData['city'] && (valueChecked == filteredData['active'] || filteredData['active']== undefined) ){\n matchedWords.push(filteredData);\n }else if(value == 'none' && (valueChecked == filteredData['active'] || filteredData['active']== undefined )) {\n matchedWords.push(filteredData);\n }\n }\n }\n //Perpiesiama nauja lentele su isfiltruotais duomenimis\n createTable(matchedWords);\n }", "function getCustomers(contacts) {\n\t\tcontactsId = contacts || '';\n\t\tif (contactsId) {\n\t\t\tcontactsId = '/?contacts_id=' + contactsId;\n\t\t}\n\t\t$.get('/api/contacts' + contactsId, function(data) {\n\t\t\tconsole.log('customers', data);\n\t\t\tcustomers = data;\n\t\t\tif (!customers || !customers.length) {\n\t\t\t\tdisplayEmpty(contacts);\n\t\t\t} else {\n\t\t\t\tinitializeRows();\n\t\t\t}\n\t\t});\n\t}", "function searchByCity(contact) {\n return contact.city + \" \" + contact.firstName + \" \" + contact.lastName;\n }", "async function updateContactList() {\n $('#contact-container').empty()\n const allToContact = await bookingsNeedContact.allDocs({ include_docs: true })\n var allPreviouslyPendings = await pendingBookings.allDocs({ include_docs: true })\n allPreviouslyPendings = allPreviouslyPendings.rows;\n const filteredToContact = allToContact.rows.filter((tc) => {\n return allPreviouslyPendings.findIndex((pb) => pb.id === tc.id ) !== -1\n });\n if (filteredToContact.length > 0) {\n $('#contact-container').show()\n $('#contact-container').append(`<li class=\"collection-header\"><b>Previously pending bookings that need contact</b></li>`)\n filteredToContact.forEach(toContact => {\n toContact = toContact.doc;\n var preferedContact = toContact.email;\n if (toContact.phone) {\n preferedContact = toContact.phone\n }\n const contactEntry = `\n<li class=\"collection-item\">\n<p>The previously pending booking done for '${toContact.firstName} ${toContact.lastName}' with ${toContact.groupSize} Members was <span class=\"${toContact.status}\">${toContact.status}</span>.<br>\nPlease Contact '${toContact.firstName} ${toContact.lastName}' under '${preferedContact}'.<p>\n<a class=\"waves-effect waves-light btn green delete-to-contact btn-flat white-text\" id=\"${toContact._id}\">\n <i class=\"material-icons left\" id=\"${toContact._id}\">done</i> Done\n</a>\n</li>\n `\n $('#contact-container').append(contactEntry)\n })\n } else {\n $('#contact-container').hide()\n }\n}", "onChangeHandler(e){\n var updatedList = this.state.initialContacts;\n updatedList = updatedList.filter((item) =>\n (item.name + ' ' + item.surname)\n .toLowerCase()\n .search(e.target.value.toLowerCase()) !== -1\n );\n\n this.setState({\n contacts: updatedList\n })\n }", "function querySearch (criteria) {\n cachedQuery = cachedQuery || criteria;\n return cachedQuery ? self.allContacts.filter(createFilterFor(cachedQuery)) : [];\n }", "function contactService( $q, $http, $rootScope, logger, $log, vncConstant ){\n\n this.filterContact = function (options, callback) {\n let defaultOptions = {\n sortBy: 'nameAsc',\n offset: 0,\n limit: 100,\n needExp: 1,\n query: 'in:contacts',\n types: 'contact',\n tz: {\n id: 'Asia/Bangkok'\n },\n locale: 'en_US'\n };\n\n let request = angular.extend({}, defaultOptions, options);\n return $http({\n url: $rootScope.API_URL + '/searchRequest',\n method: 'POST',\n data: request\n }).success(function (res) {\n if (typeof callback === 'function') {\n callback(res);\n }\n\n }).error(function (res) {\n if (typeof callback === 'function') {\n callback(null, res);\n }\n });\n };\n\n this.filterTagContact = function (options, callback) {\n let defaultOptions = {\n sortBy: 'nameAsc',\n offset: 0,\n limit: 100,\n needExp: 1,\n query: 'tag:\"your tag\"',\n types: 'contact',\n tz: {\n id: 'Asia/Bangkok'\n },\n cursor: {\n endSortVal: 'D', // The next alphabet used to search; A for search number\n id: 0,\n sortVal: 'C' // The alphabet used to search; 0 for search number\n },\n locale: 'en_US'\n };\n\n let request = angular.extend({}, defaultOptions, options);\n return $http({\n url: $rootScope.API_URL + '/searchRequest',\n method: 'POST',\n data: request\n }).success(function (res) {\n if (typeof callback === 'function') {\n callback(res.cn);\n }\n\n }).error(function (res) {\n if (typeof callback === 'function') {\n callback(null, res);\n }\n });\n };\n\n this.filterTrashContact = function (options, callback) {\n let defaultOptions = {\n sortBy: 'nameAsc',\n offset: 0,\n limit: 100,\n needExp: 1,\n query: 'in:trash',\n types: 'contact',\n tz: {\n id: 'Asia/Bangkok'\n },\n cursor: {\n endSortVal: 'D', // The next alphabet used to search; A for search number\n id: 0,\n sortVal: 'C' // The alphabet used to search; 0 for search number\n },\n locale: 'en_US'\n };\n\n let request = angular.extend({}, defaultOptions, options);\n return $http({\n url: $rootScope.API_URL + '/searchRequest',\n method: 'POST',\n data: request\n }).success(function (res) {\n if (typeof callback === 'function') {\n callback(res.cn);\n }\n\n }).error(function (res) {\n if (typeof callback === 'function') {\n callback(null, res);\n }\n });\n };\n\n this.filterEmailedContact = function (options, callback) {\n let defaultOptions = {\n sortBy: 'nameAsc',\n offset: 0,\n limit: 100,\n needExp: 1,\n query: 'in:\"Emailed Contacts\"',\n types: 'contact',\n tz: {\n id: 'Asia/Bangkok'\n },\n cursor: {\n endSortVal: 'D', // The next alphabet used to search; A for search number\n id: 0,\n sortVal: 'C' // The alphabet used to search; 0 for search number\n },\n locale: 'en_US'\n };\n\n let request = angular.extend({}, defaultOptions, options);\n return $http({\n url: $rootScope.API_URL + '/searchRequest',\n method: 'POST',\n data: request\n }).success(function (res) {\n if (typeof callback === 'function') {\n callback(res.cn);\n }\n\n }).error(function (res) {\n if (typeof callback === 'function') {\n callback(null, res);\n }\n });\n };\n\n this.getContacts = function (options, callback) {\n let defaultOptions = {\n sortBy: 'nameAsc',\n offset: 0,\n limit: 100,\n fetch: 1,\n needExp: 1,\n query: 'in:contacts',\n types: 'contact',\n tz: {\n id: 'Asia/Bangkok'\n },\n locale: 'en_US'\n };\n\n let request = angular.extend({}, defaultOptions, options);\n return $http({\n url: $rootScope.API_URL + '/searchRequest',\n method: 'POST',\n data: request\n }).success(function (res) {\n if (typeof callback === 'function') {\n callback(res);\n }\n\n }).error(function (res) {\n if (typeof callback === 'function') {\n callback(null, res);\n }\n });\n };\n\n // search contacts\n this.searchContacts = function (options, callback) {\n let defaultOptions = {\n sortBy: 'nameAsc',\n offset: 0,\n limit: 100,\n fetch: 1,\n needExp: 1,\n query: '',\n types: 'contact',\n tz: {\n id: 'Asia/Bangkok'\n },\n locale: 'en_US'\n };\n\n let request = angular.extend({}, defaultOptions, options);\n return $http({\n url: $rootScope.API_URL + '/searchRequest',\n method: 'POST',\n data: request\n }).success(function (res) {\n if (typeof callback === 'function') {\n if ( angular.isDefined(res.cn) ) {\n callback(res);\n } else {\n callback([]);\n }\n }\n\n }).error(function (res) {\n if (typeof callback === 'function') {\n callback(null, res);\n }\n });\n };\n\n\n /**\n * Move contact\n * @param {object} options\n * @param {number} options.id - Contact ID\n * @param {number} options.l - Folder ID\n */\n\n this.moveContact = function (options, callback) {\n let defaultOptions = {\n op: 'move',\n l: 7\n };\n let request = angular.extend({}, defaultOptions, options);\n if (angular.isDefined(request.id)) {\n return $http({\n url: $rootScope.API_URL + '/contactAction',\n method: 'POST',\n data: request\n }).success(function (res) {\n if (typeof callback === 'function') {\n callback(res);\n }\n\n }).error(function (res) {\n if (typeof callback === 'function') {\n callback(null, res);\n }\n });\n } else {\n logger.error('Id is required');\n }\n };\n\n /**\n * Delete a contact from trash\n * @param {number} contactId - Contact ID\n */\n this.deleteContactFromTrash = function (contactId, callback) {\n let request = {\n op: 'delete',\n id: contactId\n };\n\n if (angular.isDefined(request.id)) {\n return $http({\n url: $rootScope.API_URL + '/contactAction',\n method: 'POST',\n data: request\n }).success(function (res) {\n if (typeof callback === 'function') {\n callback(res);\n }\n\n }).error(function (res) {\n if (typeof callback === 'function') {\n callback(null, res);\n }\n });\n } else {\n logger.error('Id is required');\n }\n };\n\n /**\n * Create a folder\n * @param {object} options\n * @param {string} options.name - If \"l\" is unset, name is the full path of the new folder;\n * @param {number} options.color - color numeric; range 0-127;\n */\n this.createContactFolder = function (options, callback) {\n let defaultOptions = {\n view: 'contact',\n color: 1\n };\n let request = angular.extend({}, defaultOptions, options);\n if (angular.isDefined(request.name) && angular.isDefined(request.name)) {\n return $http({\n url: $rootScope.API_URL + '/createFolder',\n method: 'POST',\n data: request\n }).success(function (res) {\n if (typeof callback === 'function') {\n callback(res);\n }\n\n }).error(function (res) {\n if (typeof callback === 'function') {\n callback(null, res);\n }\n });\n } else {\n logger.error('name is required');\n }\n };\n\n /** Create Contact\n *\n * @param {object} options\n * @param {number} options.folderId\n * @param {object} options.contactAttrs\n *\n */\n this.createContact = function (options, callback) {\n let defaultOptions = {\n folderId: 7\n };\n let request = angular.extend({}, defaultOptions, options);\n if (angular.isDefined(request.contactAttrs)) {\n return $http({\n url: $rootScope.API_URL + '/createContact',\n method: 'POST',\n data: request\n }).success(function (res) {\n if (typeof callback === 'function') {\n callback(res);\n }\n\n }).error(function (res) {\n if (typeof callback === 'function') {\n callback(null, res);\n }\n });\n } else {\n logger.error('contactAttrs is required');\n }\n };\n\n /** Modify Contact\n *\n * @param {object} options\n * @param {number} options.id\n * @param {object} options.contactAttrs\n *\n */\n this.modifyContact = function (options, callback) {\n let defaultOptions = {};\n let request = angular.extend({}, defaultOptions, options);\n if (angular.isDefined(request.contactAttrs) && angular.isDefined(request.id)) {\n return $http({\n url: $rootScope.API_URL + '/modifyContact',\n method: 'POST',\n data: request\n }).success(function (res) {\n if (typeof callback === 'function') {\n callback(res);\n }\n\n }).error(function (res) {\n if (typeof callback === 'function') {\n callback(null, res);\n }\n });\n } else {\n logger.error('id and contactAttrs are required');\n }\n };\n\n /** Delete Contact\n *\n * @param {number} contactId\n *\n */\n this.deleteContact = function (options, callback) {\n let defaultOptions = {\n id: options.id,\n folderId: 3,\n op: 'move'\n };\n let request = angular.extend({}, defaultOptions, options);\n if (angular.isDefined(options.id)) {\n return $http({\n url: $rootScope.API_URL + '/contactAction',\n method: 'POST',\n data: request\n }).success(function (res) {\n if (typeof callback === 'function') {\n callback(res);\n }\n\n }).error(function (res) {\n if (typeof callback === 'function') {\n callback(null, res);\n }\n });\n } else {\n logger.error('contact_id is required');\n }\n };\n\n /** Move Contact\n *\n * @param {number} contactId\n * @param {number} folderId\n *\n */\n this.moveContact = function (contactId, folderId, callback) {\n if (angular.isDefined(contactId) && angular.isDefined(folderId)) {\n let request = {\n id: contactId,\n folderId: folderId,\n op: 'move'\n };\n return $http({\n url: $rootScope.API_URL + '/contactAction',\n method: 'POST',\n data: request\n }).success(function (res) {\n if (typeof callback === 'function') {\n callback(res);\n }\n\n }).error(function (res) {\n if (typeof callback === 'function') {\n callback(null, res);\n }\n });\n } else {\n logger.error('contactId and folderId are required');\n }\n };\n\n /** Assign Tag to Contact\n *\n * @param {number} contactId\n * @param {string} tags\n *\n */\n this.assignTagToContact = function (contactId, tags, callback) {\n if (angular.isDefined(contactId) && angular.isDefined(tags)) {\n let request = {\n op: 'tag',\n tn: tags,\n id: contactId\n };\n return $http({\n url: $rootScope.API_URL + '/contactAction',\n method: 'POST',\n data: request\n }).success(function (res) {\n if (typeof callback === 'function') {\n callback(res);\n }\n\n }).error(function (res) {\n if (typeof callback === 'function') {\n callback(null, res);\n }\n });\n } else {\n logger.error('contactId and tags are required');\n }\n };\n\n /** Remove Tag In Contact\n *\n * @param {number} contactId\n * @param {string} tags\n *\n */\n this.removeTagInContact = function (contactId, tags, callback) {\n if (angular.isDefined(contactId) && angular.isDefined(tags)) {\n let request = {\n op: '!tag',\n tn: tags,\n id: contactId\n };\n return $http({\n url: $rootScope.API_URL + '/contactAction',\n method: 'POST',\n data: request\n }).success(function (res) {\n if (typeof callback === 'function') {\n callback(res);\n }\n\n }).error(function (res) {\n if (typeof callback === 'function') {\n callback(null, res);\n }\n });\n } else {\n logger.error('contactId and tags are required');\n }\n };\n\n /** Remove All Tag In Contact\n *\n * @param {number} contactId\n *\n */\n this.removeAllTagInContact = function (contactId, callback) {\n if (angular.isDefined(contactId)) {\n let request = {\n op: 'update',\n tn: '',\n id: contactId\n };\n return $http({\n url: $rootScope.API_URL + '/contactAction',\n method: 'POST',\n data: request\n }).success(function (res) {\n if (typeof callback === 'function') {\n callback(res);\n }\n\n }).error(function (res) {\n if (typeof callback === 'function') {\n callback(null, res);\n }\n });\n } else {\n logger.error('contactId and tags are required');\n }\n };\n}", "function searcher() {\r\n var temp = \"\";\r\n var length = search.value.length;\r\n if (!searchValidation()) {\r\n contactsList.innerHTML = \"\";\r\n DBAlert.innerHTML = \"NOT FOUND\";\r\n DBAlert.style.display = \"block\";\r\n\r\n for (var i = 0; i < DB.length; i++) {\r\n length = search.value.length;\r\n if (\r\n check(DB[i].name, length, search) ||\r\n check(DB[i].phone, length, search) ||\r\n check(DB[i].address, length, search)\r\n ) {\r\n DBAlert.style.display = \"none\";\r\n //alert( search.value.length)\r\n temp +=\r\n '<div class=\"contact\"><div>' +\r\n DB[i].name +\r\n \"</div> <div>\" +\r\n DB[i].phone +\r\n \"</div> <div>\" +\r\n DB[i].address +\r\n \"</div> <div><i onClick=\\\"deletes('\" +\r\n i +\r\n ' \\')\" id=\"deleteContact\" class=\"fas contact-icon fa-minus-circle\"></i><i class=\"fas contact-icon fa-edit\"></i> <a href=tel:\\'' +\r\n DB[i].phone +\r\n '\\'><i class=\"fas contact-icon fa-phone-volume\"></i></a></div></div>';\r\n contactsList.innerHTML = temp;\r\n }\r\n }\r\n }\r\n}", "@wire(searchRecordList, {objectApi: CONTACT_OBJECT, fields:FIELDS, filterVars:'$filterVars', offset:0, limits:100})\n wire_getRecordList({error, data}){\n this.contactList = [];\n this.total = 0;\n if (data){\n console.log('query contacts:');\n \n (data.result || []).forEach(e=>{\n console.log(JSON.stringify(e));\n this.contactList.push(JSON.parse(JSON.stringify(e)));\n });\n this.total = data.count;\n this.renderDropItems();\n console.log(data.count);\n }else if (error){\n this.error = error;\n }\n }", "function refreshContacts() {\n client.contacts.refresh()\n}", "async getAllContacts() {\n return await axios.get(endpoint + \"contacts\");\n }", "function viewContact() {\n let searchResultList = search()\n console.log(`The person are ${searchResultList}`)\n}", "function chosenGoingTo(){\n let localContacts;\n //llamando a la referencia de data base\n database.ref('localContacts').once('value')\n .then((local) => {\n local.forEach((localContact) => { \n const string = JSON.stringify(localContact);\n const evaluar = string.includes('Laboratoria');\n console.log(evaluar);\n //console.log(JSON.stringify(local.nombre));\n //console.log(localContacts);\n });\n });\n}", "function querySearch (criteria) {\n \t//var defer = $q.defer();\n \t\n\t\t//return defer.promise;\n return criteria ? self.allContacts.filter(createFilterFor(criteria)) : [];\n }", "function CheckContactList() {\n var isContact = JSON.parse(localStorage.getItem('isContact'));\n console.log(isContact.length);\n \n //Kurt\n if (isContact.indexOf(\"kurt\") != -1) { // if Kurt is found in the Array of contacts (isContact) --> -1 if he wasn't a contact\n document.getElementById(\"contact_kurt\").style.display = \"flex\"; // on the \"my contacts\" page, Kurt gets displayed as a contact\n }\n if (isContact.indexOf(\"kurt\") == -1) {\n document.getElementById(\"contact_kurt\").style.display = \"none\"; // on the \"my contacts\" page, Kurt is no longer a contact\n }\n \n //Luke\n if (isContact.indexOf(\"luke\") != -1) { \n document.getElementById(\"contact_luke\").style.display = \"flex\"; \n }\n if (isContact.indexOf(\"luke\") == -1) {\n document.getElementById(\"contact_luke\").style.display = \"none\"; \n }\n \n //Emma\n if (isContact.indexOf(\"emma\") != -1) { \n document.getElementById(\"contact_emma\").style.display = \"flex\"; \n }\n if (isContact.indexOf(\"emma\") == -1) {\n document.getElementById(\"contact_emma\").style.display = \"none\"; \n }\n}", "function getContact(){\r\n var mycontact = getContacts();\r\n return mycontact;\r\n}", "function requestExternalContacts() {\n let apiInstance = new platformClient.ExternalContactsApi();\n let opts = {\n pageSize: 6,\n pageNumber: 1\n };\n return apiInstance.getExternalcontactsContacts(opts)\n .then(data => {\n return data;\n });\n }", "function getContactByContactId(contactId) {\n\n var deferred = new $.Deferred();\n \n var contactList = window.Compass.Helm.LoanContacts;\n var contact = null;\n\n for (var i = 0; i < contactList.length; i++) {\n if (contactList[i] !== null && contactList[i].ContactId === contactId) {\n contact = contactList[i];\n break;\n }\n }\n\n deferred.resolve(contact);\n return deferred.promise();\n\n }", "fetchContacts() {\n Contacts.getAll((err, contacts) => {\n if (err && err.type === 'permissionDenied'){\n console.log('permission denied!')\n this.setState({\n loaded: true,\n permission: 'no',\n });\n } else if (err) {\n console.log(err);\n // should probably show an error message in the ui\n } else {\n // add more dummy entries for testing purposes only\n // if (contacts.length < 10) {\n // contacts = contacts.concat(_.map(contacts, c => {\n // var d = _.clone(c); d.recordID *= 100; return d;\n // }));\n // }\n // add test entry\n var testEntry = _.clone(contacts[0]);\n testEntry.givenName = 'Venkat';\n testEntry.familyName = 'Quone Test';\n testEntry.phoneNumbers[0].number = myPhone;\n testEntry.recordID = 19642;\n contacts = contacts.concat([testEntry]);\n\n this.setState({\n loaded: true,\n permission: 'yes',\n contacts: this.getContactsRows(contacts)\n });\n console.log(this.state.contacts);\n }\n })\n }", "contactListFirst (query) {\n return this\n .contactList(query)\n .then(contacts => contacts[0] ? contacts[0] : null)\n ;\n }", "async function listContacts(app,argv) {\n const db = new dbstore.DynamoContactStore(await app.getVariables())\n console.log(await db.getAllContacts())\n}", "function dynamicSeperation() {\n //Search by Name\n name = dynamicRoster.All.map(function (a) {\n return a[\"Full Name\"];\n });\n // [[NOTICE]]: There may be an error where email never has anything removed from it. If this occurs, place 'email' right above 'for' loop below :D\n // Search by Email\n email = dynamicRoster.All.map(function (a) {\n return a[\"Email Address\"];\n });\n //Search by Phone Number\n phoneNumber = dynamicRoster.All.map(function (a) {\n return a[\"Phone Number\"];\n });\n}", "get contacts() {\r\n return new Contacts(this);\r\n }", "get contacts() {\r\n return new Contacts(this);\r\n }", "function getContactList() {\n // Call Web API to get a list of Phones\n $.ajax({\n url: '/Contact/GetContactList/',\n type: 'GET',\n data: {\n pageNumber: currentPage,\n pageSize: pageSize,\n searchValue: searchValue\n },\n success: function (contacts) {\n contactListSuccess(contacts);\n },\n error: function (request, message, error) {\n handleException(request, message, error);\n }\n });\n}", "async _getContacts () {\n try {\n var contacts = await profile.getContacts();\n this.setState({ contacts: contacts });\n } catch (e) {\n console.error(e, e.stack);\n }\n }", "_loadContacts(callback){\n //Define an empty void if no callback specified\n if(callback === undefined){\n callback = _ => {};\n }\n\n var self = this;\n contactsEndpoint.contacts(this.token, function(errors, answer){\n if(errors === null){\n for (let groupAnswer of answer['Groups']){\n //Take only servers\n if(groupAnswer.GroupType == groupsEndpoints.GroupType.Large){\n //Check that server is not already existing\n if(self.servers.has(groupAnswer.GroupID) == false){\n var server = new serverModule.Server(groupAnswer.GroupID, self);\n }\n }\n }\n\n self.friendList = answer['Friends']; //Thoses friends are not useable yet (who needs friends ?)\n callback(null);\n } else {\n callback(errors);\n }\n });\n\n }", "function setContactsInStore(contacts) {\n return {\n type: SET_CONTACTS,\n contacts\n }\n}", "function filterContacts(contacts, filter) {\n return contacts.filter(({ user }) => {\n for (const key in user) {\n if (typeof user[key] === 'string' && user[key].toLowerCase().includes(filter.toLowerCase())) return true;\n }\n return false;\n });\n}", "function searchingQuery(criteria){\n \treturn pendingSearch = $q(function(resolve, reject){\n \t\tcancelSearch = reject;\n\n \t\t$http({\n\t\t method: 'GET',\n\t\t url: 'http://45.55.7.118:5000/api/user/admin/people/search/'+criteria,\n\t\t }).success(function(data){\n self.allContacts = [];\n data.data.forEach(function(user) {\n var contact = {\n names: user.names +\" \"+ user.surnames,\n device_os: user.device_os,\n user_id: user.user_id,\n device_token: user.device_token,\n image: user.main_image\n }\n contact._lowername = contact.names.toLowerCase();\n self.allContacts.push(contact);\n\n });\n\n\t\t \t\n \t\t//self.allContacts[0] = contact;\n\n\t\t \tresolve(self.querySearch(criteria));\n\t\t \t//self.asyncContacts = data.data[0].description;\n\t\t }).error(function(){\n\n\t\t SweetAlert.swal(\"Error al cargar cupones, porfavor refresque la pagina\", \"\", \"error\")\n\t\t });\n\n \t})\n \treturn pendingSearch;\n }", "function _get_client_contacts_list(db){\n try{ \n var rows = db.execute('SELECT * FROM my_client_contact WHERE status_code=1 and client_id in ('+\n 'select a.client_id from my_'+_type+' as a where a.id=?) and '+\n 'id in (select b.client_contact_id from my_'+_type+'_client_contact as b where b.'+_type+'_id=? and b.status_code=1)',_selected_job_id,_selected_job_id);\n var b = 0;\n if(rows.getRowCount() > 0){\n while(rows.isValidRow()){\n var row = Ti.UI.createTableViewRow({\n filter_class:'client_contact',\n className:'client_contact_list_data_row_'+b,\n hasChild:true,\n source:_source,\n job_id:_selected_job_id,\n client_id:rows.fieldByName('client_id'),\n contact_id:rows.fieldByName('id'),\n title:rows.fieldByName('first_name')+' '+rows.fieldByName('last_name'),\n mobile:rows.fieldByName('phone_mobile'),\n email:rows.fieldByName('email')\n }); \n if(b === 0){\n row.header = 'Client Contacts';\n }\n self.data.push(row);\n rows.next();\n b++;\n }\n }\n rows.close();\n }catch(err){\n self.process_simple_error_message(err,window_source+' - _get_client_contacts_list');\n return;\n } \n }", "handleSearch(term) {\n let contactsFiltered = this.state.contacts.filter( (contact) => Object.values(contact).some( (blob) => blob.includes(term)));\n this.setState({\n contactsFiltered: contactsFiltered\n })\n }", "function loadContacts() {\n// clear the previous list\n// grab the tbody element that will hold the new list of addresss\n// Make an Ajax GET call to the 'addresss' endpoint. Iterate through\n// each of the JSON objects that are returned and render them to the\n// summary table.\n $.ajax({\n url: \"address\"\n }).success(function (data, status) {\n fillAddressTable(data, status);\n });\n}", "getAll(){\n\n return this.contactos;\n\n }", "function listOptions( theContacts )\r\n{\r\n var s ='';\r\n for( var contact in theContacts )\r\n {\r\n if (s != '') { s = s + \", \" };\r\n s = s + contact + \" (\" + theContacts[ contact ].nameChoices + \")\";\r\n }\r\n return s;\r\n}", "function getContacts() {\n $scope.phoneContacts = [];\n\n $cordovaContacts.find({}).then(function(contacts) {\n //On success callback function.\n console.log(JSON.stringify(contacts));\n\n for (var i = 0; i < contacts.length; i++) {\n var contact = contacts[i];\n\n //window.alert(JSON.stringify(contact.photos));\n if (contacts[i].phoneNumbers !== null) {\n\n if (contact.displayName === null) {\n if (contact.name.givenName !== null)\n contact.displayName = contact.name.givenName;\n else \n contact.displayName = \"Unknown Name\";\n }\n\n $scope.phoneContacts.push(contact);\n }\n }\n\n //Sort function alphabetically.\n //http://stackoverflow.com/questions/6712034/sort-array-by-firstname-alphabetically-in-javascript\n $scope.phoneContacts.sort(function(a, b){\n if(a.displayName < b.displayName) return -1;\n if(a.displayName > b.displayName) return 1;\n return 0;\n });\n }, function(Error) {\n //On failure callback function\n MyCareMakerPopups.showAlert(\"Error\" ,\n \"There was an problem loading your contacts. \", null);\n });\n\n }", "function getAll() {\r\n $.getJSON(\"http://localhost:8080/api/contacts\", (data) => {\r\n if (data !== undefined && data.length !== 0) {\r\n updateContacts(data);\r\n }\r\n }).fail((err) => console.log(\"Couldn't contacts \", err));\r\n}", "function checkContactGrants() {\r\n AppController.serverController.getRepoInterface().search(new EcContactGrant().getSearchStringByType(), function (encryptedValue) {\r\n EcRepository.get(encryptedValue.shortId(), function (encryptedValue) {\r\n var ev = new EcEncryptedValue();\r\n ev.copyFrom(encryptedValue);\r\n var grant = ev.decryptIntoObject();\r\n if (grant != null) {\r\n var g = new EcContactGrant();\r\n g.copyFrom(grant);\r\n if (g.valid())\r\n ModalManager.showModal(new ContactAcceptModal(g, function () {\r\n refreshContacts(EcIdentityManager.contacts);\r\n ModalManager.showModal(new SaveIdModal(\"You have added a contact\"));\r\n }));\r\n }\r\n }, null);\r\n }, null, null);\r\n }", "trovaContatto(){\n\n this.contacts.forEach( (element)=> {\n console.log(element.name)\n const search = this.ricercaContatto.toLowerCase();\n const rinomina = element.name.toLowerCase();\n\n \n element.visible = rinomina.includes(search);\n \n });\n \n \n \n\n }", "GetContactList() {\n return this.m_contactManager.m_contactList;\n }", "function loadContacts() {\n let storedContacts = JSON.parse(window.localStorage.getItem(\"contacts\"))\n if (storedContacts) {\n contacts = storedContacts\n }\n}", "function loadContacts() {\n let storedContacts = JSON.parse(window.localStorage.getItem(\"contacts\"))\n if (storedContacts) {\n contacts = storedContacts\n }\n}", "function search( input ){\n // select chat list -> contacts -> each( user name ? search input )\n $('.chat-list .contact').each( function() {\n //var filter = this.innerText; // < - You, Me , I ( for log user )\n //var _val = input[0].value.toUpperCase();\n\n if ( this.innerText.indexOf( input[0].value.toUpperCase() ) > -1)\n this.style.display = \"\";\n else this.style.display = \"none\";\n\n });\n\n}", "function loadContacts() {\n let storedContacts = JSON.parse(window.localStorage.getItem('contacts'))\n if (storedContacts) {\n contacts = storedContacts\n }\n}", "@wire(findContacts, { searchKey: '$searchKey' })\n contacts({err, data}) {\n if (data) {\n this.donors = data;\n } else if (err) {\n console.log(err);\n }\n }", "function initContactList() {\n // Get a reference to the database service for \"user\" node.\n var database = firebase.database();\n var ref = database.ref(\"bbmsdk/identity/users/\");\n\n // If the local user isn't already registered in firebase, add them now.\n database.ref('bbmsdk/identity/users/' + firebase.auth().currentUser.uid).set({\n regId: userRegId,\n email: googleUserEmail,\n avatarUrl: googleUserAvatarImageURL,\n name: googleUserName\n }).catch(function (error) {\n console.error('Error registering user in firebase: ' + error);\n });\n\n //listen to 'child_added' from \"user\" node in the database.\n ref.on('child_added', function (user) {\n var regId = user.val().regId;\n var name = user.val().name;\n var key = user.key;\n\n if (regId !== undefined) {\n //exclude the local user from the contact list\n if (regId !== userRegId) {\n console.log(\"Rich Chat: Firebase 'User' - child_added: \" + name\n + \" key: \" + key + \" regId: \" + regId);\n\n //Check if the contact map contains a contact that has the same regId\n if (contactsMap[regId] == undefined) {\n //Create a BBMData (having id: 'contact-RegId') to wrap \"user\" object for data binding\n var contactData = new BBMData(DATA_BIND_PREFIX_CONTACT + regId);\n\n // Add the user into the map, so the user can be found by its regId.\n // This must happen first so that any updates that are triggered by calling\n // contactData.set() below will be able to find the relevant data.\n contactsMap[regId] = contactData;\n\n //At this point, we only set the properties needed by UI elements.\n contactData.set(DATA_CONTACT_NAME, name);\n contactData.set(DATA_CONTACT_IMG_URL, user.val().avatarUrl);\n\n //Add the user to the list on the contact tab to display\n addContactToContactTab(regId);\n } else {\n //Filter out a new contact who has the same regId with the existing contact in the map.\n //This is to avoid the duplicated contacts in the current database.\n console.log(\"Rich Chat: Contact map already has an entry with the same RegId: \" + regId\n + \". This 'User' of name: \" + name + \" key: \" + key + \" will be ignored.\");\n }\n }\n } else {\n showErrorDialog(\"Contact '\" + key + \"' from the database doesn't have a BBM registration ID\");\n }\n });\n\n //listen to 'child_changed' from \"user\" node in the database.\n ref.on('child_changed', function (user) {\n var regId = user.val().regId;\n var name = user.val().name;\n var contactData = contactsMap[regId];\n\n console.log(\"Rich Chat: Firebase 'User' - child_changed: \" + name + \" key: \" + user.key\n + \" regId: \" + regId);\n\n if (regId !== undefined) {\n //Check if the contact map contains a contact that has the same regId\n if (contactData != undefined) {\n //Replace the properties with the new ones and the data binder should trigger the UI elements to update\n contactData.set(DATA_CONTACT_NAME, name);\n contactData.set(DATA_CONTACT_IMG_URL, user.val().avatarUrl);\n } else {\n //Prevent the map from updating a contact that was never added before\n console.log(\"Rich Chat: Firebase 'User' of RegId: \" + regId\n + \" has never been added to map before. Ignore this child_changed\");\n }\n } else {\n showErrorDialog(\"Contact '\" + key + \"' from the database doesn't have a BBM registration ID\");\n }\n });\n\n //listen to 'child_removed' from \"user\" node in the database.\n ref.on('child_removed', function (user) {\n var regId = user.val().regId;\n\n console.log(\"Rich Chat: Firebase 'User' - child_removed: \" + user.val().name + \" key: \" + user.key\n + \" regId: \" + regId);\n\n if (regId !== undefined) {\n //Check if the contact map contains a contact that has the same regId\n if (contactsMap[regId] != undefined) {\n //remove the user from the map\n delete contactsMap[regId];\n\n //remove the user from the list on the contact tab\n removeContactFromContactTab(regId);\n } else {\n //Prevent the map from removing a contact that was never added before\n console.log(\"Rich Chat: Firebase 'User' of RegId: \" + regId\n + \" has never been added to map before. Ignore this child_removed\");\n }\n } else {\n showErrorDialog(\"Contact '\" + key + \"' from the database doesn't have a BBM registration ID\");\n }\n });\n}", "function searchPhones() {\n var input = document.getElementById(\"searchFieldPhones\").value;\n document.getElementById(\"selectPhone\").innerText = null;\n for (i = 0; i < phones.data.length; i++) {\n if (phones.data[i][\"NAME\"].toLowerCase().includes(input.toLowerCase()) ||\n phones.data[i][\"CABIN\"] == input ||\n phones.data[i][\"PAGER\"] == input ||\n phones.data[i][\"PHONE\"] == input) {\n var option = document.createElement('option');\n option.text = option.value = phones.data[i][\"NAME\"];\n document.getElementById(\"selectPhone\").add(option);\n }\n }\n phoneSelected()\n}", "function LINQ() {\n this.query = new OneXrm.Query.QueryExpression(contact);\n }", "function onDeviceReady() \n{\n\n\t StatusBar.overlaysWebView(true);\n\n StatusBar.show();\n\n // find all contacts with 'Bob' in any name field\n var options = new ContactFindOptions();\n options.filter=\"\"; \n options.multiple=true;\n var fields = [\"displayName\", \"phoneNumbers\", \"photos\"];\n navigator.contacts.find(fields, onSuccess, onError, options);\n \n}", "function onDeviceReady() {\n // find all contacts with 'Bob' in any name field\n var options = new ContactFindOptions();\n options.filter=\"\"; \n var fields = [\"displayName\", \"name\"];\n navigator.contacts.find(fields, onSuccess, onError, options);\n }", "function appendToLists(contact) {\n updatePhoto(contact);\n var ph = createPlaceholder(contact);\n var groups = [ph.dataset.group];\n if (isFavorite(contact)) {\n groups.push('favorites');\n }\n\n var nodes = [];\n\n for (var i = 0, n = groups.length; i < n; ++i) {\n ph = appendToList(contact, groups[i], ph);\n nodes.push(ph);\n ph = null;\n }\n\n selectedContacts[contact.id] = selectAllPending;\n\n return nodes;\n }", "function loadContacts() {\n\tcontactArray.length = 0;\n\tloadingContact = 0;\n\tif(contactURLArray.length > loadingContact) {\n\t\tloadNextContact(contactURLArray[loadingContact]);\n\t} \n}", "function getAllContacts() {\n defer = $q.defer();\n\n $http({\n method: 'GET',\n url: DATASERVICECONSTANTS.BASE_URL + '/contacts',\n timeout: 5000\n }).then(function successCallback(response) {\n defer.resolve(response);\n }, function errorCallback(response) {\n defer.reject(response);\n });\n\n return defer.promise;\n }", "function getContacts(req, res) {\n\n\tdb.child('/contacts').once('value')\n\t.then((snapshot) => {\n\n\t\tlet database = snapshot.val();\n\n\t\tlet data = {};\n\t\tdata[\"contacts\"] = new Array();\n\n\t\tfor(let category in database) {\n\n\t\t\tlet type = {};\n\t\t\ttype[\"section\"] = category;\n\t\t\ttype[\"people\"] = new Array();\n\n\t\t\tfor(let person in database[category]) {\n\n\t\t\t\ttype[\"people\"].push(database[category][person]);\n\t\t\t}\n\n\t\t\tdata[\"contacts\"].push(type);\n\t\t}\n\n\t\tres.set('Cache-Control', 'public, max-age=3600 , s-maxage=7200');\n\t\treturn res.status(200).json({\n\t\t\tdata: data,\n\t\t\tsuccess: true\n\t\t});\n\t})\n\t.catch(() => {\n\n\t\treturn res.status(500).json({\n\t\t\tsuccess: false,\n\t\t\tmessage: 'could not fetch contacts'\n\t\t});\n\t})\n\n}", "async _fetchContact() {\n const { id, emailaddress1, contactid } = await this.store.queryRecord('contact', { me: true });\n\n return { id, emailaddress1, contactid };\n }" ]
[ "0.74078786", "0.6876069", "0.6838361", "0.67402154", "0.667373", "0.66549456", "0.6642438", "0.6420536", "0.641671", "0.63855106", "0.6385502", "0.6376897", "0.63427997", "0.6310897", "0.6303494", "0.62839806", "0.6268982", "0.6189789", "0.61882216", "0.61677134", "0.6161765", "0.6139039", "0.6110893", "0.61049694", "0.60847306", "0.60804236", "0.6050757", "0.60245776", "0.60241354", "0.6010411", "0.5984251", "0.5979267", "0.5978054", "0.59464324", "0.59123355", "0.5902242", "0.5899805", "0.5885369", "0.58772725", "0.58615446", "0.5849184", "0.5825208", "0.5821829", "0.57966316", "0.5780796", "0.57782143", "0.5761886", "0.57615846", "0.5751859", "0.57292986", "0.5727054", "0.5725557", "0.5717373", "0.57017475", "0.5694862", "0.5693271", "0.56892645", "0.56714606", "0.567017", "0.5661158", "0.56505126", "0.5643169", "0.56100774", "0.5608636", "0.5607321", "0.5601553", "0.55959", "0.5577325", "0.5577325", "0.5576314", "0.55750644", "0.5565532", "0.5548298", "0.55331445", "0.5515222", "0.55147207", "0.5507378", "0.5501364", "0.550018", "0.5499145", "0.5493362", "0.5467635", "0.5461303", "0.5451839", "0.54508954", "0.5435362", "0.5435362", "0.54311514", "0.5428603", "0.5425161", "0.54195863", "0.5400401", "0.5390056", "0.5383748", "0.53835666", "0.53809005", "0.5373691", "0.5366466", "0.53639007", "0.5361978" ]
0.62141
17
ADDS A CONTACT TO THE CONTACT LIST (NAME, ALIAS, TEAM, HOBBIES)
function add() { //get contact information from page var values = $('#addForm :input'); //an array of all inputs var inputs = $('#addForm').serialize(); //serialized version of the inputs //get each part of the contact var name = values[0].value; var alias = values[1].value; //alias = key var team = values[2].value; var hobbies = values[3].value; if (name && alias && team) { console.log($("#addForm").serialize()); //add contact $.post(uri, inputs, "json"); $('#addContact').text("Added " + name + " [ " + alias + " ] to the database."); $('#refresh').show(); //refresh the page to show the updated contact list } else { $('#addContact').text("To add a contact, you need NAME, ALIAS and TEAM."); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function addContact(){\n var name = readLineSync.question('name: ');\n var phoneNum = readLineSync.question('phone: ');\n var contact = {\n Name: name,\n Phone: phoneNum\n };\n listContact.push(contact);\n save();\n console.log(\"\\nthem thanh cong nhe!\");\n}", "function addContact(){\n let lastName = prompt('Ajouter un nom');\n let firstName = prompt('Ajouter un prénom');\n let newContact = new Contact(lastName, firstName);\n allContacts.push(newContact);\n}", "function addContactsToListView()\n{\n\t//Create \"FROM CONTACTS\" section header\n contactsSections.push(createSection('FROM CONTACTS', data));\n\n\t//Loop through people array and create appropriate listView sections\n\tfor (var i = 0; i < people.length; i++)\n\t{\n\t\t\tif(!sectionTitle)\n\t\t\t{\n\t\t\t\tsectionTitle = people[i].fullName.charAt(0).toLowerCase();\n\t\t\t}\n\t\t\telse if(sectionTitle !== people[i].fullName.charAt(0).toLowerCase())\n\t\t\t{\n\t\t\t\t// Add a section\n\t\t\t\tcontactsSections.push(createSection(sectionTitle.toUpperCase(), data));\n\t\t\t\tdata = [];\n\t\t\t\t\t\t\n\t\t\t\t// New section title\n\t\t\t\tsectionTitle = people[i].fullName.charAt(0).toLowerCase();\n\t\t\t}\n\t\t\t\t\t\n\t\t\t\tdata.push({\n\t\t\t\t\t\tcontact:\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttext: people[i].fullName\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\tproperties: \n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\titemId: people[i].identifier,\n\t\t\t\t\t\t\tphone: people[i].mobile,\n\t\t\t\t\t\t\tsearchableText: people[i].fullName,\n\t\t\t\t\t\t\tfirstName: people[i].firstName,\n\t\t\t\t\t\t\tlastName: people[i].lastName\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\ttemplate: 'contact',\n\t\t\t\t\t\tselected: false\n\t\t\t\t});\n\t\t\t\t\t\n\t\t\t\t// Add the last section\n\t\t\t\t\tif(i == people.length - 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tcontactsSections.push(createSection(sectionTitle.toUpperCase(), data));\n\t\t\t\t\t\t}\n\t}//end of loop through people array for loop\n\t\n\tif(friends.length > 0)\n\t{\n\t\tlistView.insertSectionAt(1,contactsSections);\n\t}else{\n\t\tlistView.insertSectionAt(0,contactsSections);\n\t}\n}", "function addContact(req, res, next) {\n List\n .findById(req.params.id)\n .populate('services')\n .exec(function (err, list) {\n if (err) {\n res.send(404, new Error('List not found'));\n return next(false);\n }\n\n var index = list.contacts.indexOf(req.body.contact);\n if (index != -1) {\n res.send(409, new Error('Contact is already in list'));\n return next(false);\n }\n else {\n list.contacts.push(req.body.contact);\n list.save(function (err) {\n if (err) {\n res.send(404, new Error('Unknown error saving list'));\n return next(false);\n }\n // Subscribe contact to services\n if (list.services.length) {\n Contact\n .findById(req.body.contact)\n .populate('_profile')\n .exec(function (err, contact) {\n if (!err && contact && contact.email.length) {\n var profile = contact._profile;\n list.services.forEach(function (service) {\n if (service.auto_add) {\n var merge_vars = { 'fname': contact.nameGiven, 'lname': contact.nameFamily };\n service.subscribe(profile, contact.email[0].address, merge_vars);\n }\n });\n }\n });\n }\n res.send(201, req.body.contact);\n return next();\n });\n }\n });\n}", "function addContact() {\n var newContact = {};\n\n // Set a default contact type\n newContact.typeId = 1;\n vm.contacts.push(newContact);\n }", "function addContact(data) {\n console.log(` Adding: ${data.name} (${data.owner})`);\n Contacts.collection.insert(data);\n}", "function add(firstName, lastName, phoneNumber, email) {\n contacts[contacts.length] = {\n firstName: firstName,\n lastName: lastName,\n phoneNumber: phoneNumber,\n email: email\n };\n}", "add(info) {\n this.contacts.push(new Contact(...info));\n }", "function addContact() {\n let contact = getContactFormData()\n if (!contact.contactId) {\n log('Cannot add a contact to the Address Book without a contact ID!')\n } else {\n client.contacts.add(getContactFormData())\n }\n}", "function addContact(contact) {\n contacts.push(contact);\n $localStorage.contacts = contacts;\n }", "function onAddContactToAddressBook(contact){\n try {\n var result = thisPresenter.addContact(contact);\n if(result) alert(\"Contatto [\" + mediator.createNameLabel(contact) + \"] aggiunto\");\n } catch (err) {\n alert(err);\n }\n }", "addContact (contacts) {\n // make variable for dom injection\n let contactList = document.getElementById(\"contactList\")\n // loop through objects returned from database for injection\n contacts.forEach((individualObj) => {\n contactList.innerHTML += domHTML.createContact(individualObj)\n })\n }", "addContact(contact){\n const { contacts } =this.state;\n this.setState({\n contacts: [ ...this.state.contacts, contact ]\n });\n }", "static addContact(contact) {\n const list = document.getElementById(\"contact-list\");\n // create tr\n const tr = document.createElement(\"tr\");\n tr.className = \"collection-contact\";\n tr.innerHTML = `\n <td class=\"filter-name\">${contact.name}</td>\n <td class=\"filter-number\">${contact.number}</td>\n <td><i class=\"ion-close-round btn btn-danger btn-sm delete\"></i></td>\n `;\n // append the child\n list.appendChild(tr);\n\n document.getElementById(\"name\").value = \"\";\n document.getElementById(\"number\").value = \"\";\n }", "addContact(contact) {\n // Create a new array with the list of existing items and the new contact at the end\n this.data = [...this.data, contact];\n\n // Rerender the list\n this.render();\n }", "function addContact() {\n tabPrenom.push(prompt(\"Ecrivez le prénom :\"));\n tabNom.push(prompt(\"Ecrivez le nom : \"));\n list();\n}", "function editContact(){\n var id = readLineSync.question('Lua chon id contact can sua: ');\n var name = readLineSync.question('name: ');\n var phone = readLineSync.question('phoneNum:');\n listContact[id].Name = name;\n listContact[id].Phone = phone;\n save();\n console.log(\"\\nsua thanh cong nhe!\");\n }", "function addContactToPhoneBook(currentObj) {\n var phoneNumbers = currentObj.phoneNumbers.split(',');\n var contact = readContact(currentObj.id, currentObj.firstName, currentObj.lastName, phoneNumbers);\n pushItem(currentGroup, contact);\n }", "function addContact(event) {\n event.preventDefault(); //avoid the normal submit functionality\n const formInputs = document.querySelectorAll(\"form>input\");\n const info = [];\n for (let input of formInputs) {\n info.push(input.value); //add the info to the array\n input.value = \"\"; //clear out the input after getting the info\n }\n addressBook.add(info); //add the contact to the addressBook\n addressBook.display(); //redisplay the contact container\n formInputs[0].focus(); //set focus to the first input again\n}", "function addToLeaseContacts(leaseId, contactId, isLsContactsDef){\n\tif (isLsContactsDef && valueExistsNotEmpty(contactId)) {\n\t\tvar dataSource = View.dataSources.get('abRepmLsContacts_ds'); \n\t\tvar restriction = new Ab.view.Restriction();\n\t\trestriction.addClause('ls_contacts.ls_id', leaseId, '=');\n\t\trestriction.addClause('ls_contacts.contact_id', contactId, '=');\n\t\tvar record = dataSource.getRecord(restriction);\n\t\tif (!valueExists(record.getValue('ls_contacts.contact_id'))) {\n\t\t\trecord = new Ab.data.Record({\n\t\t\t\t'ls_contacts.ls_id': leaseId,\n\t\t\t\t'ls_contacts.contact_id': contactId\n\t\t\t}, true);\n\t\t\tdataSource.saveRecord(record);\n\t\t}\n\t}\n}", "function addcontact(fullname, number, email, address, notes, website)\n{\n if (typeof (webphone_api.plhandler) !== 'undefined' && webphone_api.plhandler !== null)\n return webphone_api.plhandler.AddContact(fullname, number, email, address, notes, website);\n else\n return false;\n}", "async function addContact() {\n\t\tadd_contact_data_p.innerText = 'Adding contact...';\n\n\t\tconst data = {\n\t\t\t'first_name': add_contact_first_name_input.value,\n\t\t\t'last_name': add_contact_last_name_input.value,\n\t\t\t'email': add_contact_email_input.value\n\t\t};\n\n\t\tconst response = await submitPOSTRequest(data);\n\n\t\tif (response.ok) {\n\t\t\tadd_contact_data_p.innerText = 'Added to database!';\n\t\t} else {\n\t\t\tadd_contact_data_p.innerText = response.status + ' ' + response.statusText;\n\t\t}\n\t}", "function addNewContact( email ) {\n firebaseFunctions.addContato( currentUser.dataset.uid, email, () => {\n loadContacs();\n swal( {\n icon: 'success',\n title: 'Contato adicionado',\n } );\n }, true );\n}", "addRecipients() {\n const personalize = new helper.Personalization();\n this.recipients.forEach(recipient => {\n personalize.addTo(recipient);\n });\n this.addPersonalization(personalize);\n }", "function addUserInContactList( data ){\n\n\n var _div_date = ( data.date === null || data.date === undefined ) ? '' :\n '<div class=\"col-12 col-sm-auto d-flex flex-column align-items-end\"> \\\n <div class=\"last-message-time\">'+data.date+'</div> \\\n </div>';\n\n var _last_message = ( data.lastMessage === null || data.lastMessage === undefined ) ? '' : '<p class=\"last-message text-truncate text-muted\">'+ data.lastMessage +'</p>';\n\n var _contact =\n '<div class=\"contact ripple flex-wrap flex-sm-nowrap row p-4 no-gutters align-items-center\" id=\"'+data.user.id+'\" > \\\n \\\n <div class=\"col-auto avatar-wrapper\"> \\\n <img src=\"../assets/images/avatars/'+data.user.profilePicture+'\" class=\"avatar\" alt=\"'+data.user.firstName+'\" /> \\\n <i class=\"status '+ switchActive( data.user.action ) +' s-4\" name=\"status-contact\" ></i> \\\n </div> \\\n \\\n <div class=\"col px-4\"> \\\n <span class=\"name h6\">'+data.user.firstName+'</span> \\\n '+_last_message+' \\\n </div> \\\n \\\n '+_div_date+' \\\n \\\n </div> \\\n <div class=\"divider\"></div>';\n\n $('.chat-list').append( _contact ); // user - add in contact\n\n }", "function AddContacts(email) {\n if (!$scope.usersToMessage.replace(/^\\s+/g, '').length) {\n //alert(\"empty, adding\");\n if (email) {\n $scope.usersToMessage += email;\n }\n }\n\n else {\n //alert(\"else\");\n if (email) {\n $scope.usersToMessage += \", \" + email;\n }\n }\n }", "function addContact(state = [], action) {\n const userId = (state) ? (state.length + 1) : 1;\n\n return [\n //Keep the old state\n ...state,\n //Add the new contact\n {\n address : action.address,\n id: userId,\n mail : action.mail, \n name : action.name, \n phone: action.phone,\n surname : action.surname \n }\n ];\n}", "function makeContactList() {\n /*\n * You need something here to hold contacts. See length api for a hint:\n */\n var contacts = [];\n \n return {\n // we implemented the length api for you //\n length: function() {\n return contacts.length;\n },\n addContact: function(contact) {\n contacts.push(contact);\n return contacts;\n },\n findContact: function(fullName) {\n for (var i = 0; i < contacts.length; i++) {\n if (fullName === contacts[i].nameFirst + \" \" + contacts[i].nameLast) { return contacts[i];\n } else {\n return undefined;\n } \n }\n },\n removeContact: function(contact) {\n for (var i = 0; i < contacts.length; i++) {\n if (contacts[i] === contact) {\n contacts.splice(i, 1);\n }\n }\n \n }, printAllContactNames: function() {\n var returnedNames = \" \";\n for (var i = 0; i < contacts.length; i++) {\n returnedNames += \"\\n\" + contacts[i].nameFirst + \" \" + contacts[i].nameLast; \n } return returnedNames.trim();\n }\n \n };\n \n \n }", "function addContact() {\n // grab the values from form\n var tName = $(\"#cName\").val();\n var tPhone = $(\"#cPhone\").val();\n var tEmail = $(\"#cEmail\").val();\n //console.log(tName, tPhone, tEmail);\n // create a new object from the values\n var tc = new Contact(tName, tPhone, tEmail);\n console.log(tc);\n // add it to the array\n contacts.push(tc);\n showContacts();\n }", "function addContact(event) {\n event.preventDefault()\n let form = event.target\n\n let contact = {\n id: generateId(),\n name: form.name.value,\n phone: form.phone.value,\n emergencyContact: form.emergencyContact.checked\n }\n contacts.push(contact)\n saveContacts()\n form.reset()\n}", "add(givenName, surName, emailAddresses, businessPhones, additionalProperties = {}) {\r\n const postBody = extend({\r\n businessPhones: businessPhones,\r\n emailAddresses: emailAddresses,\r\n givenName: givenName,\r\n surName: surName,\r\n }, additionalProperties);\r\n return this.postCore({\r\n body: jsS(postBody),\r\n }).then(r => {\r\n return {\r\n contact: this.getById(r.id),\r\n data: r,\r\n };\r\n });\r\n }", "function addContact(user, userid, sendtype) {\n\n\t// Adds the contact to the list and the hidden id field. Will ignore click event if the\n\t// ID/contact exists in to[], cc[], or bcc[] fields\n\tif (sendtype == 'bcc') {\n \tvar field = window.opener.document.sendmail.namebcc;\n } else if (sendtype == 'cc') {\n var field = window.opener.document.sendmail.namecc;\n } else if (sendtype == 'to') {\n var field = window.opener.document.sendmail.nameto;\n }\n\n // Checks if the user is already sending to clicked user in some way\n if ( alreadySending('to', userid) ) {\n \treturn false;\n }\n\n if ( alreadySending('cc', userid) ) {\n return false;\n }\n\n if ( alreadySending('bcc', userid) ) {\n return false;\n }\n\n // Adds the user id to the hidden fields for submit\n // I Very Hate IE...had to do this ugly hack to get this to work for IE 6+ :(\n var contacts = window.opener.document.createElement(\"span\");\n window.opener.document.getElementById('id_name'+sendtype).parentNode.appendChild(contacts);\n contacts.innerHTML = '<input type=\"hidden\" value=\"'+userid+'\" name=\"'+sendtype+'[]\">';\n\n // Adds Name to sendtype list\n if (field.value == '') {\n \tfield.value = user;\n } else {\n \t// Checks for valid string entry for post-send validation\n if ((field.value.charAt(field.value.length-2) != ',')) {\n \tif ((field.value.charAt(field.value.length-1) != ',')) {\n \tuser = ', '+user;\n } else {\n user = ' '+user;\n }\n }\n\n field.value = field.value + user;\n\t}\n return true;\n}", "function addContact(event) {\n event.preventDefault()\n let form = event.target\n let cb = document.getElementsByTagName(\"emergencyContact\")\n console.log(form.name.value)\n console.log(form.phone.value)\n contact = {\n id: generateId(),\n name: form.name.value.toString(),\n phone: form.phone.value,\n emergencyContact: form.emergencyContact.checked\n }\n console.log(contact)\n contacts.push(contact)\n saveContacts()\n form.reset()\n}", "createContact(contact) {\n ContactsAPI.create(contact).then(contact => {\n this.setState(state => ({\n // add a new contact in the state\n contacts: state.contacts.concat([ contact ])\n }))\n })\n }", "function addEntry(name,number){\r\n\treadFile((res)=>{\r\n\t\tvar contactList = JSON.parse(res);\r\n\t\tvar contact = {\"name\":name,\"number\":number};\r\n\t\tcontactList.push(contact);\r\n\t\twriteFile(contactList);\r\n\t});\r\n\r\n}", "addContact () {\n store.addContact(this.store.newContact)\n this.store.newContact = { name: '', email: '' }\n }", "function appendContent(labelEmail, textEmail, labelName, textName, labelPass,\n textPass, edit, content){\n content.appendChild(labelEmail);\n content.appendChild(textEmail);\n content.appendChild(labelName);\n content.appendChild(textName);\n content.appendChild(labelPass);\n content.appendChild(textPass);\n content.appendChild(edit);\n return content\n}", "function AddContacts(contacts, lists, columnNames) {\n\tComponent.call(this);\n\n\tthis.lists = lists;\n\n\tif (!_.isEmpty(contacts)) {\n\t\tif (contacts[0] instanceof AddContactsImportData) {\n\t\t\tthis.import_data = contacts;\n\t\t} else {\n\t\t\tvar msg = sprintf(Config.errors.id_or_object, 'AddContactsImportData');\n\t\t\t// @todo: IllegalArgumentException\n\t\t\tthrow new Error(msg);\n\t\t}\n\t}\n\n\tif (_.isEmpty(columnNames)) {\n\t\tvar usedColumns = [Config.activities_columns.email];\n\t\tvar contact = contacts[0];\n\n\t\t['first_name',\n\t\t'middle_name',\n\t\t'last_name',\n\t\t'job_title',\n\t\t'company_name',\n\t\t'work_phone',\n\t\t'home_phone'].forEach(function(column) {\n\t\t\tif (contact[column]) {\n\t\t\t\tusedColumns.push(Config.activities_columns[column]);\n\t\t\t}\n\t\t});\n\n\t\t// Addresses\n\t\tif (!_.isEmpty(contact.addresses)) {\n\t\t\tvar address = contact.addresses[0];\n\n\t\t\t_.forEach({\n\t\t\t\tline1: 'address1',\n\t\t\t\tline2: 'address2',\n\t\t\t\tline3: 'address3',\n\t\t\t\tcity: 'city',\n\t\t\t\tstate_code: 'state',\n\t\t\t\tstate_province: 'state_province',\n\t\t\t\tcountry: 'country',\n\t\t\t\tpostal_code: 'postal_code',\n\t\t\t\tsub_postal_code: 'sub_postal_code'\n\t\t\t}, function(val, key) {\n\t\t\t\tif (address[key]) {\n\t\t\t\t\tusedColumns.push(Config.activities_columns[val]);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\t// Custom Fields\n\t\tif (!_.isEmpty(contact.custom_fields)) {\n\t\t\tcontact.custom_fields.forEach(function(customField) {\n\t\t\t\tif (customField.name.indexOf('custom_field_') !== -1) {\n\t\t\t\t\tvar customFieldNumber = customField.name.substr(13);\n\t\t\t\t\tusedColumns.push(Config.activities_columns['custom_field_' + customFieldNumber]);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tthis.column_names = usedColumns;\n\t}\n}", "addRecipients(){\n\t\tconst personalize = new helper.Personalization();\n\n\t\tthis.recipients.forEach(recipient => {\n\t\t\tpersonalize.addTo(recipient);\n\t\t});\n\n\t\tthis.addPersonalization(personalize);\n\t}", "function addMessages(messages) {\n for (let m of messages) {\n let displayPerson = m.messageSender\n \n for (let c of contactList) {\n if (m.messageSender === c.phoneNum) {\n displayPerson = c.name;\n }\n }\n \n if (typeof m.messageContent != \"string\") {\n console.log(\"invalid message\");\n }\n displayHtml += '<span id=\"message\" style=\"bottom:' + m.displayNumber + '%;\">' +\n displayPerson + ': ' + m.messageContent + '</span>';\n }\n \n document.getElementById(\"message-display\").innerHTML = displayHtml;\n}", "createContact() {\r\n //create the contact body and add \"contact\" to the class list\r\n let contactBody = document.createElement(\"li\");\r\n contactBody.classList = \"contact\";\r\n //set a data- to counter number\r\n contactBody.setAttribute(\"data-contactNumber\", Contact.counter);\r\n Contact.counter++;\r\n //complete the contact body\r\n contactBody.innerHTML = `\r\n <div class=\"justify-item-center info\">\r\n <div class=\"profile\">${this.name[0].toUpperCase()}</div>\r\n <div class=\"name\">${this.name}</div>\r\n </div>\r\n <p class=\"description-text\">${this.description}</p>`;\r\n //append the contact body to contacts list\r\n document.querySelector(\".contacts-list\").appendChild(contactBody);\r\n //add an event listener to contact body\r\n contactBody.addEventListener(\"click\", this.getContactInfo);\r\n }", "addRecipients() {\n\t\tconst personalize = new helper.Personalization();\n\t\tthis.recipients.forEach(recipient => {\n\t\t\tpersonalize.addTo(recipient);\n\t\t});\n\t\tthis.addPersonalization(personalize);\n\t}", "function pago_rapido(){ change_to('contact_find_add'); }", "function hanldeClickAdd(ev) {\n if( ev.name !== '' && ev.email !=='') {\n console.log('click');\n contacts.push({\n id:newid,\n name: ev.name,\n email: ev.email,\n company: {\n catchPhrase: ev.catchPhrase,\n }\n });\n setContacts(contacts);\n setNewid(newid-1)\n }\n }", "function addTodo(text) {\n todoList.push(text);\n displayTodos();\n\n}", "function Contacts() {\n\t\n}", "function addDetails(contact) {\n get(contact._id)\n .then(function(response) {\n extendContact(contact, response);\n });\n }", "function setupAddContact(){\n\n var ul = document.getElementById(\"contactList\");\n\n //Create li element\n var li = document.createElement(\"li\");\n li.className = 'addContact';\n\n //Create, set, and add image element\n var imageElement = document.createElement(\"img\");\n imageElement.setAttribute(\"src\", \"img/add.png\");\n imageElement.className = 'addIcon';\n\n li.appendChild(imageElement);\n li.appendChild(document.createTextNode(\"Add contact\"));\n li.addEventListener('click', function() {\n addContact()\n });\n\n ul.appendChild(li);\n\n}", "function addAnnouncements() {\r\n anmtTitle = document.getElementById(\"titleAnmt\").value;\r\n anmtDescr = document.getElementById(\"descrAnmt\").value;\r\n var ul = document.getElementById(\"fullAnnouncements\");\r\n var li = document.createElement(\"li\");\r\n li.appendChild(document.createTextNode(anmtTitle + \" : \" + anmtDescr))\r\n ul.appendChild(li);\r\n}", "function awAddRecipients(msgCompFields, recipientType, recipientsList) {\n if (!msgCompFields || !recipientsList) {\n return;\n }\n\n addressRowAddRecipientsArray(\n document.querySelector(\n `.address-row[data-recipienttype=\"${recipientType}\"]`\n ),\n msgCompFields.splitRecipients(recipientsList, false)\n );\n}", "function insertNewCRInList(name, body) {\n var li = document.createElement(\"LI\"),\n spanName = document.createElement(\"SPAN\"),\n spanDel = document.createElement(\"SPAN\");\n\n spanName.textContent = name;\n spanName.classList.add(\"name\");\n spanDel.classList.add(\"fa\", \"fa-trash\");\n\n li.appendChild(spanName);\n li.appendChild(spanDel);\n CRListElm.appendChild(li);\n }", "function addNewContact(e) {\n if(form.firstname.value == '' || form.lastname.value == '' || form.phone.value == '' || form.email.value == '') {\n var removeNotice = showNotice('You have an empty form field', 'yellow', 'black');\n setTimeout(removeNotice, 3300);\n e.preventDefault();\n return;\n }\n\n // generate a unique id to identify a particular contact by\n var id = new Date().getTime();\n\n // create new contact\n var contact = {\n firstname : form.firstname.value,\n lastname : form.lastname.value,\n phone : form.phone.value,\n email : form.email.value,\n id : id\n }\n\n // capitalize name initials (a little sanitation)\n contact.firstname = contact.firstname[0].toUpperCase() + contact.firstname.slice(1).toLowerCase();\n contact.lastname = contact.lastname[0].toUpperCase() + contact.lastname.slice(1).toLowerCase();\n\n // add contact to DOM\n displayContact(contact);\n\n // add contact to local storage\n var contacts = getStoredContacts();\n contacts.push(contact);\n localStorage.contacts = JSON.stringify(contacts);\n\n // signal that contact has been added\n var removeNotice = showNotice('Contact has been added!', 'blue', 'black');\n setTimeout(removeNotice, 3300);\n\n displaySortButton();\n e.preventDefault();\n}", "function addNote(){\n var noteText = document.getElementById(\"note_text\").value;\n noteList.addNote(noteText);\n displayNotes();\n }", "add() {\n let name = document.getElementById(\"form_name\").value;\n let email = document.getElementById(\"form_email\").value;\n let phone = document.getElementById(\"form_phone\").value;\n let relation = document.getElementById(\"form_relation\").value;\n\n //the if statement condition requires that the user enter a name and an email or phone at minimum. \n if(name !== \"\" && (email !== \"\" || phone !== \"\")){\n const info = {\n name: name,\n email: email,\n phone: phone,\n relation: relation\n }\n\n //create a new instance of new contact and upsh into contacts array\n const newContact = new Contact(info.name, info.email, info.phone, info.relation);\n myAddressBook.contacts.push(newContact);\n \n // reset input values\n myAddressBook.clearInputs();\n \n this.counter++;\n\n //display all the contacts on the page\n myAddressBook.display();\n\n } else { //let them know they didn't enter enough info\n alert(\"Please enter a new contact name and at least 1 method of contact info.\")\n }\n }", "createContact(name, email, number) {\n const {contacts} = this.state\n contacts.unshift({'id': uuid.v4(), name: name, email: email, number: number});\n this.setState({\n contacts\n }, () => updateLocalStorage(\"contacts\", contacts))\n }", "function addStaff(uid, msg){\n\tvar item = null;\n\n\tfunction findStaff(r) {\n\t\t//console.log(\"findStaff \"+reqdname);\n\t\treturn r == uid;\n\t}\n\t\n\tif (!checkStaffSender(msg, AdminListFile)){\n\t\tconsole.log(\"Not an admin member :\");\n\t\t\n\t\tmsg.author.send(`You do not have permission to use !verify-addstaff`)\n\t\t\t.catch(console.error);\n\t} else {\n\t//only nns allowed to do this\n\t//if (msg.author.id == '689153168520642744'){\n\t\n\t\t//add the member to the staff list file\n\t\tstaff = findStaffList(StaffListFile);\n\t\titem = staff.aberuid.find(findStaff);\n\t\t\n\t\tif (item) {\n\t\t\tmsg.author.send(`Aber user ${uid} is already a Verify bot Admin`)\n\t\t\t.catch(console.error);\n\t\t} else {\n\t\t\tstafflist.aberuid.push(uid);\n\t\t\tmsg.author.send(`Added ${uid} as a new staff member`)\n\t\t\t.catch(console.error);\n\t\t}\n\t\t\n\t\tlet data = JSON.stringify(stafflist, null, 2); //null, 2 for formating\n\t\tfs.writeFileSync(StaffListFile, data);\n\t}\n}", "function createContact(name,phoneNumber){\n\n}", "function handleCreateContact() {\n const jwt = localStorage.getItem(\"token\");\n const payload = {\n name: `${name}`,\n email: `${email}`,\n };\n axios\n .post(`${defaults.serverUrl}/account/contact`, payload, {\n headers: {\n \"x-auth-token\": jwt,\n },\n })\n .then((res) => {\n const cloneContacts = JSON.parse(JSON.stringify(contacts));\n cloneContacts.push(res.data);\n setContacts(cloneContacts);\n })\n .catch((err) => {\n console.error(err);\n })\n .finally(() => {\n // clear the input boxes\n setName(\"\");\n setEmail(\"\");\n });\n }", "function appendToLists(contact) {\n updatePhoto(contact);\n var ph = createPlaceholder(contact);\n var groups = [ph.dataset.group];\n if (isFavorite(contact)) {\n groups.push('favorites');\n }\n\n var nodes = [];\n\n for (var i = 0, n = groups.length; i < n; ++i) {\n ph = appendToList(contact, groups[i], ph);\n nodes.push(ph);\n ph = null;\n }\n\n selectedContacts[contact.id] = selectAllPending;\n\n return nodes;\n }", "function addContact() {\r\n var contactName = $('#addContact').val();\r\n // create a new contact object\r\n var contact = navigator.contacts.create();\r\n contact.displayName = contactName;\r\n contact.nickname = contactName; \r\n // save to device\r\n contact.save(addSuccess,contactFail);\r\n}", "updateContact (state, payload) {\n let contact = getContactByJid(state, payload.jid)\n if (contact) {\n Object.assign(contact, payload)\n } else {\n contact = new Contact(payload)\n // 存在系统消息模块,默认插到系统消息后\n state.contacts.splice(1, 0, contact)\n // 先更新列表再补充联系人与业务相关消息,避免列表延时显示\n state.uiCore.queryAddressBook(getIdFromJid(contact.jid), (user) => {\n for (let p in user) {\n if (contact.hasOwnProperty(p)) { contact[p] = user[p] }\n }\n })\n }\n }", "function saveContactInfo(name, email, message){\n let newContactInfo = contact.push();\n\n newContactInfo.set({\n Name : name,\n Email: email,\n Message: message,\n })\n }", "function addNewTodoItem(start, stop, content) {\n if (start !== \"\" && stop !== \"\" && content !== \"\") {\n let todo = new Todo(content, start, stop);\n let newTodos = [...todos];\n newTodos.push(todo);\n setTodos(newTodos);\n setSelectedRow(\"\");\n }\n }", "function addItemFromSuggestion(e, item) {\n var c = e.data;\n //console.log('adding activityinfo array added people name ' + item.name);\n ArrayUtil.removeFromArrayCmp(item, c.that.removedPeople, cmpPIds);\n if (!ArrayUtil.isInCmp(item, c.that.addedPeople, cmpPIds))\n c.that.addedPeople.push(item);\n c.that.existingPeople.removeItemFromSuggestions(item);\n c.that.save();\n c.that.existingPeople.resetBloodhound();\n c.that.makeLinkWithSuggestions();\n}", "function Contact() { //define Contact\n Person.call(this);\n this.added = false;\n //this.dropped = false; //in person\n contactArray.push(this);\n // add to gig\n }", "function addContact(event) {\n event.preventDefault();\n let results = event.target\n\n let newContact = {\n id: generateId(),\n name: results.name.value,\n phone: results.phone.value,\n ec: results.eContact.checked,\n // If emergency contact is checked, set color to empty string\n color: results.eContact.checked ? '' : results.color.value\n }\n\n document.getElementById(\"color-div\").classList.remove(\"hidden\")\n\n contacts.push(newContact)\n console.log(newContact)\n saveContacts()\n results.reset()\n submitClick()\n}", "function saveContactInfo (name,email,subject,message) {\n \n let newContactInfo = contactInfo.push();\n\n newContactInfo.set({\n name: name,\n email: email,\n subject: subject,\n message: message\n });\n }", "function addContact() {\n let newContact = createContatct()\n let alreadyExists = addressBook.filter(contact => contact.firstName == newContact.firstName).length\n if (alreadyExists) {\n console.log(\"Conatct already exists\");\n } else {\n addressBook.push(newContact)\n console.log(\"Added sucessfully\");\n }\n\n}", "function appendToList(contact, group, ph) {\n ph = ph || createPlaceholder(contact, group);\n var list = getGroupList(group);\n\n // If above the fold for list, render immediately\n if (list.children.length < getRowsPerPage()) {\n renderContact(contact, ph);\n }\n\n if (!loadedContacts[contact.id]) {\n loadedContacts[contact.id] = {};\n }\n\n loadedContacts[contact.id][group] = contact;\n\n list.appendChild(ph);\n if (list.children.length === 1) {\n showGroupByList(list);\n setRowsPerPage(list.firstChild);\n }\n\n return ph;\n }", "function sendMessage(name,lastName, email, message) {\n let newFormMessage = db.collection('contact').add({\n \n first_name: name,\n last_name: lastName,\n email: email, \n message: message\n });\n }", "async function addObjectsToList(list) {\r\n let customer =\r\n {\r\n ContactName: \"David Johnes\",\r\n CompanyName: \"Lonesome Pine Restaurant\",\r\n ContactNo: \"(1) 354-9768\",\r\n Address: \"Silicon Valley, Santa Clara, California\",\r\n };\r\n await list.add(customer);\r\n await list.add(customer =\r\n {\r\n ContactName: \"Carlos Gonzalez\",\r\n CompanyName: \"LILA-Supermercado\",\r\n ContactNo: \"(9) 331-6954\",\r\n Address: \"Carrera 52 con Ave. Bolivar #65-98 Llano Largo\",\r\n });\r\n await list.add(customer =\r\n {\r\n ContactName: \"Carlos Hernandez\",\r\n CompanyName: \"HILARION-Abastos\",\r\n ContactNo: \"(5) 555-1340\",\r\n Address: \"Carrera 22 con Ave. Carlos Soublette #8-35\",\r\n });\r\n await list.add(customer =\r\n {\r\n ContactName: \"Elizabeth Brown\",\r\n CompanyName: \"Consolidated Holdings\",\r\n ContactNo: \"(171) 555-2282\",\r\n Address: \"Berkeley Gardens 12 Brewery\",\r\n });\r\n await list.add(customer =\r\n {\r\n ContactName: \"Felipe Izquierdo\",\r\n CompanyName: \"LINO-Delicateses\",\r\n ContactNo: \"(8) 34-56-12\",\r\n Address: \"Ave. 5 de Mayo Porlamar\",\r\n });\r\n\r\n // Print output on console.\r\n console.log(\"\\nObjects are added to distributed list.\");\r\n return list;\r\n}", "function addContactInfo() {\n if (_.isEmpty($scope.contactInfo)) {\n $scope.contactInfoCssClass = 'state-filling';\n }\n\n $scope.contactInfo.push({type: ContactInfoTypeEnum.PHONE, value: ''});\n }", "function createContact(name, phone, address) {\n return `<p>${name} can be reached at ${phone} and lives at ${address}</p>`\n}", "function addContacDate (name, phone){\n // contador\n count++;\n // variable para guardar\n var finalTemplate = \"\";\n // remplazo\n finalTemplate = template.replace(\"__name__\", name).replace(\"__phone__\", phone);\n // los digo donde va aparecer\n $('main').append(finalTemplate);\n // para el contador, que sube en el h5\n $('h5').html('Total contactos:' + count);\n // para dar mensaje de listo\n swal(\"Yei!\", \"contacto agregado!\", \"success\");\n}", "function newContact(name, number) {\n dispatch(\n contactsOperations.ADD({\n name: name,\n number: number,\n })\n );\n\n setName('');\n setNumber('');\n }", "function updateContactList() {\r\n\tsupervisorsStore.load( {params: { method: \"loadSupervisors\"} } );\r\n\texpertsStore.load( {params: { method: \"loadExperts\"} } );\r\n\tpeersStore.load( {params: { method: \"loadPeers\"} } );\r\n agentsStore.load( {params: { method: \"loadFavorites\"} } );\r\n}", "handleNewContact(contact) {\n addContact(contact);\n this.closeModal();\n }", "addAddress(id, address) {\n if (address.length > 0) {\n if (id === 'to') {\n const to2 = [...this.state.to2];\n to2.push(address);\n const to = to2.join(',');\n this.setState({to2, to});\n // this.props.setMailContacts(to);\n\n }\n }\n }", "function addTeamMembers() {\n inquirer\n .prompt([\n {\n type: 'list',\n name: 'addMembers',\n message: 'What would you like to do?',\n choices: [\n 'Add an Engineer',\n 'Add an Intern',\n \"I'm all done. Let's see my team!\",\n ],\n },\n ])\n .then(answers => {\n switch (answers.addMembers) {\n case 'Add an Engineer': {\n promptEngineer();\n break;\n }\n case 'Add an Intern': {\n promptIntern();\n break;\n }\n case \"I'm all done. Let's see my team!\": {\n buildTeam();\n break;\n }\n }\n });\n }", "function addNewNote(title , content) {\n setTodoList(prev => {\n var newItem = {\n title : title,\n content: content\n }\n return[...prev, newItem]\n })\n \n }", "function addTodo(text) {\n //define todo entry object structure.\n const todo = {\n text,\n checked: false,\n id: Date.now(),\n };\n //add new todo entry to the array collection\n todoItems.push(todo);\n //trigger page update by invoking renderTodo function\n renderTodo(todo);\n}", "function AddMSNContact(name)\n{\n\tif (!is_ie)\n\t{\n\t\talert(vbphrase['msn_functions_only_work_in_ie']);\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\tMsgrObj.AddContact(0, name);\n\t\treturn false;\n\t}\n}", "function addTodos(todo) {\n todos.push(todo)\n displayTodos()\n}", "function updateContact() {\n var contacts = getStoredContacts();\n var idEdited = JSON.parse(localStorage.idEdited);\n\n contacts.forEach(function (contact) {\n if(idEdited == contact.id) { // capitalize name initials (a little sanitation)\n contact.firstname = form.firstname.value[0].toUpperCase() + form.firstname.value.slice(1).toLowerCase(),\n contact.lastname = form.lastname.value[0].toUpperCase() + form.lastname.value.slice(1).toLowerCase(),\n contact.phone = form.phone.value,\n contact.address = form.address.value,\n contact.email = form.email.value\n }\n });\n\n // add contact to local storage\n localStorage.contacts = JSON.stringify(contacts);\n localStorage.idEdited = JSON.stringify('updated');\n}", "function addannouncement() {\n\n}", "function add(todoText) {\n let obj = { todo: todoText };\n database.push(obj);\n}", "function addMessage(author, content) {\n const message = document.createElement('li');\n message.classList.add('message');\n message.classList.add('message--received');\n if (author === userName) message.classList.add('message--self');\n message.innerHTML = `\n <h3 class=\"message__author\">${userName === author ? 'You' : author}</h3>\n <div class=\"message__content\">\n ${content}\n </div>\n `;\n messagesList.appendChild(message);\n}", "function addTodo(text) {\n const todoTask = {\n id: Date.now(),\n text,\n ticked: false,\n };\n\n todoListArray.push(todoTask);\n\n // Let's show the added todoList\n showTodoList(todoTask);\n}", "contactList() {\n\t if (Session.get(\"searchName\") != \"\") {\n\t\tvar searchString = Session.get(\"searchName\");\n\t\treturn Template.contacts.__helpers[\" findContact\"](searchString);\n\t }\n\t else\n\t\treturn Contacts.findOne(\"Contacts\")[\"contacts\"];\n\t}", "add() {\n if (isValid(this.name) === false) {\n this.displayError(\"Error... Incorrect format\");\n this.utility.setSuccess(FieldList.NON_AUTHOR, false);\n this.utility.setFlow(FieldList.ABSTRACT, false);\n } else { \n var tmpname = \"\" + formatName(this.name)\n\n if (this.set.contains(tmpname) === true) {\n this.displayError(\"Error... Duplicate author\");\n this.utility.setSuccess(FieldList.NON_AUTHOR, false);\n this.utility.setFlow(FieldList.ABSTRACT, false);\n }else {\n this.displayError(\"\");\n this.finalAuthors.push(tmpname);\n this.set.add(tmpname);\n\n this.authors = this.authors + tmpname + \";\"\n this.utility.setSuccess(FieldList.NON_AUTHOR, true);\n this.utility.setFlow(FieldList.ABSTRACT, true);\n }\n }\n }", "function addTodo(text) {\n //Define todo entry object structure\n const todo = {\n text,\n checked: false,\n id: Date.now(),\n };\n //Add new todo entry to the array collection\n todoItems.push(todo);\n //Trigger page update by (invoking) calling the renderTodo function\n renderTodo(todo);\n}", "function addContact (userId, co, callback) {\n\tdebug(\"add contact co: \", JSON.stringify(co));\n User.findById(userId, function (err, user) {\n if (err) {\n log.error('Find user in add contact error: ' + err.message);\n message.e = 'Can\\'t find user';\n return callback(message);\n }\n var message = {};\n var contact = {};\n if (co.hasOwnProperty('nm')) {\n contact.name = co.nm;\n }\n if (co.hasOwnProperty('ph')) {\n contact.phone = co.ph;\n }\n if (co.hasOwnProperty('em')) {\n contact.email = co.em;\n }\n if (co.hasOwnProperty('nf')) {\n var frequencies = nconf.get('notifier:frequencies');\n var frequency = _.find(frequencies, { 'id': parseInt(co.nf, 10) });\n contact.notificationFrequency = frequency.value;\n }\n debug(' contact: ' + JSON.stringify(contact));\n user.contacts.push(contact);\n user.save(function (err) {\n if (err) {\n message.e = \"Can't save contact\";\n }\n callback(message);\n });\n });\n}", "function addTodos(todo) {\n todos.push(todo);\n displayTodos();\n}", "function addToDo(toDo, id, done, trash) {\n if(trash) {return; }\n // const DONE = done ? CHECK : UNCHECK;\n const LINE = done ? LINE_THROUGH : \"\";\n const item = `\n <li class=\"item\">\n <p class=\"text ${LINE}\">${toDo}</p>\n </li> \n `;\n const position = \"beforeend\";\n list.insertAdjacentHTML(position, item);\n}", "function addContent() {\n\tvar newText = \n\t\t\"<div class='addedContent'><span class='addedName'>\" \n\t\t+ firstName + \" \" \n\t\t+ lastName \n\t\t+ \"</span> &ndash; \" \n\t\t+ city + \" &ndash; \" \n\t\t+ school + \" \" \n\t\t+ \" &ndash; <a href='\"\n\t\t+ \"#\"\n\t\t// + \"'\" + website + \"' target='new'\"\n\t\t+ \"'>\" \n\t\t+ website \n\t\t+ \"</a></div>\";\n\t$(\"#container2\").prepend(newText);\n}", "function addEmptyContactInfo(contactInfos) {\n contactInfos.push({ isNew: true, language: $scope.language.id, id: 0 });\n }", "function Add_Comments()\n{\n\tDeleteFlag = false;\n\tvar lines = SeparateTextArea(Comments.commentsWindow.document.myComments.comments.value,60)\n\n\tvar object = new AGSObject(authUser.prodline,\"ES01.1\");\n\t\tobject.event \t= \"ADD\";\n\t\tobject.rtn \t= \"MESSAGE\";\n\t\tobject.longNames = true;\n\t\tobject.lfn\t= \"ALL\";\n\t\tobject.tds \t= false;\n\t\tobject.field \t= \"FC=A\"\n\t\t\t\t+ \"&ECM-COMPANY=\"+parseFloat(authUser.company)\n\t\t\t\t+ \"&ECM-EMPLOYEE=\"+parseFloat(Comments.Employee)\n\t\t\t\t+ \"&ECM-CMT-TYPE=TR\"\n\t\t\t\t+ \"&ECM-DATE=\"+Comments.Date\n\n\tfor(var i=0,j=1;i<lines.length;i++,j++)\n\t{\n\t\tif(i<lines.length)\n\t\t\tlines[i] = unescape(DeleteIllegalCharacters(escape(lines[i])))\n\n\t\tobject.field += \"&LINE-FC\"+j+\"=A\"\n\t\t\t// PT 127924\n\t\t\t// + \"&ECM-SEQ-NBR\"+j+\"=\"\t+ j\n\t\t\t+ \"&ECM-CMT-TEXT\"+j+\"=\"\t+ escape(lines[i])\n\t}\n\t\n\tobject.dtlField = \"LINE-FC;ECM-CMT-TEXT\";\n\tobject.debug = false;\n\tobject.func = \"parent.RecordsAdded_Comments()\"\n\tAGS(object,\"jsreturn\")\n}", "function greetDevelopers(list) {\n // thank you for checking out my kata :)\n for(var i in list){\n\tlist[i].greeting = \"Hi \" + list[i].firstName + \", what do you like the most about \" \n\t\t\t\t\t\t+ list[i].language + \"?\";\n\n };\n \n return list;\n \n}", "function populateTable(contactlist){\n for( let i=0;i<contactlist.length; i++){\n const contact = (contactlist[i]);\n const name = contact.fname + \" \" +contact.lname;\n const contactId = contact._id;\n addRow(table, name, contactId, i);\n }\n}", "function addEmail(url = gContextMenu.linkURL) {\n var addresses = getEmail(url);\n window.openDialog(\n \"chrome://messenger/content/addressbook/abNewCardDialog.xhtml\",\n \"\",\n \"chrome,resizable=no,titlebar,modal,centerscreen\",\n { primaryEmail: addresses }\n );\n}", "function addEntry() {\n var name = document.getElementById(\"add_name\").value;\n var tel = document.getElementById(\"add_tel\").value;\n var email = document.getElementById(\"add_email\").value;\n \n if (!isInputError(name, tel, email)) {\n contacts.push(new Entry(name, tel, email));\n // reset field values and hide add panel\n document.getElementById(\"add_name\").value = \"\";\n document.getElementById(\"add_tel\").value = \"\";\n document.getElementById(\"add_email\").value = \"\";\n hide(\"addentry\");\n // refresh contact list\n displayEntries();\n }\n}" ]
[ "0.67208964", "0.65374756", "0.64308107", "0.6419675", "0.62732035", "0.6248838", "0.61312896", "0.6107906", "0.6101962", "0.60928035", "0.608859", "0.6036398", "0.60298723", "0.60163015", "0.600878", "0.59914905", "0.594995", "0.591299", "0.58910793", "0.5880461", "0.5874919", "0.5870883", "0.58565205", "0.58325934", "0.5824057", "0.5777124", "0.5776107", "0.57124925", "0.56856763", "0.5673386", "0.5670156", "0.5665468", "0.5664541", "0.5660711", "0.5649801", "0.5640657", "0.56231475", "0.5591935", "0.5580372", "0.55732256", "0.5559153", "0.554387", "0.5542076", "0.5534514", "0.55246425", "0.5521687", "0.55067044", "0.54942906", "0.5492569", "0.54886425", "0.54722804", "0.5471761", "0.54601395", "0.5451302", "0.5437092", "0.5430167", "0.5423188", "0.5420207", "0.54116106", "0.5400379", "0.5386502", "0.5384393", "0.5362957", "0.53567296", "0.5354236", "0.5354219", "0.5338588", "0.53364724", "0.5332848", "0.5329599", "0.53157145", "0.5301101", "0.5290937", "0.52767473", "0.5259515", "0.5259391", "0.52532494", "0.5245495", "0.5240483", "0.5238613", "0.52286345", "0.522711", "0.5225443", "0.52235806", "0.521733", "0.5217061", "0.5213509", "0.5210997", "0.52087355", "0.5206638", "0.520328", "0.5202106", "0.52011", "0.52005005", "0.5192731", "0.5188292", "0.5180505", "0.5177761", "0.5177133", "0.5166985", "0.5164062" ]
0.0
-1
DELETES A CONTACT FROM THE CONTACT LIST (BASED ON ALIAS)
function deleteContact() { var alias = $('#deleteAlias').val(); //store the alias provided by user $.ajax({ url: uri + '/' + alias, type: 'DELETE', success: function(result) { //done $('#deleteContact').text('Contact [ ' + alias + ' ] has been deleted from list.'); } }) .fail(function () { $('#deleteContact').text("Invalid alias. Check the alias and try again."); }) $('#refresh2').show(); //refresh the page to show the updated contact list //console.log("deleted successfully"); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function deleteContact(){\n var id = readLineSync.question(\"Lua chon id contact can xoa: \");\n listContact.splice(id,1);\n save();\n console.log(\"\\nXoa thanh cong nhe!\")\n\n}", "function deleteContact() {\n app.f7.actions([[{\n text: 'Delete Contact',\n red: true,\n onClick: function() {\n var contacts = Persistence.getAllContacts();\n _.remove(contacts, { _id: contact._id });\n Persistence.setAllContacts(contacts);\n app.router.load('list'); // reRender main page view\n app.mainView.goBack(\"../index.html\", false);\n app.f7.closeModal();\n }\n }],\n [{\n text: 'Cancel',\n bold: true\n }]]);\n }", "function removeContact() {\n let contactId = getSelectedContactId()\n client.contacts.remove(contactId)\n}", "deleteByName(name) {\n for (let index in this.contacts) {\n if (this.contacts[index].name.toLowerCase() === name.trim().toLowerCase()) {\n this.contacts.splice(index, 1);\n break;\n }\n }\n }", "function deleteEntry(name){\r\n\treadFile((res)=>{\r\n\t\tvar writelist = [];\r\n\t\tvar contactList = JSON.parse(res);\r\n\t\tcontactList.forEach((item,index)=>{\r\n\t\t\tif(item.name.toUpperCase()!==name.toUpperCase()) writelist.push(item);\r\n\t\t})\r\n\t\twriteFile(writelist);\r\n\t})\r\n}", "function deletecontact(index) {\n contacts.splice(index, 1);\n}", "remove(contact) {\n // Filter out any items that have the same _id as the 'contact'\n this.data = this.data.filter((item) => {\n return item._id !== contact._id;\n });\n\n this.render();\n }", "removeFromList(name) {\n console.log(\"Requested to remove word \" + name);\n let success = this.list.delete(name);\n console.log(\"Remove \" + name + \" success: \" + success);\n }", "function deleteContact(req, res, next) {\n List\n .findById(req.params.list_id)\n .populate('services')\n .exec(function (err, list) {\n if (err) {\n res.send(404, new Error('List not found'));\n return next(false);\n }\n\n var index = list.contacts.indexOf(req.params.contact_id);\n if (index == -1) {\n res.send(404, new Error('Contact not found'));\n return next(false);\n }\n else {\n list.contacts.splice(index, 1);\n list.save(function (err) {\n if (err) {\n res.send(500, new Error('Unknown error saving list'));\n return next(false);\n }\n // Unsubscribe contact from services\n if (list.services.length) {\n Contact\n .findById(req.params.contact_id)\n .populate('_profile')\n .exec(function (err, contact) {\n if (!err && contact) {\n list.services.forEach(function (service) {\n if (service.auto_remove) {\n service.unsubscribe(contact._profile);\n }\n });\n }\n });\n }\n res.send(204);\n return next();\n });\n }\n });\n}", "function deleteContact() {\n let index = 0;\n let lengthAddresses = ADDRESSES.length;\n\n for (i=0; i<lengthAddresses; i++) {\n if (ADDRESSES[index].checked) {\n ADDRESSES.splice(index,1);\n }\n else {\n index++;\n }\n }\n if (allchecked) {\n allchecked = false;\n }\n displayTbl(ADDRESSES);\n}", "function eliminarContacto(nombreEliminar){\n\tarrayContactos.forEach((elemento,index)=>{\n\t\tif(elemento.nombre==nombreEliminar){\n\t\t\tarrayContactos.splice(index,1);\n\t\t}\n\t});\n\tguardarDatosLocales();\n}", "function onRemoveContactFromAddressBook(contact){\n try {\n var result = thisPresenter.removeContact(contact);\n if(result) alert(\"Contatto [\" + mediator.createNameLabel(contact) + \"] rimosso\");\n } catch (err) {\n alert(err);\n }\n }", "function delete_contact_entreprise(){\n\t// Recuperation de l'id du contact\n\tvar id_contact = liste_infos_contacts.getCoupler().getLastInformation();\n\t\n\tif(id_contact != -1) {\n\t\tvar xhr = new XMLHttpRequest();\n\t\txhr.open(\"DELETE\", \"/personnes/delete/\"+id_contact, false);\n\t\txhr.send();\n\t\t\n\t\tsocket.emit(\"update\",{url: \"/entreprises/\"+newContactForm.getCoupler().getLastInformation()+\"/contacts\",func: getHandler(function(url){\n\t\t\tliste_cts.clear();\n\t\t\tvar datas = DatasBuffer.getRequest(url);\n\t\t\tfor(var i=0; i < datas.length; i++)\n\t\t\t\tliste_cts.addItem('<p class=\"nom_contact\">'+datas[i].prenom+\" \"+datas[i].nom+'</p><p class=\"statut_contact\">'+datas[i].statut+'</p>',datas[i]._id);\n\t\t\tliste_cts.update();\n\t\t})});\n\n\t\tliste_infos_contacts.clear();\n\t\tliste_infos_contacts.update();\n\t\tGraphicalPopup.hidePopup(popup_sup_contact_entreprise.getPopupIndex());\n\t}\n}", "function deleteContact(id) {\n var list = getElementById('contact-list');\n\n // delete from DOM\n var item = getElementById(id);\n list.removeChild(item);\n\n // delete form local storage\n var contacts = getStoredContacts();\n var index = 0; // this variable is to get the position of the paricular contact to be deleted from the array\n contacts.forEach(function(contact) {\n if( id == contact.id) {\n contacts.splice(index, 1);\n }\n index++;\n });\n\n // update local storage\n localStorage.contacts = JSON.stringify(contacts);\n\n // signal that contact has been deleted\n var removeNotice = showNotice('Contact has been deleted!', 'red', 'white');\n setTimeout(removeNotice, 3300);\n\n displaySortButton();\n}", "deleteContact(contactToDeleteId) {\n const {contacts} = this.state\n _.remove(contacts, contact => contact.id === contactToDeleteId);\n this.setState({\n contacts\n }, () => updateLocalStorage(\"contacts\", contacts))\n }", "function deleteContact(id) {\n contacts.splice(id, 1);\n $localStorage.contacts = contacts;\n }", "function deleteContact(user,contactId) {\n var userObject = {id:contactId.id}\n var contactindex = user.contacts.lastIndexOf(userObject);\n if(contactindex){\n user.contacts.splice(contactindex,1); \n }\n return user;\n}", "function deleteEntry(idx) {\n var c = confirm(\"Are you sure you want to delete this entry?\");\n if (c) {\n contacts.splice(idx, 1);\n displayEntries();\n }\n}", "delete(nombre) {\n \n const usuario = this.read(nombre);\n const index = this.contactos.findIndex( contacto => contacto.id === usuario.id );\n\n if (index >= 0) {\n this.contactos.splice(index, 1)\n }\n\n // localStorage.setItem('contactos', JSON.stringify(contactos))\n \n }", "function handleDelete1(indexToRemove) {\n let copyContacts = [...contacts]\n copyContacts.splice(indexToRemove, 1) // Remove the element at position indexToRemove\n setContacts(copyContacts)\n }", "function deleteContact() {\n let deleting = document.getElementsByClassName('deleteButton');\n for (let d = 0; d < deleting.length; d++) {\n let deleteItem = contacts[d];\n\n\n let deleteClick = deleting[d];\n\n deleteClick.onclick = function (f) {\n let index = this.parentNode.getAttribute('data-attr-item');\n let item = this.parentNode.parentNode;\n let updatedAddress = displayList[d].value;\n let contact = document.getElementsByClassName('contact');\n let contactValue = contact[d].value;\n\n let info = updatedAddress.split(\"|\");\n\n item.remove();\n\n name = contactValue;\n phoneNum = info[0];\n email_ = info[1];\n address_ = info[2];\n\n let savedAddress = JSON.parse(localStorage.getItem('addressBook'));\n savedAddress.splice(index, 1);\n\n localStorage.setItem(\"addressBook\", JSON.stringify(savedAddress));\n alert('Contact Successfully Deleted');\n\n }\n }\n }", "function deleteContact() {\n let userInput = prompt(\"Enter name to Delete Entry : \");\n addressBookArray.forEach(addressBook => {\n if(addressBook.firstName == userInput) {\n addressBookArray.splice(addressBookArray.indexOf(addressBook), 1)\n console.log(\"Record Deleted\");\n console.log(addressBookArray);\n }\n });\n}", "function removeContact(event) {\n let target = event.target;\n if (target.tagName.toLowerCase() === \"i\") { //if the icon is clicked\n target = target.parentNode; //set the target as the button anyway\n }\n addressBook.deleteAt(target.attributes[\"i\"].value);\n addressBook.display(); //redisplay the contact container\n}", "function deleteContact(id) {\n results.style.display = \"none\";\n ContactsController.Delete(id, onDeleteContact);\n}", "function onClickDeleteContact() {\n // va rajouter la propriété data-index ayant pour valeur l'index dans la balise a suivant celle ayant un id contact-details. Lie l'index du tableau de contacts (donc le contact que l'on veut) avec le lien cliquable sur le nom du contact\n //stocke ça dans variable index\n var index = $('#contact-details a').data('index');\n\n /*stock les données du localStorage dans la variable*/\n var addressBook = loadAddressBook();\n\n //fonction prédéfinie supprimant le premier élément de index (définit localement au-dessus) de addressBook(tableau des contacts). Car premier élément de index de adressbook est le tableau/objet contenant le contact\n addressBook.splice(index, 1);\n\n //l'enregistre sur l'adressBook non local, écrasant son contenu actuel\n saveAddressBook(addressBook);\n\n //cache les détails du contact\n $('#contact-details').hide();\n\n // relance la page pour faire disparaître le contact\n refreshAddressBook();\n\n}", "function deleteConatct() {\n let contactName = prompt(\"Enter name of contact which you want to delete: \")\n let isdelete = false\n for( var index = 0; index < addressBook.length; index++){ \n if ( addressBook[index].firstName == contactName) { \n addressBook.splice(index, 1); \n isdelete = true\n index--\n }\n }\n if (isdelete) {\n console.log(\"deleted sucessfully\");\n } else {\n console.log(\"contact not found\")\n }\n}", "remove(fruit) {\n const index = this.contactarray.indexOf(fruit);\n if (index >= 0) {\n this.contactarray.splice(index, 1);\n }\n }", "function deleteCustomer(deleteParameters) {\r\n // deleteParameters is an array. EG: ['Email','[email protected]','Mobile','086 123 4567','FirstNames','Bob']\r\n\r\n console.log('Delete - Customer:');\r\n deleteParameters.unshift('customers');\r\n deleteFromCollection(deleteParameters);\r\n\r\n} // END: function deleteCustomer()", "function deleteContactInfo(contactInfo, contactInfos) {\n zooInfoService.contactInfo.deleteContactInfo(contactInfo.id).then(\n function () {\n utilitiesService.utilities.alert('דרך יצירת הקשר נמחקה בהצלחה');\n\n // Remove the contact info from the contact infos array.\n contactInfos.splice(contactInfos.indexOf(contactInfo), 1);\n },\n function () {\n utilitiesService.utilities.alert('התרחשה שגיאה בעת מחיקת דרך יצירת הקשר');\n });\n }", "function deleteContact() {\n $.ajax({\n url: apiUrl+anime._id+\"/\",\n type: 'DELETE',\n success: function (data) {\n window.location.href = \"./index.html\";\n },\n error: function (request, status, error) {\n console.log(error, status, request);\n },\n complete: function(){return;}\n });\n return;\n }", "deleteMentor(mentorName) {\n let deletedMentor = mentors.filter(mentor => {\n return mentor.name !== mentorName;\n });\n console.log(deletedMentor);\n }", "deleteContactById(id) {\n let index = this.contacts.findIndex(contact => contact.id === id)\n let deleteObject = this.contacts[index]\n this.contacts = this.contacts.filter(contact => contact.id !== id)\n\n return deleteObject\n }", "function deleteContact(index) {\n vm.contacts.splice(index, 1);\n }", "function deleteGo(id, lastname) {\r\n if(confirm('Delete ' + lastname + ' (ID: ' + id + ')?')) {\r\n db.transaction(function(t) {\r\n t.executeSql('DELETE FROM Contacts WHERE id = ?', [id]);\r\n });\r\n resetContForm();\r\n dispResults();\r\n }\r\n}", "deleteById(subject) {\n var subject = input.split(`-`);\n \n let sqlParams = {\n $subject: subject[0],\n $category: subject[1]\n };\n let sqlRequest = \"DELETE FROM todo WHERE subject=$subject and category=$category\";\n \n return this.common.run(sqlRequest, sqlParams);\n }", "function deleteAuthor(id, firstName, lastName, fullName) {\n console.warn('Author deletion not yet supported');\n // selectedAuthor = {id, firstName, lastName, fullName};\n // $(\"#delete-author-modal\").modal();\n}", "function del(answer) {\n let number = parseInt(answer.substr(1));\n console.log(`Deleted ${lists[number]}\\n`);\n lists.splice(number, 1);\n return menu();\n}", "deleteNotes(idList) {\n let realm = new Realm({schema: [TaskSchema, SubTaskSchema, NotesSchema]});\n realm.write(() => {\n for (let i = 0; i < idList.length; i++) {\n const note = realm.objects('NOTES').filtered('id == $0', idList[i]);\n realm.delete(note);\n }\n });\n }", "async function deleteAllSelectedContacts() {\n let selectedContacts = checkSelectedContact();\n\n let fetchDeletedContacts = await fetch(`${APP_SERVER}/contacts`, {\n method: 'DELETE',\n headers: {\n \"Content-Type\": \"application/json\",\n \"Authorization\": `Bearer ${token}`\n },\n body: JSON.stringify(selectedContacts)\n });\n\n let deletedContacts = await fetchDeletedContacts.json();\n\n if (deletedContacts) {\n location.reload();\n }\n}", "function deleteContact(id) {\n var _iterator2 = _createForOfIteratorHelper(contacts),\n _step2;\n\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var contact = _step2.value;\n if (parseFloat(contact.id) === parseFloat(id)) contacts.splice(contacts.indexOf(contact), 1);\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n}", "function deleteCompany() {\n console.log(\"Delete company\");\n // return firestore.remove(`companies/${id}`);\n }", "function handleDelete(item){\n //console.log(item);\n const extra = [...deletedAdvertisements, item];\n setdeletedAdvertisements(extra);\n const temp = {...advertisements};\n delete temp[item];\n setAdvertisements(temp);\n // firebase.firestore()\n // .collection(KEYS.DATABASE.COLLECTIONS.ADVERTISEMENT)\n // .doc(\"list\")\n // .set(advertisements)\n }", "function deleteContact(contact_id){\n\t\t\t\t$(function(){\n\t\t\t\t\t\t$(\"#dialog\").dialog({\n\t\t\t\t\t\t resizable: false,\n\t\t\t\t\t\t\t\tmodal: true,\n\t\t\t\t\t\t\t\tshow: ('bounce'),\n\t\t\t\t\t\t\t\thide: ('explode'),\n\t\t\t\t\t\t\t\tbuttons: {\n\t\t\t\t\t\t\t\t\t\"yes\": function() {\n\t\t\t\t\t\t\t\t\t\t$(this).dialog(\"close\");\n\t\t\t\t\t\t\t\t\t\t\tvar wordObj = {\"contact_id\":contact_id};\n\t\t\t\t\t\t \t\t\t\t$.ajax({\n\t\t\t\t\t\t \t\t\ttype:\"POST\",\n\t\t\t\t\t\t \t\t\tdata: wordObj,\n\t\t\t\t\t\t \t\t\turl:\"deleteContact.php\",\n\t\t\t\t\t\t \t\t\tsuccess:function(data){ \n\t\t\t\t\t\t \t\t\t\t$(document.getElementById(contact_id)).remove();\n\t\t\t\t\t\t \t\t\t},\n\t\t\t\t\t\t \t\t \t\t\terror:function(data){}\n\t\t\t\t\t\t\t\t\t\t}); \n\t\t\t\t\t\t\t\t\t },\n\t\t\t\t\t\t\t\t\t\"no\": function() {\n\t\t\t\t\t\t\t\t\t\t$(this).dialog(\"close\");\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t});\n \t\t}", "removeAddress(id, address) {\n if (id === 'to') {\n const to2 = [...this.state.to2];\n to2.splice(to2.indexOf(address), 1);\n const to = to2.join(',');\n this.setState({to2, to});\n // this.props.setMailContacts(to);\n }\n }", "todo_delete(todo){\n todosRef.child(todo['.key']).remove();\n this.activity_add(\"Todo with text \" + todo.task + \" removed\");\n var index = this.todos.indexOf(todo);\n if(index > -1){\n this.todos.splice(index, 1);\n }\n }", "function delete_personne(){\n\t// Recuperation de l'id de la personne\n\tvar id_contact = liste_pers_contacts.getCoupler().getLastInformation();\n\t\n\tif(id_contact != -1) {\n\t\tvar xhr = new XMLHttpRequest();\n\t\txhr.open(\"DELETE\", \"/personnes/delete/\"+id_contact, false);\n\t\txhr.send();\n\t\t\n\t\tsocket.emit(\"update\",{url: \"/personnes\",func: getHandler(function(url){\n\t\t\tliste_contacts.clear();\n\t\t\tvar prs = DatasBuffer.getRequest(\"/personnes\");\n\t\t\tfor(var i=0;i<prs.length;i++)\n\t\t\t{\t\n\t\t\t\tliste_contacts.addItem('<p class=\"nom_contact\">'+prs[i].nom+'</p>',prs[i]._id);\n\t\t\t}\n\t\t\tliste_contacts.update();\n\t\t})});\n\n\t\tliste_pers_contacts.clear();\n\t\tliste_pers_contacts.update();\n\t\tGraphicalPopup.hidePopup(popup_sup_personne.getPopupIndex());\n\t}\n}", "function del(key, mvName) {\n var response = confirm(\"Remove \\\"\" + mvName + \"\\\" from the list?\");\n if (response == true) {\n var deleteListRef = buildEndPoint(key);\n deleteListRef.remove();\n }\n}", "removeContactMessage(contactid) {\n\n return axios.delete(API_URL + 'remove/?contactId=' + contactid, {\n headers: authenticationHeader()\n });\n\n }", "function clearDeleted() {\n for (let i = 0; i < allNotes.length; i++) {\n if (allNotes[i].delete == true) {\n allNotes.splice(i, 1);\n }\n }\n}", "function onRemoveContact(e) {\n\n activeContact.remove(onSuccess, onError);\n \n function onSuccess() {\n alert(\"The contact was successfully removed\");\n displContactList.updateList();\n $.mobile.changePage(\"#cont_list_page\", { transition: \"pop\" }); \n };\n\n function onError(contactError) {\n alert(\"Cannot remove contact: error \" + contactError.code);\n $.mobile.changePage(\"#cont_info_page\", { transition: \"pop\" }); \n };\n}", "function del_choice(cid) {\n var b = document.getElementById('formChoices' + cid).remove();\n}", "function deleteList(c) {\n\tconst taskDel = document.querySelector(`.item-${c}`);\n\ttaskDel.firstElementChild.addEventListener(\"click\", () => {\n\t\tif (confirm(\"Are you sure?\")) {\n\t\t\ttaskDel.remove();\n\t\t\tconsole.log(taskDel.textContent);\n\t\t\tremoveFromStorage(taskDel.textContent);\n\t\t}\n\t});\n}", "deleteAt(index) {\n this.contacts = [...this.contacts.slice(0, index), ...this.contacts.slice(index + 1)];\n }", "static delete(email) {\n // TODO\n }", "function deletingchildelem() {\r\n $(\"#newcontent22\").remove();\r\n}", "function del_current_email(close){\n\t$close = $(close);\n\tvar this_p = $close.parent();\n\tthis_p.remove();\n\n\tvar addresses = $('#addresses').val().split(',');\n\tvar len = addresses.length;\n\tvar email = this_p.children('label:eq(0)').attr('title');\n\n\tfor(var i=0;i<len;i++){\n\t\tif(email == addresses[i]){\n\t\t\taddresses.splice(i, 1);\n\t\t\tbreak;\n\t\t}\n\t}\n\t$('#addresses').val(addresses.join(','));\n}", "deleteContact(event) {\n const { contactItems } = this.state;\n const target = event.target;\n const value = target.value;\n\n const newContactItems = contactItems;\n if (value > -1) {\n newContactItems.splice(value, 1);\n }\n\n localStorage.setItem('contactItems', JSON.stringify(newContactItems));\n this.setState({ contactItems: newContactItems, firstName: \"\", sirName: \"\" });\n }", "spamAction() {\n this.spams.forEach((group) => {\n if(group.length >= this.config.spamCountLimit) {\n let toDelete = [];\n\n group.forEach((id) => {\n let comment = this.comments.get(id);\n\n if(!comment.deleted) {\n this.group.deleteComment(id);\n comment.deleted = true;\n this.logger.log('Deleted spam comment with id: '+ id);\n }\n });\n }\n });\n }", "function use_del(uid) {\n Personals.use_del(uid).then(useSuccessFn, useErrorFn);\n /**\n * @name useSuccessFn\n * @desc Update ClubCard array on view\n */\n function useSuccessFn(data, status, headers, config) {\n activate();\n }\n /**\n * @name useErrorFn\n * @desc console log error\n */\n function useErrorFn(data, status, headers, config) {\n console.log(data);\n }\n }", "function DeleteNoteFromList(id){\n\t\t//this.projNotes[];\n\t\tvar noteIndex = FindProjNote(id);\n\t\t\n\t\tif(typeof noteIndex != \"boolean\"){\n\t\t\tprojNotes.splice(noteIndex, 1);\n\t\t\tnoteListChanged=true;\n\t\t}\n\t\t\n\t\t\n\t}", "function deleteChamp(l){\n\tvar supprimer = document.getElementById('line'+l);\n\tsupprimer.remove();\n}", "function delSelect(){\n\tvar activeObject = c.getActiveObject();\n if (activeObject['_objects']) {\n activeObject['_objects'].map(x => c.remove(x));\n } else if (activeObject) {\n c.remove(activeObject);\n }\n}", "async delete_message(msgid) {\n \n }", "deleteContact(contact) {\n $.ajax({\n url: '/contacts/' + contact.id,\n type: 'DELETE',\n dataType: \"json\",\n success: (response) => {\n const filterContacts = this.state.contacts.filter(contact => contact.id != response.id);\n this.setState({ contacts: filterContacts });\n },\n error: () => {\n console.log(\"Error in deleting contacts\");\n }\n });\n\n\n }", "function delete_person(data) {\n\t\t$('#' + data['old_id']).remove();\n\t}", "function deleteContact(contact) {\n var future = $q.defer();\n $http.post('/contacts/deleteContact', contact).success(function (data) {\n future.resolve(data);\n }, function (err) { future.reject(err); });\n return future.promise;\n }", "function deleteCm(evt) {\n var target = evt.target;\n console.log(target.getAttribute('delete'));\n coffeemakers = JSON.parse(localStorage.getItem('coffeemakers'));\n delete coffeemakers[target.getAttribute('delete')];\n localStorage.setItem('coffeemakers', JSON.stringify(coffeemakers));\n get_list();\n}", "function deletecontact(name, number)\n{\n if (typeof (webphone_api.plhandler) !== 'undefined' && webphone_api.plhandler !== null)\n return webphone_api.plhandler.DeleteContact(name, number);\n else\n return false;\n}", "function BOT_delete(list,atom) {\r\n\tvar l = new Array();\r\n\tfor(i in list) {\r\n\t\tif(list[i] != atom) l = l.concat([list[i]]);\r\n\t}\r\n\treturn l;\r\n}", "deleteAt(index) {\n if (index >= 0 && index < this.contacts.length) {\n this.contacts.splice(index, 1);\n } else {\n console.log(\"Invalid index.\");\n }\n }", "deletehsSubject(hssubject){\n var choice = confirm('Are you sure you want to delete this?');\n if (choice) {\n var index = this.get('subjectModel').indexOf(hssubject);\n var restemp = this.get('subjectModel').objectAt(index);\n console.log(restemp);\n restemp.deleteRecord();\n restemp.save();\n }\n }", "function deleteListItem(e) {\n let myTarget = e.target.parentElement.parentElement.parentElement;\n myTarget.remove();\n\n const myTitle = myTarget.querySelector('.notes-list-item-title');\n const mySubtext = myTarget.querySelector('.notes-list-item-subtext');\n\n deleteFromLocalStorage(myTitle.textContent, mySubtext.textContent);\n}", "function EliminarTel(indice) {\n telefonoItems.Eliminar(indice);\n MostrarTelefonos(true);\n return false;\n}", "function eliminarContacto() {\n\n var id_ver = document.getElementById(\"ver\").value;\n\n for (let i = 0; i < agenda.length; i++) {\n\n let persona = agenda[i];\n\n if ((persona.id) == id_ver) {\n\n agenda.splice(persona.id, 1);\n cargarResumen();\n }\n }\n}", "function deleteContact(contactID) {\n var tmpCurrentGroup = currentGroup;\n findItemAndDelete(currentGroup, contactID);\n updateLocalStorage();\n currentGroup = tmpCurrentGroup;\n getContactsList(currentGroup.id);\n\n }", "deleteNote(note) {\n this.notes = this.notes.filter(item => item !== note);\n }", "function removeRecipient(user, recipients) {\n var index = recipients.indexOf(user.email);\n if (index >= 0) {\n recipients.splice(index, 1);\n }\n }", "function deleteListItem() {\n item.remove();\n }", "function delete_contact()\n{\n $(document).on('click', '#del-contacts', function(event)\n {\n var response = confirm('This action is irreversible. Do you still want to delete this record?');\n if(response == true)\n {\n event.preventDefault();\n let id =$('#up-id').val();\n let delContacts=$('#del-contacts').val();\n $.ajax\n ({\n url:'contacts',\n method:'POST',\n data:\n {\n delid:id,\n delContacts:delContacts,\n },\n success:function()\n {\n show_record();\n $('form').trigger('reset');\n }\n })\n }\n })\n \n}", "handleDelete(){\n this.props.removeFromTable(this.props.index); \n this.props.removeContact(this.props.index);\n }", "function deleteRoomList(data) {\r\n let n = roomsName.indexOf(data);\r\n roomsName.splice(n, 1);\r\n rooms.splice(n, 1);\r\n console.log(rooms);\r\n let room = select(`#${data}`);\r\n room.remove();\r\n}", "function deletePerson3(person) {\n document.getElementById('tblPerson').removeChild(person);\n}", "function delete_it(thes)\n{\n\t $(thes).parent().remove();\n var id=$(thes).parent().attr('id');\n var index = id.indexOf('_');\n if(index != -1)\n {\n id= id.substr(index+1);\n var abcn=\".\"+id;\n //$('#List_'+id).removeClass('addItinerary');\n $(abcn).each(function() {\n $(this).removeClass('addItinerary');\n });\n\n index=Itineraries_list.indexOf(id);\n if(index != -1)\n {\n Itineraries_list.splice(index, 1);\n Itineraries_Ad.splice(index, 1);\n }\n Tour_List.splice(0,1);\n }\n }", "deleteByName(req, res) {\n Activity.findOneAndRemove({name: req.params.name}).then(result => {\n res.json(result);\n })\n .catch(err => {\n res.json(err);\n });\n }", "function removeContact(userid, sendtype, field, user) {\n\t// Show if exist in opener window.\n if ( existing = window.opener.document.getElementsByName(sendtype+'[]') ) {\n for (var i=0; i < existing.length; i++) {\n if (userid == existing[i].value) {\n var parent = window.opener.document.getElementById('id_name'+sendtype).parentNode;\n var fieldvalue = field.value;\n // Removes this element and returns boolean true\n parent.removeChild(existing[i].parentNode);\n // Removes the name from the contacts list\n if ( fieldvalue.indexOf(',') == -1) {\n field.value = '';\n } else {\n var firstindex = fieldvalue.indexOf(user);\n // Not first name...so remove the comma as well\n if (firstindex != 0) {\n user = ', '+user;\n } else {\n user = user+', ';\n }\n fieldvalue = fieldvalue.replace(user, '');\n field.value = fieldvalue;\n }\n return true;\n }\n }\n }\n // Not found...user not added\n return false;\n}", "function deleteNote() {\n const note = notes.value;\n window.localStorage.removeItem(note);\n editor.value = '';\n for (let i = 0; i < notes.length; i++) {\n const option = notes[i];\n if (option.value === note) {\n notes.removeChild(option);\n }\n }\n}", "function deleteTodos(position) {\n todos.splice(position, 1);\n displayTodos();\n}", "function eliminarPersona(user,res){\n tb_persona.connection.query(\"DELETE FROM persona WHERE id=\" + user.id);\n res.send();\n}", "function delete_meal_from_meal_list()\n{\n if (!current_meal.is_calendar_meal) {\n if (confirm(\"Are you sure you want to remove \" + current_meal.name + \" from your meals? (This cannot be undone)\")) {\n // Get the meal id\n var meal_id = current_meal.id;\n\n // Remove that one item from the calendar in HTML\n var meal_element_to_be_removed = document.getElementById(\"meal_list_item_\" + meal_id);\n meal_element_to_be_removed.parentElement.removeChild(meal_element_to_be_removed);\n\n // Delete the meal from the Users_Meals in the database\n var meal_record_to_remove = firebase_database.ref(\"Users_Meals/\" + user.uid + \"/\" + meal_id);\n meal_record_to_remove.remove();\n\n // Remove the meal from the \"meals\" in memory\n for (var i = 0; i < meals.length; i++) {\n if (meals[i].id == meal_id) {\n meals.splice(i, 1);\n break;\n }\n }\n }\n }\n}", "function remove_address_book_items(items)\n{\n for (i in items)\n {\n Widget.PIM.deleteAddressBookItem(items[i].addressBookItemId);\n }\n}", "handleRowRemoveTrialContact(event){\n this.isErrorSpinner= true;\n var row = event.detail.row;\n let rows = JSON.parse(JSON.stringify(this.trailContactsSelected));\n var index = rows.map(x => {\n return x.email;\n }).indexOf(row.email);\n \n \n rows.splice(index, 1);\n this.trailContactsSelected = rows;\n this.trailContactsSelectedTemp = rows;\n\n this.trailContactsToDisplay = [...this.trailContactsToDisplay, row];\n this.isErrorSpinner= false;\n }", "function deleteContact(element) {\r\n let row = element.parentNode.parentNode;\r\n let id = row.children[0].innerText;\r\n $.ajax({\r\n url: \"http://localhost:8080/api/contact/delete/\"+id,\r\n type: 'DELETE',\r\n success: function() {\r\n row.parentNode.removeChild(row);\r\n },\r\n fail: (err) => console.log(\"Couldn't delete \" + id, err)\r\n });\r\n}", "deleteTask(task) {\n const taskArray = [...this.state.tasks];\n const index = taskArray.map(t => t.text).indexOf(task);\n\n taskArray.splice(index, 1);\n\n this.setState({ tasks: taskArray });\n }", "function deleteContact(deleteButton){\n\t\t$(deleteButton).on('click', function(){\n\t\t\tvar phonebookContactId = $(this).data('id');\n\t\t\t\t//alert(contactId);\n\t\t\tif(confirm('Želite li da obrišete ovaj kontakt?')){\n\t\t\t\t$.ajax({\n\t\t\t\t\turl: 'inc/pages/pages_insert_info.php',\n\t\t\t\t\ttype: 'POST',\n\t\t\t\t\tdata: { phonebookContactId:phonebookContactId },\n\t\t\t\t\tsuccess: function(data){\n\t\t\t\t\t\tlocation.reload();\n\t\t\t\t\t},\n\t\t\t\t\terror: function(data){\n\t\t\t\t\t\tconsole.log('Error during the sending request...');\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}", "function deleteTodo(position){\n todos.splice(position, 1)\n displayTodos()\n}", "function deleteButtonHandler(event) {\n deleteContact(event.target.parentNode.getAttribute('data-id'));\n render(contacts);\n}", "function deleteTodo(position) {\r\n todos.splice(position, 1);\r\n displayTodos();\r\n}", "function deleteEntry(ENTRY){\n ENTRY_LIST.splice(ENTRY.id,1)\n updateUI()\n}", "deleteItem(req, res) {\n //grab the index where we will delete and use it for a splice\n const { index } = req.params;\n list.splice(index, 1);\n res.status(200).send(list);\n }", "delete(req, res) {\n\t\tUsuario.destroy({\n\t\t\twhere: {\n\t\t\t\tid_mail: req.params.id_mail\n\t\t\t}\n\t\t})\n\t\t.then(function (deletedRecords) {\n\t\t\tres.status(200).json(deletedRecords);\n\t\t})\n\t\t.catch(function (error){\n\t\t\tres.status(500).json(error);\n\t\t});\n\t}" ]
[ "0.6580841", "0.64672863", "0.64549804", "0.64067894", "0.6198085", "0.61663175", "0.6137476", "0.613246", "0.6119947", "0.61086005", "0.604236", "0.6016374", "0.6003497", "0.5986705", "0.59671557", "0.5945955", "0.59337527", "0.58832395", "0.58733827", "0.58339447", "0.5820829", "0.58172226", "0.5763839", "0.5762935", "0.5755485", "0.571969", "0.57137233", "0.5696716", "0.5690913", "0.568817", "0.5671814", "0.56698376", "0.5669664", "0.5643219", "0.56179357", "0.56072456", "0.55920464", "0.55895424", "0.5588932", "0.55863506", "0.5580955", "0.5561415", "0.5556129", "0.5553801", "0.5553122", "0.55499166", "0.5549189", "0.5541413", "0.5538342", "0.5532273", "0.5523523", "0.5492406", "0.54874957", "0.54825735", "0.5479557", "0.5478923", "0.5473416", "0.54515094", "0.54492956", "0.54431266", "0.54351276", "0.54251623", "0.5423533", "0.5421192", "0.5419615", "0.5419332", "0.54180014", "0.53988147", "0.5385794", "0.53841317", "0.53761786", "0.5367867", "0.5365213", "0.535782", "0.53558296", "0.5354136", "0.5353929", "0.5341822", "0.5333601", "0.5322631", "0.5322183", "0.53182775", "0.5313212", "0.5312153", "0.5308731", "0.53085977", "0.5307106", "0.5303828", "0.52989304", "0.5296116", "0.5295622", "0.52948076", "0.5293488", "0.52895534", "0.5288496", "0.52871966", "0.5285733", "0.52842206", "0.52740616", "0.5266247" ]
0.60610366
10
Function that would park a vehicle to the nearest entry point. accepts a vehicle object as a paramater. returns a List of where the vehicles is parked (A,B,C) and the parking slot object
park_vehicle(vehicle) { //Initial Loop through the list of parking slots for(var i=0 ; i<this.sizes.length; i++) { //check if the slot is occupied and if the vehicle size is SMALL //Small vehicles can park either of the three, Small, Medium, Large Parking Slot if(vehicle.vehicle_size === 'S' && !this.sizes[i].occupied) { //check if where would be the vehicle coming from entry point 1; if(vehicle.entry_point === 1) { // calculate for the closest distance from where the vehicle is coming from var currDistance = Math.abs(1 - this.map[0].entry_point1); var newDistance = Math.abs(1 - this.map[i].entry_point1); // check if the new distance is less than the curr distance if so park the vehicle // else park the vehicle with the lowest distance from the entry point of the vehicle if(newDistance < currDistance) { currDistance = newDistance; this.sizes[i].occupied = true; this.sizes[i].charge = 40; this.sizes[i].time_in = new Date() this.sizes[i].vehicle = vehicle; return [this.map[i], this.sizes[i]] } else { this.sizes[i].occupied = true; this.sizes[i].charge = 40; this.sizes[i].time_in = new Date() this.sizes[i].vehicle = vehicle; return [this.map[i], this.sizes[i]] } } //check if where would be the vehicle coming from entry point 2; else if(vehicle.entry_point == 2) { // calculate for the closest distance from where the vehicle is coming from var currDistance = Math.abs(1 - this.map[0].entry_point2); var newDistance = Math.abs(1 - this.map[i].entry_point2); // check if the new distance is less than the curr distance if so park the vehicle // else park the vehicle with the lowest distance from the entry point of the vehicle if(newDistance < currDistance) { currDistance = newDistance; this.sizes[i].occupied = true; this.sizes[i].charge = 40; this.sizes[i].time_in = new Date() this.sizes[i].vehicle = vehicle; return [this.map[i], this.sizes[i]] } else { this.sizes[i].occupied = true; this.sizes[i].charge = 40; this.sizes[i].time_in = new Date() this.sizes[i].vehicle = vehicle; return [this.map[i], this.sizes[i]] } } //check if where would be the vehicle coming from entry point 3; else if(vehicle.entry_point == 3) { // calculate for the closest distance from where the vehicle is coming from var currDistance = Math.abs(1 - this.map[0].entry_point3); var newDistance = Math.abs(1 - this.map[i].entry_point3); // check if the new distance is less than the curr distance if so park the vehicle // else park the vehicle with the lowest distance from the entry point of the vehicle if(newDistance < currDistance) { currDistance = newDistance; this.sizes[i].occupied = true; this.sizes[i].charge = 40; this.sizes[i].time_in = new Date() this.sizes[i].vehicle = vehicle; return [this.map[i], this.sizes[i]] } else { this.sizes[i].occupied = true; this.sizes[i].charge = 40; this.sizes[i].time_in = new Date() this.sizes[i].vehicle = vehicle; return [this.map[i], this.sizes[i]] } } } //check the size of the vehicle and if the parking slot is occupied else if (vehicle.vehicle_size === 'M' && !this.sizes[i].occupied) { //if the vehicle size is medium it can only be parked at medium slot and large slot if(this.sizes[i].slot_size === MEDIUM_SLOT || this.sizes[i].slot_size === LARGE_SLOT) { if(vehicle.entry_point === 1) { var currDistance = Math.abs(1 - this.map[0].entry_point1); var newDistance = Math.abs(1 - this.map[i].entry_point1); if(newDistance < currDistance) { currDistance = newDistance; this.sizes[i].occupied = true; this.sizes[i].charge = 40; this.sizes[i].time_in = new Date() this.sizes[i].vehicle = vehicle; return [this.map[i], this.sizes[i]] } else { this.sizes[i].occupied = true; this.sizes[i].charge = 40; this.sizes[i].time_in = new Date() this.sizes[i].vehicle = vehicle; return [this.map[i], this.sizes[i]] } } else if(vehicle.entry_point == 2) { var currDistance = Math.abs(1 - this.map[0].entry_point2); var newDistance = Math.abs(1 - this.map[i].entry_point2); if(newDistance < currDistance) { currDistance = newDistance; this.sizes[i].occupied = true; this.sizes[i].charge = 40; this.sizes[i].time_in = new Date() this.sizes[i].vehicle = vehicle; return [this.map[i], this.sizes[i]] } else { this.sizes[i].occupied = true; this.sizes[i].charge = 40; this.sizes[i].time_in = new Date() this.sizes[i].vehicle = vehicle; return [this.map[i], this.sizes[i]] } } else if(vehicle.entry_point == 3) { var currDistance = Math.abs(1 - this.map[0].entry_point3); var newDistance = Math.abs(1 - this.map[i].entry_point3); if(newDistance < currDistance) { currDistance = newDistance; this.sizes[i].occupied = true; this.sizes[i].charge = 40; this.sizes[i].time_in = new Date() this.sizes[i].vehicle = vehicle; return [this.map[i], this.sizes[i]] } else { this.sizes[i].occupied = true; this.sizes[i].charge = 40; this.sizes[i].time_in = new Date() return [this.map[i], this.sizes[i]] } } // if there is no more available slot for the vehicle to parked // return no avaialable parking slot } else { return 'No available Parking Slot' } } //checks if the vehicle size is Large and if the parking slot is occupied //Large vehicles can only be parked at Large Parking Slot else if (vehicle.vehicle_size === 'L' && !this.sizes[i].occupied) { if(this.sizes[i].slot_size === LARGE_SLOT) { if(vehicle.entry_point === 1) { var currDistance = Math.abs(1 - this.map[0].entry_point1); var newDistance = Math.abs(1 - this.map[i].entry_point1); if(newDistance < currDistance) { currDistance = newDistance; this.sizes[i].occupied = true; this.sizes[i].charge = 40; this.sizes[i].time_in = new Date() this.sizes[i].vehicle = vehicle; return [this.map[i], this.sizes[i]] } else { this.sizes[i].occupied = true; this.sizes[i].charge = 40; this.sizes[i].time_in = new Date() this.sizes[i].vehicle = vehicle; return [this.map[i], this.sizes[i]] } } else if(vehicle.entry_point == 2) { var currDistance = Math.abs(1 - this.map[0].entry_point2); var newDistance = Math.abs(1 - this.map[i].entry_point2); if(newDistance < currDistance) { currDistance = newDistance; this.sizes[i].occupied = true; this.sizes[i].charge = 40; this.sizes[i].time_in = new Date() this.sizes[i].vehicle = vehicle; return [this.map[i], this.sizes[i]] } else { this.sizes[i].occupied = true; this.sizes[i].charge = 40; this.sizes[i].time_in = new Date() this.sizes[i].vehicle = vehicle; return [this.map[i], this.sizes[i]] } } else if(vehicle.entry_point == 3) { var currDistance = Math.abs(1 - this.map[0].entry_point3); var newDistance = Math.abs(1 - this.map[i].entry_point3); if(newDistance < currDistance) { currDistance = newDistance; this.sizes[i].occupied = true; this.sizes[i].charge = 40; this.sizes[i].time_in = new Date() this.sizes[i].vehicle = vehicle; return [this.map[i], this.sizes[i]] } else { this.sizes[i].occupied = true; this.sizes[i].charge = 40; this.sizes[i].time_in = new Date() this.sizes[i].vehicle = vehicle; return [this.map[i], this.sizes[i]] } } } else { return 'No available Parking Slot' } } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function nearestParcel(place, parcels) {\n let routes = {};\n for (let parcelIndex in parcels) {\n routes[parcelIndex] = findRoute(roadGraph, place, parcels[parcelIndex].place)\n }\n\n let shortestRoute;\n for(let x in routes) {\n if(shortestRoute == undefined || routes[x].length < routes[shortestRoute].length) {\n shortestRoute = x\n }\n }\n return parcels[shortestRoute];\n}", "function navigateToClosestParkinglot(that){\n var parkinglots = [];\n var start;\n // Get all ParkingLot coordinates and save them in turf-compatible format\n // If StartLocation is Object also save coordinates\n for (var i =0; i < route_in_editing.values.parking.length; i++){\n var parking = route_in_editing.values.parking[i];\n if (parking.type === \"Parking\"){\n parkinglots.push(turf.helpers.point([parking.coords.x, parking.coords.y], {\"name\": parking.name}));\n } else if (parking.name === that.id.substr(20)){\n start = turf.helpers.point([parking.coords.x, parking.coords.y], {\"name\": parking.name});\n }\n }\n // If Start was not set as it is not an Object. check if startobject is startlocation else it is endlocation.\n if (start === undefined){\n var wp = route_in_editing.values.route.waypoints;\n if (that.id.substr(20) === route_in_editing.values.startLocation.name) {\n start = turf.helpers.point([wp[0].latLng.lat, wp[0].latLng.lng]);\n }else {\n start = turf.helpers.point([wp[wp.length-1].latLng.lat, wp[wp.length-1].latLng.lng]);\n }\n }\n // Calculate Nearest Parking using turf \n var nearest = turf.nearest(start, turf.helpers.featureCollection(parkinglots));\n // If there is a nearest Parking create RM\n if (nearest !== undefined) {\n navigationControl = L.Routing.control({\n // serviceUrl: \"http://localhost:5000/route/v1\", for development only\n routeWhileDragging: false,\n fitSelectedRoutes: true,\n show: true,\n position: 'topright',\n lineOptions: {\n styles: [{color: 'red', opacity: 1, weight: 5}]\n },\n createMarker: function() { return null; },\n }).addTo(map);\n navigationControl.setWaypoints([\n new L.latLng(start.geometry.coordinates[0], start.geometry.coordinates[1]),\n new L.latLng(nearest.geometry.coordinates[0], nearest.geometry.coordinates[1])\n ])\n } else {\n alert(\"No Parking Lots associated with this Stage.\");\n }\n}", "separate(vehicles) {\n let desiredseparation = this.separationDistance;\n // the steering force is the average of all the force sum/count\n let steer = createVector(0, 0);\n let count = 0;\n // For every boid in the system, check if it's too close\n for (let i = 0; i < vehicles.length; i++) {\n let d = p5.Vector.dist(this.location, vehicles[i].location);\n // If the distance is greater than 0 and less than an arbitrary amount (0 when you are yourself)\n if ((d > 0) && (d < desiredseparation)) {\n // Calculate vector pointing away from neighbor\n let diff = p5.Vector.sub(this.location, vehicles[i].location);\n diff.normalize();\n diff.div(d); // Weight by distance\n steer.add(diff);\n count++; // Keep track of how many\n }\n }\n // Average -- divide by how many\n if (count > 0) {\n steer.div(count);\n // Our desired vector is the average scaled to maximum speed\n steer.normalize();\n steer.mult(this.maxSpeed);\n // Implement Reynolds: Steering = Desired - Velocity\n steer.sub(this.velocity);\n steer.limit(this.maxForce);\n }\n return steer;\n }", "function findNearestParcel(graph, startingPlace, parcels) {\n // Keep track of the places we've already looked at.\n let checkedPlaces = [];\n\n // Keep track of the next place to look at. We'll add neighboring places to\n // this array to keep checking parcels.\n let placesToCheck = [startingPlace];\n\n // If there are no more places to check, then we have exhausted the entire\n // graph without finding a parcel.\n while (placesToCheck.length > 0) {\n\n // Start by checking the first place in the placesToCheck array.\n let nextPlace = placesToCheck.shift();\n\n // If a package is located at that place, then return it!\n if (parcels.map(p => p.place).includes(nextPlace)) {\n return parcels.find(p => p.place == nextPlace);\n }\n // Otherwise, we need to check the neighbors that we haven't already checked\n else {\n for (let adjacentPlace of graph[nextPlace]) {\n // If we haven't checked this neighbor, then add it to the places to\n // check.\n if (!checkedPlaces.includes(adjacentPlace)) {\n placesToCheck.push(adjacentPlace);\n }\n }\n }\n\n // Remember to mark the place as checked!\n checkedPlaces.push(nextPlace);\n }\n}", "function evenEvenBetterGoalOrientedRobot({place, parcels}, route){\n\tif (route.length > 0) return [route[0], route.slice(1)];\n\n\tlet routes = [];\n\tfor (let parcel of parcels){\n\t\tif (place == parcel.place) {\n\t\t\troutes.push({type: 'delivery', route: findRoute(roadGraph, place, parcel.address)});\n\t\t} else {\n\t\t\troutes.push({type: 'pickup', route: findRoute(roadGraph, place, parcel.place)});\n\t\t}\n\t}\n\n\tlet shortestRoute = routes.reduce((r1, r2) => {\n\t\tif (r1.route.length < r2.route.length) {\n\t\t\treturn r1;\n\t\t} else if (r1.route.length == r2.route.length) {\n\t\t\treturn r1.type == 'pickup' ? r1 : r2;\n\t\t} else {\n\t\t\treturn r2;\n\t\t}\n\t}).route;\n\treturn [shortestRoute[0], shortestRoute.slice(1)];\n}", "function lazyRobot({place, parcels}, route){\n\tif (route.length > 0) return [route[0], route.slice(1)];\n\tlet routes = parcels.map(p => place == p.place ? \n\t\t\t{pickup: false, route: findRoute(roadGraph, place, p.address)} :\n\t\t\t{pickup: true, route: findRoute(roadGraph, place, p.place)});\n\n\tfunction score(route){\n\t\treturn (route.pickup ? 0.5 : 0) - route.route.length;\n\t}\n\n\tlet shortestRoute = routes.reduce((r1, r2) => score(r1) > score(r2) ? r1 : r2).route;\n\n\treturn [shortestRoute[0], shortestRoute.slice(1)];\n}", "function nearestPoint(candidatePoints, points) {\n\n}", "function evenBetterGoalOrientedRobot({place, parcels}, route){\n\tif (route.length > 0) return [route[0], route.slice(1)];\n\n\tlet routes = [];\n\tfor (let parcel of parcels){\n\t\tif (place == parcel.place) {\n\t\t\troutes.push(findRoute(roadGraph, place, parcel.address));\n\t\t} else {\n\t\t\troutes.push(findRoute(roadGraph, place, parcel.place));\n\t\t}\n\t}\n\n\tlet shortestRoute = routes.reduce((r1, r2) => r1.length > r2.length ? r2 : r1);\n\treturn [shortestRoute[0], shortestRoute.slice(1)];\n}", "createCarPark(n, entryPoints) {\n this.maxSlots = n;\n for (let i = 0; i < n; i++) {\n this.slots.push(null);\n }\n this.entryPoints = entryPoints;\n\n // Prevent entry points from being available slots\n entryPoints.forEach((entryPoint) => {\n this.slots[entryPoint - 1] = 'Entry point';\n });\n }", "unpack_vehicle(vehicle) {\n //Loops through the parking slots.\n for(var i = 0; i < this.sizes.length; i++) {\n //check if the parking slot is occupied and there is a vehicle parked.\n if(this.sizes[i].occupied && this.sizes[i].vehicle !== undefined) {\n //check if the vehicle provided in the parameter is the same with the vehicle parked in the parking slot.\n if(this.sizes[i].vehicle.plate_number === vehicle.plate_number) {\n //checks if the vehicle size is in a small parking slot.\n if(this.sizes[i].slot_size === SMALL_SLOT) {\n //calculate the total amount of parking fee the vehicle consumed.\n // small parking slot cause a 20/hour rate.\n // and every exceeding 24 hours the vehicles is charge for 5000 PHP.\n let total_charge = this.sizes[i].charge\n let time_out = new Date().getHours()\n let time_difference = Math.ceil(Math.abs(parseInt(this.sizes[i].time_in.getHours()) - parseInt(time_out)))\n while(time_difference > 24) {\n if(time_difference > 24) {\n total_charge += this.sizes[i].charge + 5000\n time_difference -= 24;\n }\n }\n total_charge = total_charge + (20 * time_difference)\n this.sizes[i].occupied = false;\n this.sizes[i].vehicle = null;\n this.sizes[i].time_in = null;\n return `Total Parking Charge is: ${total_charge} PHP for vehicle ${vehicle.plate_number}`\n }\n //checks if the vehicle size is in a medium parking slot.\n else if (this.sizes[i].slot_size === MEDIUM_SLOT) {\n //calculate the total amount of parking fee the vehicle consumed.\n // medium parking slot cause a 60/hour rate.\n // and every exceeding 24 hours the vehicles are charged for 5000 PHP.\n let total_charge = this.sizes[i].charge;\n let time_out = new Date().getHours()\n let time_difference = Math.ceil(Math.abs(parseInt(this.sizes[i].time_in.getHours()) - parseInt(time_out)))\n while(time_difference > 24) {\n if(time_difference > 24) {\n total_charge += this.sizes[i].charge + 5000\n time_difference -= 24;\n }\n }\n total_charge = total_charge + (60 * time_difference)\n this.sizes[i].occupied = false;\n this.sizes[i].vehicle = null;\n this.sizes[i].time_in = null;\n return `Total Parking Charge is: ${total_charge} PHP for vehicle ${vehicle.plate_number}`\n }\n //checks if the vehicle size is in a medium parking slot.\n else if (this.sizes[i].slot_size === LARGE_SLOT) {\n // calculate the total amount of parking fee the vehicle consumed.\n // large parking slot cause a 60/hour rate.\n // and every exceeding 24 hours the vehicles are charged for 5000 PHP.\n let total_charge = this.sizes[i].charge;\n let time_out = new Date().getHours()\n let time_difference = Math.ceil(Math.abs(parseInt(this.sizes[i].time_in.getHours()) - parseInt(time_out)))\n while(time_difference > 24) {\n if(time_difference > 24) {\n total_charge += this.sizes[i].charge + 5000\n time_difference -= 24;\n // console.log(total_charge)\n }\n }\n total_charge = total_charge + (100 * time_difference)\n this.sizes[i].occupied = false;\n this.sizes[i].vehicle = null;\n this.sizes[i].time_in = null;\n return `Total Parking Charge is: ${total_charge} PHP for vehicle ${vehicle.plate_number}`\n }\n }\n }\n }\n }", "route (curPt, pois, options = {}) {\n const includedNearbys = [];\n\n\n // NEW - once we've created the graph, snap the current and nearby panos to the nearest junction within 5m, if there is one\n const snappedNodes = [ curPt, null ];\n if(options.snapToJunction) {\n snappedNodes[0] = this.jMgr.snapToJunction(curPt, 0.005);\n }\n pois.forEach(p => {\n p.lon = parseFloat(p.lon);\n p.lat = parseFloat(p.lat);\n //nearby.poseheadingdegrees = parseFloat(nearby.poseheadingdegrees);\n p.bearing = 720;\n snappedNodes[1] = options.snapToJunction ? this.jMgr.snapToJunction([p.lon, p.lat], this.distThreshold) : [p.lon, p.lat];\n \n const route = this.calcPath(snappedNodes);\n\n if(route!=null && route.path.length>=2) {\n // Initial bearing of the route (for OTV arrows, Hikar signposts, etc)\n let bearing = turfBearing(turfPoint(route.path[0]), turfPoint(route.path[1]));\n\n if(bearing < 0) bearing += 360;\n p.bearing = bearing;\n p.weight = route.weight;\n\n // save the path so we can do something with it \n p.path = route.path;\n }\n });\n // Sort routes to each POI based on bearing\n const sorted = pois.filter( p => p.bearing<=360).sort((p1,p2)=>(p1.bearing-p2.bearing)); \n let lastBearing = 720;\n let curPOIsForThisBearing = [];\n const poisGroupedByBearing = [];\n \n for(let i=0; i<sorted.length; i++) {\n if(Math.abs(sorted[i].bearing-lastBearing) >= 5) {\n // new bearing\n curPOIsForThisBearing = { bearing: sorted[i].bearing, pois: [] };\n poisGroupedByBearing.push(curPOIsForThisBearing);\n }\n curPOIsForThisBearing.pois.push(sorted[i]);\n lastBearing = sorted[i].bearing;\n }\n\n // Return value: an array of pois grouped by bearing and\n // sorted by distance within each bearing group.\n // This could be used to generate a virtual signpost (Hikar) or\n // select the immediately linked panorama (OTV)\n const poisGroupedByBearingSortedByDistance = poisGroupedByBearing.map ( forThisBearing =>{ return { bearing: Math.round(forThisBearing.bearing), pois: forThisBearing.pois.sort((n1, n2) => n1.weight - n2.weight)} });\n return poisGroupedByBearingSortedByDistance; \n }", "function betterGoalOrientedRobot({place, parcels}, route){\n\tif (route.length > 0) return [route[0], route.slice(1)];\n\n\tlet routes = [];\n\tfor (let parcel of parcels){\n\t\tif (place == parcel.place) {\n\t\t\troute = findRoute(roadGraph, place, parcel.address);\n\t\t\treturn [route[0], route.slice(1)];\n\t\t} else {\n\t\t\troutes.push(findRoute(roadGraph, place, parcel.place));\n\t\t}\n\t}\n\n\tlet shortestRoute = routes.reduce((r1, r2) => r1.length > r2.length ? r2 : r1);\n\treturn [shortestRoute[0], shortestRoute.slice(1)];\n}", "function getClosestCurvePointOnTrack(vertexOnTrack, closestVertex, carPosition) {\n // Get the vectors starting at closest vertex and ending at next and previous vertices\n let V = vec3.subtract(vec3.create(), vertexOnTrack, closestVertex);\n\n // Calculates the point on the track directly beneathe the car's position using the next vertex\n let t = (-V[0]*closestVertex[0] + V[0]*carPosition[0]\n -V[1]*closestVertex[1] + V[1]*carPosition[1]\n -V[2]*closestVertex[2] + V[2]*carPosition[2])\n /(Math.pow(V[0], 2) + Math.pow(V[1], 2) + Math.pow(V[2], 2));\n\n let point = vec3.scaleAndAdd(vec3.create(), closestVertex, V, t);\n \n return point;\n}", "function smartCourier({location, parcels}, route) {\n if (!route ||route.length == 0) {\n let parcel = parcels[0];\n if (parcel.location != location) {\n route = shortestRoute(roadGraph, location, parcel.location);\n } else {\n route = shortestRoute(roadGraph, location, parcel.address);\n }\n }\n return {newLocation: route[0], memory: route.slice(1)};\n}", "function launchFleet(planetA, planetB, player)\n{\n // TODO: This function launches a fleet from planet A to planet B,\n // controlled by player.\n}", "closestPointTo(position, closest, exclude) {\n if (this.visible && this.objects !== undefined) {\n for (let i = 0; i < this.objects.length; i++) {\n this.objects[i].closestPointTo(position, closest, exclude);\n }\n }\n }", "function checkParkCoord() {\n // clear parkResults array and remove any results cards from previous search\n parkResults = [];\n var resultsNode = document.getElementById(\"results\");\n resultsNode.innerHTML = '';\n // create resultsArray for current search\n for (var i = 0; i < parksArray.length; i++) {\n var parkLat = parseFloat(parksArray[i].lat);\n var parkLon = parseFloat(parksArray[i].lon);\n var park = parksArray[i].name;\n var index = [i];\n distance(userLat, userLon, parkLat, parkLon, park, index);\n }\n createResults();\n showMap();\n}", "function park(position){\n setDetail(selected, 'lat', position.lat());\n setDetail(selected, 'lng', position.lng());\n var markerId = 'marker'+selected;\n clearMarkers();\n $('#map_canvas').gmap('addMarker', {'markerId':markerId,\n 'position': position,\n 'icon' : icons[getUnitDetail(selected, 'type')],\n 'draggable': true,\n 'clickable': true,\n 'animation': google.maps.Animation.DROP}).dragend( function(event) {\n // Drag handler //\n park(event.latLng);\n }).click( function(event){\n // Click Handler // \n $('#map_canvas').gmap('openInfoWindow', { content : getUnitDetail(selected, 'adress') }, this);\n });\n getAdress(position);\n }", "function goalOrientedRobot({place, parcels}, route){\n\tif (route.length > 0) return [route[0], route.slice(1)];\n\tlet parcel = parcels[0];\n\tif (place == parcel.place) {\n\t\troute = findRoute(roadGraph, place, parcel.address);\n\t} else {\n\t\troute = findRoute(roadGraph, place, parcel.place);\n\t}\n\treturn [route[0], route.slice(1)];\n}", "function distance(lat1, lon1, lat2, lon2, park, index) {\n var p = 0.017453292519943295; \n var c = Math.cos;\n var a = 0.5 - c((lat2 - lat1) * p)/2 + \n c(lat1 * p) * c(lat2 * p) * \n (1 - c((lon2 - lon1) * p))/2;\n if ((12742 * Math.asin(Math.sqrt(a))) < 1 ) {\n var closePark = {};\n closePark['name'] = park;\n closePark['location'] = parksArray[index].location;\n closePark['monument'] = parksArray[index].monument;\n closePark['trails'] = parksArray[index].trails;\n closePark['lat'] = parksArray[index].lat;\n closePark['lon'] = parksArray[index].lon;\n parkResults.push(closePark);\n } \n}", "getCarPoints(pickedProps) {\n // Mercedes-Benz Citan Tourer xlg\n const carLength = 4.705\n const carWidth = 1.829\n const headlightBeamLength = 0.5\n\n const lightAngle = (90 - 30 / 2) * Points.degreesToRadians\n\n const carWidthHalf = carWidth / 2\n const carWidthQuarter = carWidth / 4\n const carLengthHalf = carLength / 4\n // all basic shapes are 0-based, and will be ratio adjusted and repositioned later\n const shell = [\n {x: carWidthHalf, y: -carLengthHalf},\n {x: -carWidthHalf, y: -carLengthHalf},\n {x: -carWidthHalf, y: carLengthHalf},\n {x: carWidthHalf, y: carLengthHalf},\n ]\n const headlight = [\n {x: 0, y: 0},\n {x: Math.cos(lightAngle) * headlightBeamLength, y: -headlightBeamLength},\n {x: -Math.cos(lightAngle) * headlightBeamLength, y: -headlightBeamLength},\n ]\n return new Points([\n shell,\n new Points(headlight).center({x: -carWidthQuarter, y: -carLengthHalf}),\n new Points(headlight).center({x: carWidthQuarter, y: -carLengthHalf}),\n ]).scale(10)\n }", "function calcPoint(currentPoint) {\n var distances = new Array(); // make array for the distances\n for(let point of points){\n\n // call distance function\n var distance = getDistance(point[2], point[3], Number(currentPoint[2]), Number(currentPoint[3]));\n\n // put the distance from the boat to the point in an array\n var location = new Array();\n location[0] = point[0];\n location[1] = Number(distance)*1000; // *1000 to get meters instead of km's \n location[2] = point[2];\n location[3] = point[3];\n distances.push(location); // add current position and distance to boat to distances array\n }\n\n distances.sort(compareSecondColumn); // sort the array by the distances\n\n var closestPoint = distances[0]; // take the lowest distance\n\n distances.shift(); // 2.2 remove the used point from the distances\n points = distances; // and replace the points array with the remaining items of the distances array\n\n return closestPoint; // return the closest point\n}", "function serve(service, truck, airport) {\n truck.setProp(\"status\", \"busy\")\n truck.setProp(\"current-service\", service)\n // get from truck position to service road, move there slowly\n let p = geojson.findClosest(truck.getProp(\"position\"), airport.serviceroads)\n //debug.print(\"closest to truck\", truck.position, p)\n truck.addPointToTrack(p, truck.getProp(\"slow\"), 30) // truck moves to serviceroad\n\n // get to parking on service road at full speed\n let parking = geojson.findFeature(service.parking, airport.parkings, \"name\")\n debug.print(parking)\n if (!parking) {\n debug.print(\"not found\", \"name\", service.parking)\n return\n }\n let p1 = geojson.findClosest(parking, airport.serviceroads)\n //debug.print(\"closest to parking\", parking, p1)\n\n // move truck from where it was to close to parking on serviceroads\n let r = geojson.route(p, p1, airport.serviceroads)\n truck.addPathToTrack(r.coordinates, truck.getProp(\"speed\"), null)\n\n // we do not stop \"exactly\" at the parking's center but nearby\n let aroundParkingCoordinates = jitter(parking.geometry.coordinates, 30) // 30 meters\n\n // get from service road to parking slowly and service plane\n // service\n truck.addPointToTrack(aroundParkingCoordinates, truck.getProp(\"slow\"), truck.serviceTime(service.qty))\n\n truck.setProp(\"load\", truck.getProp(\"load\") - service.qty)\n truck.setProp(\"position\", aroundParkingCoordinates)\n\n // ADD STOP TO EXPLAIN SERVICE OPERATION\n truck.addMarker(\n \"serve\",\n aroundParkingCoordinates,\n 0,\n truck.serviceTime(service.qty),\n truck.getProp(\"syncCount\"),\n truck.getProp(\"color\"),\n {\n \"device\": truck.getName(),\n \"service\": truck.getProp(\"service\"),\n \"capacity\": truck.getProp(\"capacity\"),\n \"load\": truck.getProp(\"load\"),\n \"status\": truck.getProp(\"status\"),\n \"action\": \"serve\",\n \"quantity\": service.qty,\n \"posname\": service.parking,\n \"scheduled\": service.datetime\n })\n truck.setProp(\"syncCount\", truck.getProp(\"syncCount\") + 1)\n\n truck.setProp(\"last-service\", service)\n truck.setProp(\"last-parking\", service.parking)\n truck.setProp(\"status\", \"available\")\n\n // We add an extra point at the end to move the truck away from parking back to service road\n // so that it 'leaves' the parking position after it services.\n truck.addPointToTrack(p1, truck.getProp(\"slow\"), 0)\n truck.setProp(\"position\", p1.geometry.coordinates)\n truck.addPointToTrack(p1, 0, 120) // make sure it emits out of parking space.\n}", "function initialize() {\n // grab the UI elements that we need to manipulate\n var name = document.querySelector('#name');\n console.log(name);\n var nbPlaces = document.querySelector('#max');\n var itineraryBtn = document.querySelector('button');\n //var main = document.querySelector('main');\n\n // keep a record of what the last name and nbPlaces entered were\n var lastName = name.value;\n // no search has been made yet\n var lastNbPlaces = nbPlaces.value;\n\n // these contain the results of filtering by name, and nbPlaces\n // finalGroup will contain the parkings that need to be displayed after\n // the searching has been done. Each will be an array containing objects.\n // Each object will represent a parking\n var nameGroup;\n var finalGroup;\n\n // To start with, set finalGroup to equal the entire parkings database\n // then run updateDisplay(), so ALL parkings are displayed initially.\n finalGroup = parkings;\n ajouterLigne();\n //updateDisplay();\n\n // Set both to equal an empty array, in time for searches to be run\n nameGroup = [];\n finalGroup = [];\n\n // when the itineraryBtn is clicked, invoke selectName() to start\n // a search running to select the name of parkings we want to display\n itineraryBtn.onclick = selectName;\n\n function selectName(e) {\n // Use preventDefault() to stop the form submitting — that would ruin\n // the experience\n e.preventDefault();\n\n // Set these back to empty arrays, to clear out the previous search\n nameGroup = [];\n finalGroup = [];\n\n // if the name and nbPlaces are the same as they were the last time a\n // search was run, the results will be the same, so there is no point running\n // it again — just return out of the function\n if (name.value === lastName && max.value === lastNbPlaces) {\n return;\n } else {\n // update the record of last name and nbPlaces\n lastName = name.value;\n lastNbPlaces = max.value;\n // In this case we want to select all parkings, then filter them by the search\n // term, so we just set nameGroup to the entire JSON object, then run selectParkings()\n if (name.value === 'All') {\n nameGroup = parkings;\n selectParkings();\n // If a specific name is chosen, we need to filter out the parkings not in that\n // name, then put the remaining parkings inside nameGroup, before running\n // selectParkings()\n } else {\n // the values in the <option> elements are uppercase, whereas the categories\n // store in the JSON (under \"type\") are lowercase. We therefore need to convert\n // to lower case before we do a comparison\n var lowerCaseType = name.value.toLowerCase();\n for (var i = 0; i < parkings.length; i++) {\n // If a parking's type property is the same as the chosen name, we want to\n // dispay it, so we push it onto the nameGroup array\n if (parkings[i].type === lowerCaseType) {\n nameGroup.push(parkings[i]);\n }\n }\n\n // Run selectParkings() after the filtering has bene done\n selectParkings();\n }\n }\n }\n/*\n // selectParkings() Takes the group of parkings selected by selectName(), and further\n // filters them by the tnered nbPlaces (if one has bene entered)\n function selectParkings() {\n // If no nbPlaces has been entered, just make the finalGroup array equal to the nameGroup\n // array — we don't want to filter the parkings further — then run updateDisplay().\n if (max.value === '') {\n finalGroup = nameGroup;\n updateDisplay();\n } else {\n // Make sure the nbPlaces is converted to lower case before comparison. We've kept the\n // parking names all lower case to keep things simple\n var lowerCaseMax = max.value.trim().toLowerCase();\n // For each parking in nameGroup, see if the nbPlaces is contained inside the parking name\n // (if the indexOf() result doesn't return -1, it means it is) — if it is, then push the parking\n // onto the finalGroup array\n for (var i = 0; i < nameGroup.length; i++) {\n if (nameGroup[i].name.indexOf(lowerCaseMax) !== -1) {\n finalGroup.push(nameGroup[i]);\n }\n }\n\n // run updateDisplay() after this second round of filtering has been done\n updateDisplay();\n }\n\n }\n*/\n /*\n // start the process of updating the display with the new set of parkings\n function updateDisplay() {\n // remove the previous contents of the <main> element\n while (main.firstChild) {\n main.removeChild(main.firstChild);\n }\n\n // if no parkings match the nbPlaces, display a \"No results to display\" message\n if (finalGroup.length === 0) {\n var para = document.createElement('p');\n para.textContent = 'No results to display!';\n main.appendChild(para);\n // for each parking we want to display, pass its parking object to fetchBlob()\n } else {\n for (var i = 0; i < finalGroup.length; i++) {\n fetchBlob(finalGroup[i]);\n }\n }\n }*/\n/*\n // fetchBlob uses fetch to retrieve the image for that parking, and then sends the\n // resulting image display URL and parking object on to showParking() to finally\n // display it\n function fetchBlob(parking) {\n // construct the URL path to the image file from the parking.image property\n var url = 'images/' + parking.image;\n // Use fetch to fetch the image, and convert the resulting response to a blob\n // Again, if any errors occur we report them in the console.\n fetch(url).then(function (response) {\n if (response.ok) {\n response.blob().then(function (blob) {\n // Convert the blob to an object URL — this is basically an temporary internal URL\n // that points to an object stored inside the browser\n objectURL = URL.createObjectURL(blob);\n // invoke showParking\n showParking(objectURL, parking);\n });\n } else {\n console.log('Network request for \"' + parking.name + '\" image failed with response ' + response.status + ': ' + response.statusText);\n }\n });\n }\n */\n // Display a parking inside the <main> element\n function showParking(objectURL, parking) {\n // create <section>, <h2>, <p>, and <img> elements\n //var section = document.createElement('section');\n var heading = document.createElement('h2');\n var para = document.createElement('p');\n //var image = document.createElement('img');\n /*\n // give the <section> a classname equal to the parking \"type\" property so it will display the correct icon\n section.setAttribute('class', parking.type);\n */\n\n // Give the <h2> textContent equal to the parking \"name\" property, but with the first character\n // replaced with the uppercase version of the first character\n heading.textContent = parking.name.replace(parking.name.charAt(0), parking.name.charAt(0).toUpperCase());\n\n // Give the <p> textContent equal to the parking nbPlaces property\n para.textContent = parking.nbPlaces;\n\n /*\n // Set the src of the <img> element to the ObjectURL, and the alt to the parking \"name\" property\n image.src = objectURL;\n image.alt = parking.name;\n */\n\n // append the elements to the DOM as appropriate, to add the parking to the UI\n main.appendChild(section);\n section.appendChild(heading);\n section.appendChild(para);\n //section.appendChild(image);\n }\n}", "move(destination) {\n if (!roadGraph[this.location].includes(destination)) {\n return this;\n } else {\n let parcels = this.parcels.map(p => {\n if (p.location != this.location) return p;\n return {location: destination, address: p.address};\n }).filter(p => p.location != p.address);\n return new Itinerary(destination, parcels);\n }\n }", "function goalOrientedRobot({place, parcels}, route) { //This robot takes \n if (route.length == 0) { //route.length is zero means the robot has not run yet\n let parcel = parcels[0]; //parcels is ready to be picked up but not yet\n if (parcel.place != place) {//place is the pickup point, parcel is the drop-off point, when the pickup and drop-off points are not the same, we do the following\n route = findRoute(roadGraph, place, parcel.place); //place is the location of the robot, parcel.place is the pickup point\n } else {\n route = findRoute(roadGraph, place, parcel.address); //parcel.address is drop-off point\n }\n }\n return {direction: route[0], memory: route.slice(1)}; //tell the robot to not to remember the route taken\n }", "function computeMainPoints(totalPoints, mainPoints, epsilon = 0.0001) {\n var ans = [];\n for (var i = 0; i < totalPoints.length; i++) {\n var runningPoint = totalPoints[i];\n for (var j = 0; j < mainPoints.length; j++) {\n var runningPassenger = mainPoints[j];\n\n // si\n // lat match\n var siLatMatch = Math.abs(runningPoint.lat - runningPassenger.lat) < epsilon;\n var siLngMatch = Math.abs(runningPoint.lng - runningPassenger.lng) < epsilon;\n\n if (siLatMatch && siLngMatch) {\n // console.log(\"Including point: \", runningPoint, \" because it's equal to existing main point: \", runningPassenger, \" at index: \" + j);\n ans.push(runningPoint);\n break;\n }\n\n }\n }\n return ans;\n}", "function clickOnPark(p) {\n // zoom to the park, but not too close\n var fb = bbox(p.geometry);\n var flybox = [[fb[0], fb[1]], [fb[2], fb[3]]]\n map.fitBounds(flybox, { padding: 50, maxZoom: 17 })\n\n\n // get all the amenities for the park\n var parkAmenities = [];\n Object.keys(p.properties).forEach(function(a){\n if (p.properties[a] == 1) {\n parkAmenities.push(FILTERS[a]);\n }\n });\n\n // html for all parks\n var parkHtml = `\n <span>Park name: <b>${p.properties.name}</b></span>\n <span>Address: <b>${p.properties.address}</b></span>\n <hr>\n <span><b>Available activities:<br/></b> ${parkAmenities.join(', ')}</span>\n `\n\n // if it has a rec center, toss this in there\n if (p.properties.rec_center_name != 'null') {\n var recCtrHtml = `\n <span><b>Recreation Center:</b><br/> ${p.properties.rec_center_name}</span>\n <span><b>Hours of Operation:</b><br/> ${p.properties.opening_hours}</span>\n <br/>\n `\n parkDetails.innerHTML = recCtrHtml + parkHtml;\n }\n else {\n parkDetails.innerHTML = parkHtml;\n };\n\n if (window.innerWidth < 768) {\n thisSlideout.open();\n }\n }", "function getCarsNearBy(lat, lng){\r\n\t\r\n\t// lat and lng variables in this call object are shared among all closures\r\n\tlat = (_.isString(lat)) ? parseFloat(lat) : lat;\r\n\tlng = (_.isString(lng)) ? parseFloat(lng) : lng;\r\n\t\r\n\t// do mapMatch and update the (lat,lng) to matched ones\r\n\tfunction matchMapOrigin(){\r\n\t\t// do matchMap with error-fallback option\r\n\t\treturn Q.allSettled([contextMapping.matchMap(lat, lng), 'default'])\r\n\t\t\t\t.spread(function(matchResult, defaultResult){\r\n\t\t\t\t\tif (matchResult.state == 'fulfilled'){\r\n\t\t\t\t\t\tlat = matchResult.value.lat;\r\n\t\t\t\t\t\tlng = matchResult.value.lng;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t}\r\n\t\r\n\tfunction findExistingCarsNearBy(){\r\n\t\tvar devices = connectedDevices.getConnectedDevices();\r\n\t\tvar devicesNearBy = devices.filter(function(device){\r\n\t\t\tif(!device.lat || !device.lng)\r\n\t\t\t\treturn false;\r\n\t\t\tvar distance = getDistance(\r\n\t\t\t\t\t{latitude: device.lat, longitude: device.lng},\r\n\t\t\t\t\t{latitude: lat, longitude: lng}\r\n\t\t\t);\r\n\t\t\treturn distance < 1000;//first filter out those who are in radius of 1000\r\n\t\t}).map(_.clone);\r\n\t\treturn devicesNearBy;\r\n\t}\r\n\t\r\n\tfunction filterOutUnreservedCars(devices){\r\n\t\tvar devicesIds = _.pluck(devices, 'deviceID');\r\n\t\treturn dbClient.searchView('activeReservations', {keys: devicesIds}).then(function(result){\r\n\t\t\tvar activeDeviceIds = _.pluck(result.rows, 'key');\r\n\t\t\tvar result = devices.filter(function(device){\r\n\t\t\t\treturn activeDeviceIds.indexOf(device.deviceID) < 0; // retain if missing\r\n\t\t\t});\r\n\t\t\treturn result;\r\n\t\t});\r\n\t}\r\n\t\r\n\tfunction reviewAndUpdateList(devicesNearBy){\r\n\t\t// expand car list if necessary\r\n\t\tif (router.onGetCarsNearbyAsync){\r\n\t\t\t// user exit to allow demo-cars around\r\n\t\t\treturn router.onGetCarsNearbyAsync(lat, lng, devicesNearBy)\r\n\t\t\t\t.then(filterOutUnreservedCars);\r\n\t\t}else{\r\n\t\t\treturn Q(devicesNearBy);\r\n\t\t}\r\n\t}\r\n\t\r\n\tfunction appendDistance(devices){\r\n\t\t// add route distance to all devices\r\n\t\treturn Q.all(devices.map(function(device){\r\n\t\t\treturn contextMapping.routeDistance(lat, lng, device.lat, device.lng)\r\n\t\t\t\t\t.then(function(dist){ \r\n\t\t\t\t\t\tdevice.distance = dist; \r\n\t\t\t\t\t\treturn device; \r\n\t\t\t\t\t});\r\n\t\t\t\t}));\r\n\t}\r\n\t\r\n\treturn matchMapOrigin()\r\n\t\t.then(dbClient.cleanupStaleReservations)\r\n\t\t.then(findExistingCarsNearBy)\r\n\t\t.then(filterOutUnreservedCars)\r\n\t\t.then(reviewAndUpdateList)\r\n\t\t.then(appendDistance)\r\n\t\t.then(dbClient.getDeviceDetails);\r\n}", "function nearest(x,y,obj,n) {\n let all_distance = [] \n if (obj.length > 1 && n<=obj.length) {\n for (let i = 0; i < obj.length; i++) {\n all_distance[i] = distance(x,y,obj[i].x,obj[i].y) \n }\n all_distance = sort(all_distance);\n for (let i = 0; i < obj.length; i++) {\n if (distance(x,y,obj[i].x,obj[i].y)==all_distance[n]) return obj[i] \n }\n }\n}", "function closest_neighbor() {\n\t// Calculate neighbor for each shape\n\tshapes.forEach(function (item, index, arr) {\n\t//console.log(item);\n\t\n\t\tvar distances = []; // between on point an the rest\n\n\t\t// calculating distances\n\t\tfor (var i = 0; i < shapes.length ; i++) {\n\t\t\tlet delta_x = item.x - shapes[i].x;\n\t\t\tlet delta_y = item.y - shapes[i].y;\n\n\t\t\t//console.log(\"delta_x = item.x - shapes[i+1].x = \" + item.x + \" - \" + shapes[i+1].x + \" = \" + delta_x);\n\t\t\t//console.log(\"delta_y = item.y - shapes[i+1].y = \" + item.y + \" - \" + shapes[i+1].y + \" = \" + delta_y);\n\n\t\t\tdistances[i] = Math.sqrt( delta_x*delta_x + delta_y*delta_y);\n\n\t\t\t//var next_shape_idx = i+1;\n\t\t\t//console.log(\"distance [\"+ index +\" to \"+ next_shape_idx + \"] = \" + distances[i]);\n\t\t}\n\n\t\t// Look for smallest distance and assign it as neighbor\n\t\tshapes[index].neighbor = index_of_min(distances, 0);\n\t});\n}", "function cutTripsByBearing(driverTrip, riderTrips) {\n\tif (typeof riderTrips === \"undefined\" || typeof driverTrip === \"undefined\" || riderTrips === []) {\n\t\treturn [];\n\t}\n\n\tlet newDriverRoute = driverTrip.tripRoute;\n\tlet driverBearing = LatLng.getLatLngBearing(newDriverRoute.routes[0].legs[0].start_location.lat,\n\t\t\tnewDriverRoute.routes[0].legs[0].start_location.lng,\n\t\t\tnewDriverRoute.routes[0].legs[newDriverRoute.routes[0].legs.length - 1].end_location.lat,\n\t\t\tnewDriverRoute.routes[0].legs[newDriverRoute.routes[0].legs.length - 1].end_location.lng);\n\tlet riderTripsBearing = [];\n\n\triderTrips.forEach(function(riderTrip) {\n\t\tlet newRiderRoute = riderTrip.tripRoute;\n\t\tlet riderBearing = LatLng.getLatLngBearing(newRiderRoute.routes[0].legs[0].start_location.lat,\n\t\t\t\tnewRiderRoute.routes[0].legs[0].start_location.lng,\n\t\t\t\tnewRiderRoute.routes[0].legs[0].end_location.lat,\n\t\t\t\tnewRiderRoute.routes[0].legs[0].end_location.lng);\n\t\tif (Math.abs(driverBearing - riderBearing) <= MaxDriverBearingDiff) {\n\t\t\triderTripsBearing.push(riderTrip);\n\t\t}\n\t});\n\n\treturn riderTripsBearing;\n}", "function chooseClosest() {\n for (var i = 0; i < tempCheckArray.length; i++) {\n // Sort Distances\n tempCheckArray.sort(function(a, b) {\n let varA;\n let varB;\n varA = a[\"distance\"];\n varB = b[\"distance\"];\n if (varA < varB) {\n return 1;\n } else if (varB < varA) {\n return -1;\n }\n return 0;\n });\n }\n airportsByDistanceClosest = tempCheckArray.reverse();\n closestAirportLat = airportsByDistanceClosest[0][\"latitude\"];\n closestAirportLon = airportsByDistanceClosest[0][\"longitude\"];\n closeLatLon = { \"latitude\": closestAirportLat, \"longitude\": closestAirportLon };\n}", "function getLeastVisitedPlaces(bookings) {\n var visits = [];\n for (let planet of destinations) {\n visits.push({ planet: planet, totalVisits: 0 });\n }\n\n for (booking of bookings) {\n places = [\n booking.travelRoute[0],\n booking.travelRoute[booking.travelRoute.length - 1],\n ];\n for (place of places) {\n for (vObj of visits) {\n if (vObj.name == place) {\n vObj.totalVisits += 1;\n break;\n }\n }\n }\n }\n\n _.orderBy(visits, [\"totalVisits\"], [\"desc\"]);\n\n length = visits.length;\n\n // recommending the least 3 visited planets\n leastVisited = [\n visits[length - 1][\"planet\"],\n visits[length - 2][\"planet\"],\n visits[length - 3][\"planet\"],\n ];\n\n return leastVisited;\n}", "function lazyRobot({ place, parcels }, route) {\n if (route.length == 0) {\n // Describe a route for every parcel\n let routes = parcels.map(parcel => {\n if (parcel.place != place) {\n return {\n route: findRoute(roadGraph, place, parcel.place),\n pickUp: true\n };\n } else {\n return {\n route: findRoute(roadGraph, place, parcel.address),\n pickUp: false\n };\n }\n });\n\n // This determines the precedence a route gets when choosing.\n // Route length counts negatively, routes that pick up a package\n // get a small bonus.\n function score({ route, pickUp }) {\n return (pickUp ? 0.5 : 0) - route.length;\n }\n route = routes.reduce((a, b) => (score(a) > score(b) ? a : b)).route;\n }\n\n return { direction: route[0], memory: route.slice(1) };\n}", "function getClosestLot(coords) {\n // Calculate distances to each parking lot\n distances = [];\n markers.forEach(function (marker) {\n if (marker.labelContent === 'CLOSED' || marker.labelContent === '0') {\n distances.push(Infinity);\n } else {\n var dist = Math.pow(marker.position.lat() - coords.latitude, 2) + Math.pow(marker.position.lng() - coords.longitude, 2);\n distances.push(dist);\n }\n });\n\n // Get the closest parking lot\n var smallest_index = argmin(distances);\n var closest_lot = markers[smallest_index];\n console.log(closest_lot);\n\n // Display new location information\n if (locationMarker) { locationMarker.setMap(null); }\n locationMarker = new MarkerWithLabel({\n position: {lat: coords.latitude - 0.00025, lng: coords.longitude},\n map: map,\n icon: '/static/img/location.png',\n animation: google.maps.Animation.DROP,\n });\n\n // Move map to closest parking lot\n map.panTo(closest_lot.getPosition());\n\n // Set marker of closest parking lot marker\n // TODO: Recolor all markers in the correct color before making a new one blue\n closest_lot.setIcon('/static/img/closest_icon.png');\n\n // Draw line to closest parking lot\n if (closestLotLine) { closestLotLine.setMap(null); }\n closestLotLine = new google.maps.Polyline({\n path: [{lat: coords.latitude, lng: coords.longitude}, \n {lat: closest_lot.position.lat(), lng: closest_lot.position.lng()}],\n strokeOpacity: 0,\n icons: [{\n icon: {\n path: 'M 0,-1 0,1',\n strokeOpacity: 1,\n scale: 3,\n strokeColor: '#00a8ff',\n fillColor: '#00a8ff',\n },\n offset: '0',\n repeat: '20px',\n }],\n map: map\n });\n\n // Draw line to closest parking lot\n locationMarkerContent = '<h2 style=\"color:rgb(0, 168, 255);\">Your Location</h2>' + \n '<p><strong>Coordinates</strong>: <a href=\"http://maps.google.com/maps?q=' + coords.latitude + ',' + coords.longitude + '&z=14&ll=' + coords.latitude + ',' + coords.longitude + '\" target=\"_blank\">(' + coords.latitude + ', ' + coords.longitude + ')</a></p>';\n markerAddInfoWindow(locationMarker, locationMarkerContent);\n}", "function showParkListings() {\n let bounds = new google.maps.LatLngBounds();\n // Extend the boundaries of the map for each marker and display the marker\n for (let i = 0; i < markersPark.length; i++) {\n markersPark[i].setMap(map);\n bounds.extend(markersPark[i].position);\n }\n map.fitBounds(bounds);\n}", "function currently_in_use_getStocksAndVehicles(trips, timeRange){\n\t// Returns vehicles as objects\n\t// Best one\n\tvar stocks = [];\n\tvar vehicles = [];\n\n stocks.push({\n type : 'inTransit',\n name : 'inTransit',\n id : 'inTransit',\n initial: 0,\n stackOrder: 0,\n values : []\n });\n stocks.push({\n type : 'dispatched',\n name : 'dispatched',\n id : 'dispatched',\n initial: 0,\n stackOrder: 1,\n values : []\n });\n\ttrips.forEach(function(trip) {\n if (stocks.find(d => d.name==trip.start_station)==null) {\n stocks.push({\n type : 'station',\n name : trip.start_station_name,\n id : trip.start_station,\n lat : trip.start_station_lat,\n lng : trip.start_station_lng,\n initial: 0,\n stackOrder: 10,\n values : []\n });\n }\n if (stocks.find(d => d.name==trip.end_station)==null){\n stocks.push({\n type : 'station',\n name : trip.end_station_name,\n id : trip.end_station,\n lat : trip.end_station_lat,\n lng : trip.end_station_lng,\n initial: 0,\n stackOrder: 10,\n values : []\n });\n }\n\t\tif (vehicles.find(d => d.vehicle_id == trip.bikeid)==null) {\n\t\t\tvehicles.push({vehicle_id : trip.bikeid});\n\t\t\tstocks.find(d => d.name==trip.start_station).initial++;\n\t\t}\n\t\tif(trip.start_date<=timeRange[0]){\n\t\t\tif(trip.type==\"full\") stocks.find(function(d){return d.name=='inTransit'}).initial++;\n\t\t\tif(trip.type==\"empty\") stocks.find(function(d){return d.name=='dispatched'}).initial++;\n\t\t}\n\t});\n\treturn {\n\t\tstocks: stocks,\n\t\tvehicles: vehicles\n\t}\n}", "function fasterRobot({place, parcels}, route) {\n if (route == undefined || route.length == 0) {\n let parcel = nearestParcel(place, parcels);\n if (parcel.place != place) {\n route = findRoute(roadGraph, place, parcel.place);\n } else {\n route = findRoute(roadGraph, place, parcel.address);\n }\n }\n return {direction: route[0], memory: route.slice(1)};\n}", "function pathFindingRobot({place, parcels}, moves){\n\tif (moves.length > 0) return [moves[0], moves.slice(1)];\n\tlet i = parcels.findIndex(p => place == p.place);\n\tlet newMoves;\n\tif (i > -1){\n\t\tnewMoves = findRoute(roadGraph, place, parcels[i].address);\n\t} else {\n\t\tnewMoves = findRoute(roadGraph, place, parcels[0].place)\n\t}\n\treturn [newMoves[0], newMoves.slice(1)];\n}", "function findClosestN(pt, numberOfResults) {\n var closest = [];\n for (var i = 0; i < gmarkers.length; i++) {\n gmarkers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt, gmarkers[i].getPosition());\n document.getElementById('info').innerHTML += \"process \" + i + \":\" + gmarkers[i].getPosition().toUrlValue(6) + \":\" + gmarkers[i].distance.toFixed(2) + \"<br>\";\n gmarkers[i].setMap(null);\n closest.push(gmarkers[i]);\n }\n closest.sort(sortByDist);\n return closest;\n}", "function nearestParking(lon, lat, callback){\n\tvar url = \"http://localhost:8080/geoserver/sig/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=sig:search_nearest_parking&maxFeatures=1&outputFormat=application/json&viewparams=lon:\" + lon + \";lat:\" + lat;\n\t\n\t$.ajax({\n url: url,\n datatype: 'json',\n success: function(json){\n \tcallback(json.features[0].geometry.coordinates);\n \t}\n\t});\n}", "function getNeighbours(trainingSet, testInstance, k)\n{\n var distances = []\n var list_testInstance = listify(testInstance);\n // console.log(list_testInstance);\n // console.log(\"here\")\n\n for (partner of trainingSet)\n {\n var name = partner.firstName\n list_trainingSet = listify(partner);\n // console.log(list_trainingSet);\n dist = euclideanDistance(list_testInstance, list_trainingSet);\n distances.push([name, dist])\n }\n // console.log('// ----------------------------------------------------')\n \n// sort distances by order of magnitude\nvar distancesSorted = distances.sort(function (a, b)\n{\n return a[1] - b[1];\n});\n// console.log(distancesSorted)\n//console.log('// ----------------------------------------------------')\nvar neighbours = []\nvar counter = 0\n// return top k neighbours\nwhile (counter < k)\n{\n if (counter >= distancesSorted.length) break\n if (!Object.is(distancesSorted[counter], undefined)) \n { \n var element = distancesSorted[counter];\n var obj = {id: String, match: Number, rank: Number}\n obj = {id:element[0],match: element[1], rank: counter + 1};\n neighbours.push(obj);\n \n }\n counter++;\n}\nreturn neighbours;\n}", "function findCandidatePair () {\n if (self.destroyed) return\n\n self.getStats(function (err, items) {\n if (self.destroyed) return\n\n // Treat getStats error as non-fatal. It's not essential.\n if (err) items = []\n\n var remoteCandidates = {}\n var localCandidates = {}\n var candidatePairs = {}\n var foundSelectedCandidatePair = false\n\n items.forEach(function (item) {\n // TODO: Once all browsers support the hyphenated stats report types, remove\n // the non-hypenated ones\n if (item.type === 'remotecandidate' || item.type === 'remote-candidate') {\n remoteCandidates[item.id] = item\n }\n if (item.type === 'localcandidate' || item.type === 'local-candidate') {\n localCandidates[item.id] = item\n }\n if (item.type === 'candidatepair' || item.type === 'candidate-pair') {\n candidatePairs[item.id] = item\n }\n })\n\n items.forEach(function (item) {\n // Spec-compliant\n if (item.type === 'transport' && item.selectedCandidatePairId) {\n setSelectedCandidatePair(candidatePairs[item.selectedCandidatePairId])\n }\n\n // Old implementations\n if (\n (item.type === 'googCandidatePair' && item.googActiveConnection === 'true') ||\n ((item.type === 'candidatepair' || item.type === 'candidate-pair') && item.selected)\n ) {\n setSelectedCandidatePair(item)\n }\n })\n\n function setSelectedCandidatePair (selectedCandidatePair) {\n foundSelectedCandidatePair = true\n\n var local = localCandidates[selectedCandidatePair.localCandidateId]\n\n if (local && (local.ip || local.address)) {\n // Spec\n self.localAddress = local.ip || local.address\n self.localPort = Number(local.port)\n } else if (local && local.ipAddress) {\n // Firefox\n self.localAddress = local.ipAddress\n self.localPort = Number(local.portNumber)\n } else if (typeof selectedCandidatePair.googLocalAddress === 'string') {\n // TODO: remove this once Chrome 58 is released\n local = selectedCandidatePair.googLocalAddress.split(':')\n self.localAddress = local[0]\n self.localPort = Number(local[1])\n }\n if (self.localAddress) {\n self.localFamily = self.localAddress.includes(':') ? 'IPv6' : 'IPv4'\n }\n\n var remote = remoteCandidates[selectedCandidatePair.remoteCandidateId]\n\n if (remote && (remote.ip || remote.address)) {\n // Spec\n self.remoteAddress = remote.ip || remote.address\n self.remotePort = Number(remote.port)\n } else if (remote && remote.ipAddress) {\n // Firefox\n self.remoteAddress = remote.ipAddress\n self.remotePort = Number(remote.portNumber)\n } else if (typeof selectedCandidatePair.googRemoteAddress === 'string') {\n // TODO: remove this once Chrome 58 is released\n remote = selectedCandidatePair.googRemoteAddress.split(':')\n self.remoteAddress = remote[0]\n self.remotePort = Number(remote[1])\n }\n if (self.remoteAddress) {\n self.remoteFamily = self.remoteAddress.includes(':') ? 'IPv6' : 'IPv4'\n }\n\n self._debug(\n 'connect local: %s:%s remote: %s:%s',\n self.localAddress, self.localPort, self.remoteAddress, self.remotePort\n )\n }\n\n // Ignore candidate pair selection in browsers like Safari 11 that do not have any local or remote candidates\n // But wait until at least 1 candidate pair is available\n if (!foundSelectedCandidatePair && (!Object.keys(candidatePairs).length || Object.keys(localCandidates).length)) {\n setTimeout(findCandidatePair, 100)\n return\n } else {\n self._connecting = false\n self.connected = true\n }\n\n if (self._chunk) {\n try {\n self.send(self._chunk)\n } catch (err) {\n return self.destroy(makeError(err, 'ERR_DATA_CHANNEL'))\n }\n self._chunk = null\n self._debug('sent chunk from \"write before connect\"')\n\n var cb = self._cb\n self._cb = null\n cb(null)\n }\n\n // If `bufferedAmountLowThreshold` and 'onbufferedamountlow' are unsupported,\n // fallback to using setInterval to implement backpressure.\n if (typeof self._channel.bufferedAmountLowThreshold !== 'number') {\n self._interval = setInterval(function () { self._onInterval() }, 150)\n if (self._interval.unref) self._interval.unref()\n }\n\n self._debug('connect')\n self.emit('connect')\n })\n }", "function addPriority (finalCarObj, input) {\n Object.keys(input.priority).map((passenger) => {\n let priDriver = Object.keys(input.priority[passenger].driver)[0];\n input.drivers[priDriver].spots++;\n finalCarObj[priDriver].spots++;\n finalCarObj[priDriver].current.push({\n Passenger: passenger,\n Time: Object.values(input.priority[passenger])[0],\n });\n });\n return finalCarObj;\n}", "function updateVehicles() {\n\t\t\tcar.update();\n\t\tif(car.x() < 300)\n\t\t\tcar.driveForward(5);\n\t\t\n\t\t\n\t\t\n\t\tfor(var i in cops) {\n\t\t\tif(streak >= 6) {\n\t\t\t\tcops[i].update(car.y()-20-(i*30));\n\t\t\t\tif(cops[i].x() < car.x()-220-(i*20))\n\t\t\t\t\tcops[i].driveForward(5);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcops[i].driveBack(speed*5);\n\t\t\t}\n\t\t}\n\t}", "function PlanRoad (start, end)\n{\n //Check if road is already known\n var roadIsKnown = false;\n var knownRoads = start.room.memory.roomInfo.knownRoads;\n\n if ( knownRoads && knownRoads.length > 0)\n {\n for ( let n in knownRoads )\n {\n var knownRoad = knownRoads[n];\n if ( knownRoad.start.x == start.pos.x && knownRoad.start.y == start.pos.y && knownRoad.end.x == end.pos.x && knownRoad.end.y == end.pos.y )\n {\n roadIsKnown = true;\n }\n }\n }\n // If not a known road, plan it.\n if ( !roadIsKnown )\n {\n var road = {};\n\n // Special case, if start and end are the same, build a road around the object\n // otherwise plan one from start to end\n if (start == end )\n {\n console.log('control.Construction.PlanRoad: Around Position: ' + start.pos );\n\n road = getSurroundingPositions(start) ;\n\n }\n else\n {\n console.log('control.Construction.PlanRoad: start: ' + start + ' - position: ' + start.pos );\n console.log('control.Construction.PlanRoad: end: ' + end + ' - position: ' + end.pos );\n\n road = PathFinder.search(start.pos, { pos: end.pos, range: 1 }) ;\n }\n for ( let n in road.path )\n {\n var buildPosition = road.path[n];\n start.room.memory.roomInfo.futureConstructionSites.push({position: buildPosition, structure: STRUCTURE_ROAD})\n }\n\n start.room.memory.roomInfo.knownRoads.push({start: start.pos, end: end.pos });\n }\n\n // Set a return value, so the caller knows if we did anything\n return (!roadIsKnown);\n}", "_computePlayerClosestToBall() {\n\n\t\tconst ball = this.ball;\n\t\tconst players = this.children;\n\n\t\tlet closestDistance = Infinity;\n\n\t\tfor ( let i = 0, l = players.length; i < l; i ++ ) {\n\n\t\t\tconst player = players[ i ];\n\n\t\t\tconst distance = player.position.squaredDistanceTo( ball.position );\n\n\t\t\tif ( distance < closestDistance ) {\n\n\t\t\t\tclosestDistance = distance;\n\n\t\t\t\tthis.playerClosestToBall = player;\n\n\t\t\t}\n\n\t\t}\n\n\t}", "function parliamentViewPositions() {\n const seats = []\n const { maxSeatNumber, nRows, b } = calcMaxSeatNumber(opts)\n const rowWidth = (opts.outerParliamentRadius - opts.innerParliementRadius) / nRows\n const seatsToRemove = maxSeatNumber - opts.nSeats\n let k = 0\n for (let i = 0; i < nRows; i++) {\n const rowRadius = opts.innerParliementRadius + rowWidth * (i + 0.5)\n const rowSeats = opts.aligned\n ? Math.ceil(opts.nSeats / nRows)\n : Math.floor(Math.PI * (b + i))\n - Math.floor(seatsToRemove / nRows)\n - (seatsToRemove % nRows > i ? 1 : 0)\n\n const anglePerSeat = Math.PI / rowSeats\n for (let j = 0; j < rowSeats; j++) {\n if (k >= opts.nSeats) break\n const s = {}\n s.polar = {\n rw: rowWidth,\n r: rowRadius,\n teta: -Math.PI + anglePerSeat * (j + 0.5),\n }\n s.rotation = 180 / (rowSeats - 1) * j\n s.cartesian = {\n x: s.polar.r * Math.cos(s.polar.teta),\n y: s.polar.r * Math.sin(s.polar.teta),\n }\n seats.push(s)\n k++\n }\n }\n /* sort the seats by angle */\n seats.sort((a, b) => a.polar.teta - b.polar.teta || b.polar.r - a.polar.r)\n\n return seats\n }", "join(traveler) {\r\n if (this.capacity > this.passengers.length) {\r\n this.passengers.push(traveler)\r\n //console.log(this.passengers)\r\n }\r\n else {\r\n //alert('Wagon has reached it/s max capacity. Search for another wagon.')\r\n }\r\n }", "function getStocksAndVehicles(trips, timeRange){\n\t// Returns vehicles as objects\n\t// Best one\n\tvar stocks = [];\n\tvar vehicles = [];\n\n stocks.push({\n type : 'inTransit',\n name : 'inTransit',\n id : 'inTransit',\n initial: 0,\n stackOrder: 0,\n values : []\n });\n stocks.push({\n type : 'dispatched',\n name : 'dispatched',\n id : 'dispatched',\n initial: 0,\n stackOrder: 1,\n values : []\n });\n\ttrips.forEach(function(trip) {\n if (stocks.find(d => d.name==trip.start_station)==null) {\n stocks.push({\n type : 'station',\n name : trip.start_station_name,\n id : trip.start_station,\n lat : trip.start_station_lat,\n lng : trip.start_station_lng,\n initial: 0,\n stackOrder: 10,\n values : []\n });\n }\n if (stocks.find(d => d.name==trip.end_station)==null){\n stocks.push({\n type : 'station',\n name : trip.end_station_name,\n id : trip.end_station,\n lat : trip.end_station_lat,\n lng : trip.end_station_lng,\n initial: 0,\n stackOrder: 10,\n values : []\n });\n }\n\t\tif (vehicles.find(d => d.vehicle_id == trip.bikeid)==null) {\n\t\t\tvehicles.push({vehicle_id : trip.bikeid});\n\t\t\tstocks.find(d => d.name==trip.start_station).initial++;\n\t\t}\n\t\tif(trip.start_date<=timeRange[0]){\n\t\t\tif(trip.type==\"full\") stocks.find(function(d){return d.name=='inTransit'}).initial++;\n\t\t\tif(trip.type==\"empty\") stocks.find(function(d){return d.name=='dispatched'}).initial++;\n\t\t}\n\t});\n\treturn {\n\t\tstocks: stocks,\n\t\tvehicles: vehicles\n\t}\n}", "function find_closest_asset_address(player_enter_x, player_enter_z) {\n var closest_distance = 9999999;\n\n var closet_coor = null;\n\n // for each coordinate our coordinate map\n for (var i = 0; i < coordinate_map.length; i++) {\n var coor = coordinate_map[i]\n\n // determine the distance from that coordinate to the player enter position\n var distance = find_distance(player_enter_x, player_enter_z, coor.x, coor.z)\n\n // if this coordinate is closer set it as our closest\n if (distance < closest_distance) {\n closest_distance = distance\n closet_coor = coor;\n }\n }\n\n // return the address of the closest coordinate\n if (closet_coor != null) {\n return closet_coor.address\n } else {\n return \"\";\n }\n}", "function closest(points, k) {\n var arr = []\n for(var i =0 ; i<points.length ; i++) {\n var obj = {}\n var x = points[i][0]\n var y = points[i][1]\n\n var distance = Math.sqrt(x*x + y*y)\n\n obj['coordinates'] = points[i]\n obj['distance'] = distance\n\n arr.push(obj)\n }\n\n var sortedArr = arr.sort((a,b) => {\n return a.distance - b.distance\n })\n\n var arrResult = []\n\n for(var i =0 ; i < k ; i ++) {\n arrResult.push(sortedArr[i]['coordinates'])\n }\n\n return arrResult\n\n}", "function addSplitComport(object)\n{\n object.focus = m_midPts(gameobjects[0][0], gameobjects[0][1]);\n object.distMin = 100;\n\n object.comport = function()\n {\n object.focus = m_midPts(gameobjects[0][0], gameobjects[0][1]);\n\n if(m_dist(object, object.focus) <= object.distMin)\n {\n gameobjects[2].push(new Ennemy({x: this.x, y: this.y, focus: gameobjects[0][0]}));\n gameobjects[2].push(new Ennemy({x: this.x, y: this.y, focus: gameobjects[0][1]}));\n\n object.toDestroy = true;\n }\n }\n}", "function assignTrips() {\n // First, get all currently unassigned trips\n return db.getNewTrips()\n .then((trips) => {\n // Iterating over trips in series to avoid having the same driver assigned to multiple trips\n // This is okay the purposes of this example, but may be too slow when dealing with high volumes of trips and drivers\n bluebird.mapSeries(trips, trip =>\n // For each trip, get a list of candidate drivers\n db.getCandidateDriversForTrip(trip.rowid)\n .then((drivers) => {\n if (drivers.length === 0) {\n return Promise.resolve();\n }\n const mode = 'fastest;car;traffic:enabled';\n const starts = drivers.map(driver => ({ lat: driver.latitude, lon: driver.longitude }));\n const destinations = [{ lat: trip.pickup_latitude, lon: trip.pickup_longitude }];\n // Then calculate an ETA matrix from the drivers' locations to the pickup location\n return matrixrouting.getEtaMatrix(starts, destinations, mode)\n // Then find the closest driver\n .then(matrix => getClosestDriver(drivers, matrix))\n // Then assign the closest driver to the trip\n // You can insert your more complex matchmaking algorithm here as this logic is fairly primitive\n .then(closestDriver => db.assignDriverToTrip(trip.rowid, closestDriver));\n }));\n });\n}", "function requestPlaces(location) {\n var request = {\n location: location,\n types: ['park'],\n rankBy: google.maps.places.RankBy.DISTANCE\n };\n \n var service = new google.maps.places.PlacesService(map);\n service.search(request, callback);\n }", "function nearestToilet(latitude, longitude) {\r\n var mindif = 99999;\r\n var closest;\r\n\r\n for (index = 0; index < cities.length; ++index) {\r\n var dif = pythagorasEquirectangular(latitude, longitude, cities[index][1], cities[index][2]);\r\n if (dif < mindif) {\r\n closest = index;\r\n mindif = dif;\r\n }\r\n }\r\n // echo the nearest city\r\n alert(cities[closest]);\r\n}", "function findCandidatePair () {\n if (self.destroyed) return\n\n self.getStats(function (err, items) {\n if (self.destroyed) return\n\n // Treat getStats error as non-fatal. It's not essential.\n if (err) items = []\n\n var remoteCandidates = {}\n var localCandidates = {}\n var candidatePairs = {}\n var foundSelectedCandidatePair = false\n\n items.forEach(function (item) {\n // TODO: Once all browsers support the hyphenated stats report types, remove\n // the non-hypenated ones\n if (item.type === 'remotecandidate' || item.type === 'remote-candidate') {\n remoteCandidates[item.id] = item\n }\n if (item.type === 'localcandidate' || item.type === 'local-candidate') {\n localCandidates[item.id] = item\n }\n if (item.type === 'candidatepair' || item.type === 'candidate-pair') {\n candidatePairs[item.id] = item\n }\n })\n\n items.forEach(function (item) {\n // Spec-compliant\n if (item.type === 'transport') {\n setSelectedCandidatePair(candidatePairs[item.selectedCandidatePairId])\n }\n\n // Old implementations\n if (\n (item.type === 'googCandidatePair' && item.googActiveConnection === 'true') ||\n ((item.type === 'candidatepair' || item.type === 'candidate-pair') && item.selected)\n ) {\n setSelectedCandidatePair(item)\n }\n })\n\n function setSelectedCandidatePair (selectedCandidatePair) {\n foundSelectedCandidatePair = true\n\n var local = localCandidates[selectedCandidatePair.localCandidateId]\n\n if (local && local.ip) {\n // Spec\n self.localAddress = local.ip\n self.localPort = Number(local.port)\n } else if (local && local.ipAddress) {\n // Firefox\n self.localAddress = local.ipAddress\n self.localPort = Number(local.portNumber)\n } else if (typeof selectedCandidatePair.googLocalAddress === 'string') {\n // TODO: remove this once Chrome 58 is released\n local = selectedCandidatePair.googLocalAddress.split(':')\n self.localAddress = local[0]\n self.localPort = Number(local[1])\n }\n\n var remote = remoteCandidates[selectedCandidatePair.remoteCandidateId]\n\n if (remote && remote.ip) {\n // Spec\n self.remoteAddress = remote.ip\n self.remotePort = Number(remote.port)\n } else if (remote && remote.ipAddress) {\n // Firefox\n self.remoteAddress = remote.ipAddress\n self.remotePort = Number(remote.portNumber)\n } else if (typeof selectedCandidatePair.googRemoteAddress === 'string') {\n // TODO: remove this once Chrome 58 is released\n remote = selectedCandidatePair.googRemoteAddress.split(':')\n self.remoteAddress = remote[0]\n self.remotePort = Number(remote[1])\n }\n self.remoteFamily = 'IPv4'\n\n self._debug(\n 'connect local: %s:%s remote: %s:%s',\n self.localAddress, self.localPort, self.remoteAddress, self.remotePort\n )\n }\n\n // Ignore candidate pair selection in browsers like Safari 11 that do not have any local or remote candidates\n // But wait until at least 1 candidate pair is available\n if (!foundSelectedCandidatePair && (!Object.keys(candidatePairs).length || Object.keys(localCandidates).length)) {\n setTimeout(findCandidatePair, 100)\n return\n } else {\n self._connecting = false\n self.connected = true\n }\n\n if (self._chunk) {\n try {\n self.send(self._chunk)\n } catch (err) {\n return self._destroy(err)\n }\n self._chunk = null\n self._debug('sent chunk from \"write before connect\"')\n\n var cb = self._cb\n self._cb = null\n cb(null)\n }\n\n // If `bufferedAmountLowThreshold` and 'onbufferedamountlow' are unsupported,\n // fallback to using setInterval to implement backpressure.\n if (typeof self._channel.bufferedAmountLowThreshold !== 'number') {\n self._interval = setInterval(function () { self._onInterval() }, 150)\n if (self._interval.unref) self._interval.unref()\n }\n\n self._debug('connect')\n self.emit('connect')\n })\n }", "function findCandidatePair () {\n if (self.destroyed) return\n\n self.getStats(function (err, items) {\n if (self.destroyed) return\n\n // Treat getStats error as non-fatal. It's not essential.\n if (err) items = []\n\n var remoteCandidates = {}\n var localCandidates = {}\n var candidatePairs = {}\n var foundSelectedCandidatePair = false\n\n items.forEach(function (item) {\n // TODO: Once all browsers support the hyphenated stats report types, remove\n // the non-hypenated ones\n if (item.type === 'remotecandidate' || item.type === 'remote-candidate') {\n remoteCandidates[item.id] = item\n }\n if (item.type === 'localcandidate' || item.type === 'local-candidate') {\n localCandidates[item.id] = item\n }\n if (item.type === 'candidatepair' || item.type === 'candidate-pair') {\n candidatePairs[item.id] = item\n }\n })\n\n items.forEach(function (item) {\n // Spec-compliant\n if (item.type === 'transport') {\n setSelectedCandidatePair(candidatePairs[item.selectedCandidatePairId])\n }\n\n // Old implementations\n if (\n (item.type === 'googCandidatePair' && item.googActiveConnection === 'true') ||\n ((item.type === 'candidatepair' || item.type === 'candidate-pair') && item.selected)\n ) {\n setSelectedCandidatePair(item)\n }\n })\n\n function setSelectedCandidatePair (selectedCandidatePair) {\n foundSelectedCandidatePair = true\n\n var local = localCandidates[selectedCandidatePair.localCandidateId]\n\n if (local && local.ip) {\n // Spec\n self.localAddress = local.ip\n self.localPort = Number(local.port)\n } else if (local && local.ipAddress) {\n // Firefox\n self.localAddress = local.ipAddress\n self.localPort = Number(local.portNumber)\n } else if (typeof selectedCandidatePair.googLocalAddress === 'string') {\n // TODO: remove this once Chrome 58 is released\n local = selectedCandidatePair.googLocalAddress.split(':')\n self.localAddress = local[0]\n self.localPort = Number(local[1])\n }\n\n var remote = remoteCandidates[selectedCandidatePair.remoteCandidateId]\n\n if (remote && remote.ip) {\n // Spec\n self.remoteAddress = remote.ip\n self.remotePort = Number(remote.port)\n } else if (remote && remote.ipAddress) {\n // Firefox\n self.remoteAddress = remote.ipAddress\n self.remotePort = Number(remote.portNumber)\n } else if (typeof selectedCandidatePair.googRemoteAddress === 'string') {\n // TODO: remove this once Chrome 58 is released\n remote = selectedCandidatePair.googRemoteAddress.split(':')\n self.remoteAddress = remote[0]\n self.remotePort = Number(remote[1])\n }\n self.remoteFamily = 'IPv4'\n\n self._debug(\n 'connect local: %s:%s remote: %s:%s',\n self.localAddress, self.localPort, self.remoteAddress, self.remotePort\n )\n }\n\n if (!foundSelectedCandidatePair && items.length) {\n setTimeout(findCandidatePair, 100)\n return\n } else {\n self._connecting = false\n self.connected = true\n }\n\n if (self._chunk) {\n try {\n self.send(self._chunk)\n } catch (err) {\n return self._destroy(err)\n }\n self._chunk = null\n self._debug('sent chunk from \"write before connect\"')\n\n var cb = self._cb\n self._cb = null\n cb(null)\n }\n\n // If `bufferedAmountLowThreshold` and 'onbufferedamountlow' are unsupported,\n // fallback to using setInterval to implement backpressure.\n if (typeof self._channel.bufferedAmountLowThreshold !== 'number') {\n self._interval = setInterval(function () { self._onInterval() }, 150)\n if (self._interval.unref) self._interval.unref()\n }\n\n self._debug('connect')\n self.emit('connect')\n if (self._earlyMessage) { // HACK: Workaround for Chrome not firing \"open\" between tabs\n self._onChannelMessage(self._earlyMessage)\n self._earlyMessage = null\n }\n })\n }", "function DetectNearbyWorkers() {\n\t// Find all objects within the game.\n\tvar detectedStructures = Physics.OverlapSphere(transform.position, 100);\n\tvar dist : float = 2000000;\n\tvar minGO : GameObject;\n\t// Loop through to find worker with minimum distance.\n\tfor (var i = 0; i < detectedStructures.Length; i++) {\n\t\tvar x : Collider = detectedStructures[i];\n\t\tif ( x.gameObject.tag == \"Worker\" ) {\n\t\t\t// Detected nearby worker\n\t\t\tvar curDist : float = Vector3.Distance(transform.position, x.transform.position);\n\t\t\tif ( curDist < dist ) {\n\t\t\t\tdist = curDist;\n\t\t\t\tminGO = x.gameObject;\n\t\t\t}\n\t\t}\n\t}\n\t// If cannot find return -1.\n\tif ( dist == 2000000 ) return -1;\n\telse return minGO;\n}", "function mapVehicles(routeList) {\r\n /* clear current vehicle markers before updating with new ones, else end\r\n\tup with vehicle markers in old and new locations. */\r\n while (markerArray.length > 0) {\r\n var m = markerArray.pop();\r\n m.setMap(null);\r\n }\r\n /* add vehicle markers for user-selected routeList */\r\n $.each(routeList, function(index, route) {\r\n /* retrieve location data for vehicles on this route */\r\n $.getJSON(PHP_URL + \"getvehruns.php?id=\" + route, function(data) {\r\n var vehList = data.items; // extract the list of vehicles\r\n\t/* create a marker for each vehicle */\r\n\t$.each(vehList, function(index, vehicle) {\r\n var marker;\r\n\t var dirName; // name to display for vehicle direction\r\n\t // some vehicles have no run names, or their run # has no defined name\r\n\t if (vehicle.run_name == null || vehicle.run_name == undefined) {\r\n\t\tdirName = \"#\"+vehicle.run_id;\r\n\t }\r\n\t else { // have a run name, so display it\r\n\t\tdirName = vehicle.run_name; \r\n\t };\r\n\t text = 'direction: ' + dirName + ', vehicle#: ' + vehicle.id;\r\n \t marker = new google.maps.Marker({\r\n position: new google.maps.LatLng(vehicle.latitude, vehicle.longitude),\r\n map: map,\r\n title: text,\r\n\t\ticon: bus_icons[vehicle.dir_name] \r\n });\r\n\t marker.setMap(map);\r\n\t markerArray.push(marker);\r\n\t});\r\n });\r\n });\r\n}", "function closestPointToLine3D(a,b,p,out){\n\tif(out == undefined) out = new Vec3();\n\tvar dx\t= b.x - a.x,\n\t\tdy\t= b.y - a.y,\n\t\tdz\t= a.z - a.z,\n\t\tt\t= ((p.x-a.x)*dx + (p.y-a.y)*dy + (p.z-a.z)*dz) / (dx*dx+dy*dy+dz*dz),\n\t\tx\t= a.x + (dx * t),\n\t\ty\t= a.y + (dy * t),\n\t\tz\t= a.z + (dz * t);\n\treturn out.set(x,y,z);\n}", "function findCandidatePair() {\n if (self.destroyed) return;\n\n self.getStats(function (err, items) {\n if (self.destroyed) return;\n\n // Treat getStats error as non-fatal. It's not essential.\n if (err) items = [];\n\n var remoteCandidates = {};\n var localCandidates = {};\n var candidatePairs = {};\n var foundSelectedCandidatePair = false;\n\n items.forEach(function (item) {\n // TODO: Once all browsers support the hyphenated stats report types, remove\n // the non-hypenated ones\n if (item.type === 'remotecandidate' || item.type === 'remote-candidate') {\n remoteCandidates[item.id] = item;\n }\n if (item.type === 'localcandidate' || item.type === 'local-candidate') {\n localCandidates[item.id] = item;\n }\n if (item.type === 'candidatepair' || item.type === 'candidate-pair') {\n candidatePairs[item.id] = item;\n }\n });\n\n items.forEach(function (item) {\n // Spec-compliant\n if (item.type === 'transport') {\n setSelectedCandidatePair(candidatePairs[item.selectedCandidatePairId]);\n }\n\n // Old implementations\n if (item.type === 'googCandidatePair' && item.googActiveConnection === 'true' || (item.type === 'candidatepair' || item.type === 'candidate-pair') && item.selected) {\n setSelectedCandidatePair(item);\n }\n });\n\n function setSelectedCandidatePair(selectedCandidatePair) {\n foundSelectedCandidatePair = true;\n\n var local = localCandidates[selectedCandidatePair.localCandidateId];\n\n if (local && local.ip) {\n // Spec\n self.localAddress = local.ip;\n self.localPort = Number(local.port);\n } else if (local && local.ipAddress) {\n // Firefox\n self.localAddress = local.ipAddress;\n self.localPort = Number(local.portNumber);\n } else if (typeof selectedCandidatePair.googLocalAddress === 'string') {\n // TODO: remove this once Chrome 58 is released\n local = selectedCandidatePair.googLocalAddress.split(':');\n self.localAddress = local[0];\n self.localPort = Number(local[1]);\n }\n\n var remote = remoteCandidates[selectedCandidatePair.remoteCandidateId];\n\n if (remote && remote.ip) {\n // Spec\n self.remoteAddress = remote.ip;\n self.remotePort = Number(remote.port);\n } else if (remote && remote.ipAddress) {\n // Firefox\n self.remoteAddress = remote.ipAddress;\n self.remotePort = Number(remote.portNumber);\n } else if (typeof selectedCandidatePair.googRemoteAddress === 'string') {\n // TODO: remove this once Chrome 58 is released\n remote = selectedCandidatePair.googRemoteAddress.split(':');\n self.remoteAddress = remote[0];\n self.remotePort = Number(remote[1]);\n }\n self.remoteFamily = 'IPv4';\n\n self._debug('connect local: %s:%s remote: %s:%s', self.localAddress, self.localPort, self.remoteAddress, self.remotePort);\n }\n\n if (!foundSelectedCandidatePair && items.length) {\n setTimeout(findCandidatePair, 100);\n return;\n } else {\n self._connecting = false;\n self.connected = true;\n }\n\n if (self._chunk) {\n try {\n self.send(self._chunk);\n } catch (err) {\n return self._destroy(err);\n }\n self._chunk = null;\n self._debug('sent chunk from \"write before connect\"');\n\n var cb = self._cb;\n self._cb = null;\n cb(null);\n }\n\n // If `bufferedAmountLowThreshold` and 'onbufferedamountlow' are unsupported,\n // fallback to using setInterval to implement backpressure.\n if (typeof self._channel.bufferedAmountLowThreshold !== 'number') {\n self._interval = setInterval(function () {\n self._onInterval();\n }, 150);\n if (self._interval.unref) self._interval.unref();\n }\n\n self._debug('connect');\n self.emit('connect');\n if (self._earlyMessage) {\n // HACK: Workaround for Chrome not firing \"open\" between tabs\n self._onChannelMessage(self._earlyMessage);\n self._earlyMessage = null;\n }\n });\n }", "function bruteforce (coordinateList) {\n let distance, shortest\n\n let useCache = process.env.DISTANCE_CACHE_ENABLED\n\n for (let i=0; i < coordinateList.length; i++) {\n if (coordinateList[i].error) continue; // skip - if location lookup had an error\n shortest = Infinity\n for (let j=0; j < coordinateList.length; j++) {\n if (coordinateList[j].error) continue; // skip - if location lookup had an error\n if (i == j) continue; // skip - since the distance to self will be 0\n distance = haversine(coordinateList[i], coordinateList[j], useCache)\n if (distance < shortest && distance > 0) {\n shortest = distance\n coordinateList[i].match = coordinateList[j].name\n }\n }\n }\n\n return coordinateList\n}", "findNearestCollision(boxes, to_ignore){\n var closest_box = null;\n var lowest_mag = this.trajectory.getMagnitude();\n for(var b of boxes){\n if(b == to_ignore){ continue;}\n //use fast/efficient method before the most costly point-finding algorithm\n if(this.trajectory.checkBoxIntersect(b)){\n var collision_point = this.trajectory.boxIntersectAt(b);\n if(!collision_point){\n console.log(\"A collision was detected but no intersection point \\\n was found. There must be a bug.\");\n }\n var old_end_point = this.trajectory.end;\n this.trajectory.end = collision_point;\n var new_mag = this.trajectory.getMagnitude();\n if(new_mag < lowest_mag){\n lowest_mag = new_mag;\n closest_box = b;\n }\n else{\n this.trajectory.end = old_end_point;\n }\n }\n }\n return closest_box;\n }", "function findPlat(){\n\t//console.log(inlinePlat);\n\tfor(var i = 0; i < plats.length; i++){\n\t\tcurPlat = plats[i];\n\t\tif(player1.x >= curPlat[1]+diff && player1.x+40 <= curPlat[2]+diff){\n\t\t\tinlinePlat = true;\n\t\t\tplatH = curPlat[0];\n\t\t\t//console.log(platV);\n\t\t\tif(player1.y > platH-40){\n\t\t\t\tplatH = height;\n\t\t\t}\n\t\t\tbreak;\n\t\t}else{\n\t\t\tinlinePlat = false;\n\t\t\tplatH = height;\n\t\t}\n\t}\n}", "function apartmentHunting(blocks, reqs) {\n const minDistancesFromBlocks = reqs.map(req => getMinDistances(blocks, req)); // O(br)\n // console.log('This is minDistancesFromBlocks', minDistancesFromBlocks);\n const maxDistancesAtBlocks = getMaxDistancesAtBlocks(blocks, minDistancesFromBlocks); // O(br)\n // console.log('MaxDistancesAtBlock will be', maxDistancesAtBlocks);\n return getIndexAtMinValue(maxDistancesAtBlocks); // O(br)\n\n}", "function possibleHotelBookings2(arrive, depart, k) {\n arrive.sort((a, b) => a - b);\n depart.sort((a, b) => a - b);\n\n let count = 0;\n let arrivePointer = 0;\n let departPointer = 0;\n let n = arrive.length;\n // console.log(arrive, depart)\n\n while (arrivePointer < n && departPointer < n) {\n // check the min\n if (arrive[arrivePointer] < depart[departPointer]) {\n arrivePointer++;\n count++;\n\n if (count > k) return false;\n } else {\n departPointer++;\n count--;\n }\n }\n return true;\n}", "join (traveler) {\n if (this.getAvailableSeatCount () > 0) {\n this.passengerList.push (traveler);\n } \n }", "function cutTripsByDistance(driverTrip, riderTrips) {\n\tlet riderTripsDistance = [];\n\n\tif (typeof riderTrips === \"undefined\" || driverTrip === \"undefined\") {\n\t\treturn [];\n\t}\n\n\tlet newDriverRoute = driverTrip.tripRoute;\n\n\triderTrips.forEach(function(riderTrip) {\n\t\tlet newRiderRoute = riderTrip.tripRoute;\n\t\tlet riderDistanceStart = LatLng.getLatLngShortestDistanceLinePoint(\n\t\t\tnewDriverRoute.routes[0].legs[0].start_location.lat,\n\t\t\tnewDriverRoute.routes[0].legs[0].start_location.lng,\n\t\t\tnewDriverRoute.routes[0].legs[newDriverRoute.routes[0].legs.length - 1].end_location.lat,\n\t\t\tnewDriverRoute.routes[0].legs[newDriverRoute.routes[0].legs.length - 1].end_location.lng,\n\t\t\tnewRiderRoute.routes[0].legs[0].start_location.lat,\n\t\t\tnewRiderRoute.routes[0].legs[0].start_location.lng\n\t\t);\n\t\tlet riderDistanceEnd = LatLng.getLatLngShortestDistanceLinePoint(\n\t\t\tnewDriverRoute.routes[0].legs[0].start_location.lat,\n\t\t\tnewDriverRoute.routes[0].legs[0].start_location.lng,\n\t\t\tnewDriverRoute.routes[0].legs[newDriverRoute.routes[0].legs.length - 1].end_location.lat,\n\t\t\tnewDriverRoute.routes[0].legs[newDriverRoute.routes[0].legs.length - 1].end_location.lng,\n\t\t\tnewRiderRoute.routes[0].legs[0].end_location.lat,\n\t\t\tnewRiderRoute.routes[0].legs[0].end_location.lng\n\t\t);\n\n\t\tif (riderDistanceStart + riderDistanceEnd <= MaxDriverDistanceDiff) {\n\t\t\triderTripsDistance.push(riderTrip);\n\t\t}\n\t});\n\n\treturn riderTripsDistance;\n}", "function moveEverything() {\n updateTrack();\n p1.carMove();\n\n if (currentScore >= currentScoreGoal)\n {\n if (stageNow < stageTuning.length - 1){\n levelUp(false);\n }\n else {\n attractLoop = true;\n }\n }\n\n if (trafficCars.length < stageTuning[stageNow].maxCars && Math.random() < stageTuning[stageNow].spawnFreq) {\n spawnTrafficCar();\n }\n\n // Car collisions below\n for (var i = 0; i < trafficCars.length; i ++) {\n for (var ii = i+1; ii < trafficCars.length; ii ++) {\n var laneDiff = Math.abs(trafficCars[i].lanePerc - trafficCars[ii].lanePerc);\n\n if (laneDiff < 0.1) {\n var yDiff = Math.abs(trafficCars[i].y - trafficCars[ii].y);\n\n if (yDiff <= CLOSE_ENOUGH_TO_AVOID) {\n var futureYDiff = Math.abs((trafficCars[i].y - trafficCars[i].speed) - \n (trafficCars[ii].y - trafficCars[ii].speed));\n if (yDiff > futureYDiff) {\n var tempSpeedI = trafficCars[i].speed;\n\n trafficCars[i].speed = trafficCars[ii].speed;\n trafficCars[ii].speed = tempSpeedI;\n //console.log(\"bumped\" + i + \" : \" + ii);\n }\n }\n }\n }\n }\n\n // Updating car positions\n for (var i = 0; i < trafficCars.length; i ++) {\n trafficCars[i].move();\n }\n\n for (var i = trafficCars.length-1; i >= 0; i--) {\n if (trafficCars[i].readyToRemove) {\n trafficCars.splice(i, 1);\n }\n }\n\n // Updating point popper positions\n for (var i = 0; i < pointPoppers.length; i ++) {\n pointPoppers[i].move();\n }\n\n for (var i = pointPoppers.length-1; i >= 0; i--) {\n if (pointPoppers[i].readyToRemove) {\n pointPoppers.splice(i, 1);\n }\n }\n}", "closest(points) {\n if (points.length === 1) {\n return Point.create(points[0]);\n }\n let ret = null;\n let min = Infinity;\n points.forEach((p) => {\n const dist = this.squaredDistance(p);\n if (dist < min) {\n ret = p;\n min = dist;\n }\n });\n return ret ? Point.create(ret) : null;\n }", "function Park(data) {\n this.name = data.name;\n this.description = data.description;\n this.address = `${data.addresses[0].linel} ${data.addresses[0].city} ${data.addresses[0].linel} ${data.addresses[0].statecode} ${data.addresses[0].postalcode} `;\n this.fee = data.fees[0] || '0.00';\n this.Park_url = data.url;\n}", "function closestPath(waypoint){\n var pathDistances = [];\n var percentage = [];\n for (var i=0; i<vm.trailPath.length-1; i++){\n let a = spherical.computeDistanceBetween(waypoint, vm.trailPath[i+1]);\n let b = spherical.computeDistanceBetween(waypoint, vm.trailPath[i]);\n let c = spherical.computeDistanceBetween(vm.trailPath[i], vm.trailPath[i+1]);\n let A = Math.acos(Math.min((Math.pow(b,2)+Math.pow(c,2)-Math.pow(a,2))/(2*b*c), 1));\n let B = Math.acos(Math.min((Math.pow(c,2)+Math.pow(a,2)-Math.pow(b,2))/(2*a*c), 1));\n let C = Math.PI-B-A;\n\n if (A > (Math.PI/2)){\n pathDistances[i] = b;\n percentage[i]=0;\n } else if (B > (Math.PI/2)){\n pathDistances[i] = a;\n percentage[i]=1;\n } else {\n pathDistances[i] = a*Math.sin(B);\n percentage[i]=Math.sqrt(Math.pow(b,2) - Math.pow(pathDistances[i],2))/c;\n }\n }\n let minIndex = pathDistances.reduce((iMin, x, i, arr) => x < arr[iMin] ? i : iMin, 0) + 1;\n let finalPercentage = percentage[minIndex-1];\n let path1 = vm.trailPath.slice(0, [minIndex]);\n let path2 = vm.trailPath.slice(0, [minIndex+1]);\n let distance = (spherical.computeLength(path1)+ (spherical.computeLength(path2) - spherical.computeLength(path1))*finalPercentage)\n * metersMilesConversion;\n\n return [minIndex, finalPercentage, distance];\n}", "function findNearest(lat, lon, amt){\n var nearest = [];\n var all = [];\n var hold = [];\n //trying to remove duplicates from the dataset DOESNT WORK YET\n for(var i = 0; i < data.length; i++){\n for(var j = i+1; j < data.length; j++){\n if(data[i].applicant == data[j].applicant){\n data.splice(j,\"\");\n } \n }\n }\n\n //for each truck find the distance from your position to the truck if longitude exists\n for (var i = 0; i < data.length; i++) {\n if(data[i].longitude != undefined && data[i].latitude != undefined){\n all[i] = distance(data[i].longitude, data[i].latitude, lon, lat);\n }\n }\n //duplicate all array to hold array\n for(var m = 0; m < all.length; m++){\n hold[m] = all[m];\n }\n //sorts the hold array from lowest to highest\n hold.sort(function(a,b){return a-b});\n\n //compares the hold array to the all array. the amt is the number of results wanted. push the \n for(var j = 0; j < amt; j++){\n nearest.push(hold[j]); \n }\n\n //create result array, from the nearest array for each element push the data value to the result array. basically the nearest array is replicated to the result array but the result array holds the information about the truck\n var result = [];\n nearest.forEach(function(value){\n result.push(data[value]);\n });\n return result;\n }", "_checkPrioritiySnapping (closestLayer) {\n const map = this._map\n\n // A and B are the points of the closest segment to P (the marker position we want to snap)\n const A = closestLayer.segment[0]\n const B = closestLayer.segment[1]\n\n // C is the point we would snap to on the segment.\n // The closest point on the closest segment of the closest polygon to P. That's right.\n const C = closestLayer.latlng\n\n // distances from A to C and B to C to check which one is closer to C\n const distanceAC = this._getDistance(map, A, C)\n const distanceBC = this._getDistance(map, B, C)\n\n // closest latlng of A and B to C\n let closestVertexLatLng = distanceAC < distanceBC ? A : B\n\n // distance between closestVertexLatLng and C\n let shortestDistance = distanceAC < distanceBC ? distanceAC : distanceBC\n\n // snap to middle (M) of segment if option is enabled\n if (this.options.snapMiddle) {\n const M = Utils.calcMiddleLatLng(map, A, B)\n const distanceMC = this._getDistance(map, M, C)\n\n if (distanceMC < distanceAC && distanceMC < distanceBC) {\n // M is the nearest vertex\n closestVertexLatLng = M\n shortestDistance = distanceMC\n }\n }\n\n // the distance that needs to be undercut to trigger priority\n const priorityDistance = this.options.snapDistance\n\n // the latlng we ultemately want to snap to\n let snapLatlng\n\n // if C is closer to the closestVertexLatLng (A, B or M) than the snapDistance,\n // the closestVertexLatLng has priority over C as the snapping point.\n if (shortestDistance < priorityDistance) {\n snapLatlng = closestVertexLatLng\n } else {\n snapLatlng = C\n }\n\n // return the copy of snapping point\n return Object.assign({}, snapLatlng)\n }", "moveSlot() {\n if (this.raycaster.ray.intersectPlane(this.plane, this.intersection)) {\n let newPosition = this.intersection.x - this.offset; //Subtracts the offset to the x coordinate of the intersection point\n let leftFace = this.closet.getClosetFaces().get(FaceOrientationEnum.LEFT).mesh();\n let valueCloset = leftFace.position.x;\n if (Math.abs(newPosition) < Math.abs(valueCloset)) { //Doesn't allow the slot to overlap the faces of the closet\n this.selected_slot.position.x = newPosition;\n }\n }\n }", "function pickNext( neighbors ){\n\n //get sum of surrounding pheromones\n let sum = neighbors.reduce( (total, index) => {\n return total + pheromones[index]\n },0)\n\n //if sum is too low then randomly pick\n if(sum < 0.002) {\n return neighbors[Math.floor(Math.random()*neighbors.length)]\n }\n \n //calulate each neighbor's pheromone percentage\n let percentage = neighbors.map( index => {\n return pheromones[index]/sum\n })\n\n //assign percentage with neighbor index\n let neighborObjects = [];\n neighbors.forEach( (n, i)=>{\n neighborObjects.push( {\n index: n,\n percentage: percentage[i]\n })\n } )\n //sort based on percentage\n neighborObjects = neighborObjects.sort( (a,b) => {\n if(b.percentage < a.percentage ) {\n return 1\n } else if( b.percentage > a.percentage ) {\n return -1\n } else {\n return 0\n }\n })\n \n const randomValue = Math.random();\n \n for( let y=0; y<neighborObjects.length; y++){\n if (randomValue < neighborObjects[y].percentage ) {\n return neighborObjects[y].index\n }\n }\n \n //return last index with largest percentage\n return neighborObjects[neighborObjects.length-1].index\n}", "function chooseWarmest() {\n for (var i = 0; i < tempCheckArray.length; i++) {\n // Sort Distances\n tempCheckArray.sort(function(a, b) {\n let varA;\n let varB;\n varA = a[\"temp\"];\n varB = b[\"temp\"];\n if (varA < varB) {\n return 1;\n } else if (varB < varA) {\n return -1;\n }\n return 0;\n });\n }\n warmestAirportLat = tempCheckArray[0][\"latitude\"];\n warmestAirportLon = tempCheckArray[0][\"longitude\"];\n warmLatLon = { \"latitude\": warmestAirportLat, \"longitude\": warmestAirportLon };\n}", "function isVehicleAlreadySpawned(vehData){\n\tif(spawnedVehicles.length > 0){\n\t\tfor(let i in spawnedVehicles){\n\t\t\t// x, y, and game should be enough to pinpoint specific vehicle data from the array.\n\t\t\tif(spawnedVehicles[i].position.x == vehData.x && spawnedVehicles[i].position.y == vehData.y && spawnedVehicles[i].game == vehData.game){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn false;\n}", "function driveIt(vehicle) {\n vehicle.start();\n raceTrack.push(vehicle);\n}", "function find_match(rider, driver, match_callback) {\n const rider_leave_earliest = rider.leave_earliest.getMinutes();\n const rider_leave_latest = rider.leave_latest.getMinutes();\n\n const driver_leave_earliest = driver.leave_earliest.getMinutes();\n const driver_leave_latest = driver.leave_latest.getMinutes();\n\n if (!driver.start_point.equals(rider.start_point) ||\n !same_date(rider, driver) ||\n driver_leave_earliest >= rider_leave_latest ||\n driver_leave_latest <= rider_leave_earliest) {\n match_callback(null, null);\n return;\n }\n\n const connector = (item, callback) => valid_trip(rider, driver, item, callback);\n\n async.map(rider.end_points, connector, (err, res) => {\n if (err) {\n match_callback(err);\n return;\n }\n\n for (let i = 0; i < res.length; i++) {\n if (res[i]) {\n match_callback(null, res[i]);\n return;\n }\n }\n\n match_callback(null, null);\n });\n}", "function _distanceToNearestStreetWithWayType(turfPoint) {\n let streets = svl.taskContainer.getTasks();\n let closestStreet = streets[0];\n let closestDistance = turf.pointToLineDistance(turfPoint, closestStreet.getGeoJSON().features[0]);\n svl.taskContainer.getTasks().forEach(function (street, i) {\n let distance = turf.pointToLineDistance(turfPoint, street.getGeoJSON().features[0]);\n if (distance < closestDistance) {\n closestStreet = street;\n closestDistance = distance;\n }\n });\n return [closestDistance, closestStreet];\n }", "_findSpotPricesForRegion({pricePoints}) {\n debugger;\n let zones = {};\n\n for (let pricePoint of pricePoints) {\n let instanceType = pricePoint.InstanceType;\n let time = new Date(pricePoint.Timestamp);\n let price = toFloat(pricePoint.SpotPrice, 10);\n let zone = pricePoint.AvailabilityZone;\n\n if (!zones[zone]) {\n zones[zone] = {};\n }\n if (!zones[zone][instanceType]) {\n zones[zone][instanceType] = [];\n }\n\n zones[zone][instanceType].push({price, time});\n }\n\n let prices = [];\n\n for (let zone in zones) {\n for (let instanceType in zones[zone]) {\n let price = this._findSpotPriceForInstanceType(zones[zone][instanceType]);\n prices.push({zone, instanceType, price});\n }\n }\n\n return prices;\n }", "function goalOrientedRobot({place, parcels}, route = []) {\n if (route.length == 0) {\n let parcel = parcels[0];\n if (parcel.place != place) {\n route = findRoute(roadGraph, place, parcel.place);\n } else {\n route = findRoute(roadGraph, place, parcel.address);\n }\n }\n return {direction: route[0], memory: route.slice(1)}\n }", "function getWayPts(x, y) {\n // Round to nearest grid point\n [i, j] = Terrain.xyToGrid(x, y);\n [x, y] = Terrain.gridToXY(Math.floor(i), Math.round(j));\n\n var gMaterials = Terrain.getGraph();\n var g = gMaterials[\"g\"];\n var idToXY = gMaterials[\"idToXY\"];\n var destNodeID = gMaterials[\"destNodeID\"];\n\n // Find the starting node ID\n var startNode = \"0\";\n for (var key in idToXY) {\n if (!idToXY.hasOwnProperty(key)) { continue; }\n\n var currPt = idToXY[key];\n var currX = currPt[0];\n var currY = currPt[1];\n // ASSUMPTION HERE that you start on a node location\n if (currX === x && currY === y) {\n startNode = key;\n }\n\n }\n\n function weight (e) {\n return g.edge(e) + Math.random() * 10;\n }\n\n var dijMaterials = graphlib.alg.dijkstra(g, startNode, weight);\n\n // find the nearest destination node\n var minDis = Infinity;\n var minNodeID = \"\";\n for (var i = 0; i < destNodeID.length; i++) {\n var currNodeID = destNodeID[i];\n var currDis = dijMaterials[currNodeID].distance;\n if (currDis < minDis) {\n minDis = currDis;\n minNodeID = currNodeID;\n }\n }\n\n // Find the route to that destination node\n var nodeIdStack = [];\n currNodeID = minNodeID;\n while (dijMaterials[currNodeID].predecessor !== undefined) {\n nodeIdStack.push(currNodeID);\n currNodeID = dijMaterials[currNodeID].predecessor;\n }\n\n // Helper method... wrapper object for mapping nodes back to xy coordinates\n function nodeIDToXY(nodeId) {\n return idToXY[nodeId];\n }\n\n // map node id's to xy\n var wayPtStack = nodeIdStack.map(nodeIDToXY);\n\n return wayPtStack;\n}", "function allocateSeat() {\n let votesTotal = parties.reduce((total, party) => total + party.votes, 0);\n parties = parties.sort((a, b) => b.votesCalculated - a.votesCalculated);\n if (parties[0].votes / votesTotal < threshold) {\n parties[0].votesCalculated = 0;\n allocateSeat();\n }\n parties[0].mpsGranted++;\n parties[0].votesCalculated = parties[0].votes / (parties[0].mpsGranted+1);\n}", "function mapCreatePins(map){\n\tvar bounds = new google.maps.LatLngBounds();\n\tfor (i = 0; i < parklist.length; i++){\n\t\t\tx = i;\n\t\t\ttitle = parklist[i]['Name'];\n\t\t\tvar position = new google.maps.LatLng(parseFloat(parklist[i]['Latitude']), parseFloat(parklist[i]['Longitude']))\n\t\t\tvar marker = new google.maps.Marker({\n\t\t\t\tid: parklist[i]['parkId'],\n\t\t\t\tmap: map,\n\t\t\t\tdraggable: false,\n\t\t\t\tanimation: google.maps.Animation.DROP,\n\t\t\t\tposition: position,\n\t\t\t\ttitle: title\n\t\t\t});\t\t\t\n\t\t\t\n\t\t\turl = window.location.href;\n\t\t\tvar patt = new RegExp('results.php');\t\t\n\t\t\t\n\t\t\t// Creates the Link on the map pins that match the list on the left.\n\t\t\tif (patt.test(url)){\n\t\t\t\tgoogle.maps.event.addListener(marker, 'click', (function(marker, i) {\n\t\t\t\t\treturn function() {\n\t\t\t\t\t\tdocument.forms[i + 1].submit();\n\t\t\t\t\t}\n\t\t\t\t})(marker, i));\n\t\t\t}\t\t\t\t\n\t\t\tbounds.extend(position);\n\t}\n\tif (parklist.length > 3){\n\t\tmap.fitBounds(bounds);\n\t}\n}", "function getParks(input, limit=10) {\r\n const params = {\r\n stateCode: input,\r\n limit,\r\n api_key: apiKey\r\n };\r\n const queryString = formatQueryParams(params)\r\n const url = searchURL + '?' + queryString;\r\n console.log(url)\r\n\r\n fetch(url)\r\n .then(response => {\r\n if(response.ok){\r\n return response.json();\r\n }\r\n throw new Error(response.statusText);\r\n })\r\n .then(responseJson => displayResults(responseJson))\r\n .catch(err => {\r\n $('#js-error-message').text(`Something went wrong: ${err.message}`);\r\n });\r\n}", "function isCarBetweenRoutePoints(routePoints, carPosition) {\n //first: are there two routePoints?\n if (routePoints.length >= 2) {\n //get all routePoints\n fill(255, 0, 0);\n circle(carPosition[0], carPosition[1], 10, 10);\n\n for (let i = 0; i <= routePoints.length - 1; i++) {\n //save every two routePoints\n //if there is one left...\n if (i < routePoints.length - 1) {\n let firstRoutePoint = routePoints[i];\n let secondRoutePoint = routePoints[i + 1];\n\n stroke(255);\n noFill();\n quad(\n routePoints[i][0],\n routePoints[i][1],\n routePoints[i + 1][0],\n routePoints[i][1],\n routePoints[i + 1][0],\n routePoints[i + 1][1],\n routePoints[i][0],\n routePoints[i + 1][1]\n );\n if (\n carPosition[0] >= firstRoutePoint[0] &&\n carPosition[0] <= secondRoutePoint[0] &&\n carPosition[1] >= firstRoutePoint[1] &&\n carPosition[1] <= secondRoutePoint[1]\n ) {\n //console.log(\"das Auto befindet sich zwischen zwei routenpunkten\");\n return true;\n } else {\n return false;\n }\n }\n }\n } else {\n //console.log(\"zu wenig Routenpunkte\");\n let err = \"zu wenig Routenpunkte\";\n return err;\n }\n}", "async function deleteObj(licensenumber, timestamp, parking_lot_id) {\n\n var parkingLog_name;\n var parkingInfo_name;\n if(parking_lot_id) {\n parkingLog_name = 'parkingLog_' + parking_lot_id;\n parkingInfo_name = 'parkingInfo_' + parking_lot_id;\n }\n else {\n parkingLog_name = 'parkingLog';\n parkingInfo_name = 'parkingInfo';\n }\n\n await createTable(parkingLog_name, parkingInfo_name);\n\n // check if the vehicle exiting the parking lot is in the snapshot\n const snapshot = await getObj(parking_lot_id);\n if(!snapshot.rows || snapshot.rows.length == 0) {\n console.log(\"Query failed!\");\n throw new Error(\"Query failed!\");\n }\n let found = false;\n snapshot.rows.forEach(function(element) {\n if(element.licensenumber == licensenumber) {\n found = true;\n }\n });\n\n if(!found) {\n console.log(\"Missing vehicle in the snapshot!\");\n throw new Error(\"Missing vehicle in the snapshot!\");\n }\n\n // select the start time and the vehicle type\n const selectQuery = \"select * from \" + parkingLog_name + \" where licenseNumber = ? and enterOrExit = 0 order by enterOrExitTime desc limit 1 allow filtering\";\n let selectParam = [licensenumber];\n const selectResult = await client.execute(selectQuery, selectParam, { prepare: true });\n if(enableLog >= 1)console.log('Result: ', selectResult.rows);\n\n if(!selectResult.rows || selectResult.rows.length == 0) {\n console.log(\"Query failed!\");\n throw new Error(\"Query failed!\");\n }\n\n \n\n // calculate the start time and end time of the parking\n let startTime = Date.parse(selectResult.rows[0].enterorexittime);\n let endTime = Date.parse(timestamp);\n console.log(\"startTime:\", startTime);\n console.log(\"endTIme:\", endTime);\n\n // calculate the parking fee\n var parkingFee = (endTime - startTime) / (3600 * 1000) * price;\n console.log(\"parkingFee:\", parkingFee);\n\n let parkingSlotType = selectResult.rows[0].parkingslottype; // avoid inconsistency in case the map is modified\n let vehicleType = selectResult.rows[0].vehicletype;\n\n // log the exiting information\n const insertQuery = 'insert into ' + parkingLog_name + ' (licenseNumber, vehicleType, enterOrExitTime, enterOrExit, parkingSlotType) values (?, ?, ?, ?, ?)';\n let insertParam = [licensenumber, vehicleType, timestamp, 1, parkingSlotType];\n const insertResult = await client.execute(insertQuery, insertParam, { prepare: true });\n if(enableLog == 2)console.log('InsertResult: ', insertResult);\n\n // delete the vehicle from the snapshot\n const deleteQuery = 'delete from ' + parkingInfo_name + ' where licenseNumber = ?'\n let deleteParam = [licensenumber];\n const deleteResult = await client.execute(deleteQuery, deleteParam, { prepare: true });\n if(enableLog == 2)console.log('DeleteResult: ', deleteResult);\n\n\n let parkingFeeObj = {'parkingfee': parkingFee};\n\n return parkingFeeObj;\n}", "separate(boids) {\r\n let desiredseparation = 25.0;\r\n let steer = createVector(0, 0);\r\n let count = 0;\r\n // For every boid in the system, check if it's too close\r\n for (let i = 0; i < boids.length; i++) {\r\n\r\n if (boids[i].position!=\"undefined\") {\r\n\r\n\r\n let d = p5.Vector.dist(this.position, boids[i].position);\r\n // If the distance is greater than 0 and less than an arbitrary amount (0 when you are yourself)\r\n if ((d > 0) && (d < desiredseparation)) {\r\n // Calculate vector pointing away from neighbor\r\n let diff = p5.Vector.sub(this.position, boids[i].position);\r\n diff.normalize();\r\n diff.div(d); // Weight by distance\r\n steer.add(diff);\r\n count++; // Keep track of how many\r\n }\r\n }\r\n }\r\n // Average -- divide by how many\r\n if (count > 0) {\r\n steer.div(count);\r\n }\r\n\r\n // As long as the vector is greater than 0\r\n if (steer.mag() > 0) {\r\n // Implement Reynolds: Steering = Desired - Velocity\r\n steer.normalize();\r\n steer.mult(this.maxspeed);\r\n steer.sub(this.velocity);\r\n steer.limit(this.maxforce);\r\n }\r\n return steer;\r\n }", "findNext() {\n // look left, right, up, down\n let leftLoc = {x: this.center.x - 1, y: this.center.y};\n let rightLoc = {x: this.center.x, y: this.center.y};\n let upLoc = {x: this.center.x, y: this.center.y - 1};\n let downLoc = {x: this.center.x, y: this.center.y + 1};\n\n let carArray = [this.layout[leftLoc.y][leftLoc.x] || 0, this.layout[rightLoc.y][rightLoc.x] || 0,\n this.layout[upLoc.y][upLoc.x] || 0, this.layout[downLoc.y][downLoc.x] || 0];\n if(Math.max(...carArray) === 0) {\n console.log(\"bunny sleep\")\n return\n }\n let nextLoc = carArray.indexOf(Math.max(...carArray));\n\n switch(nextLoc) {\n case 0: \n return leftLoc;\n \n case 1: \n return rightLoc;\n\n case 2: \n return upLoc;\n \n case 3: \n return downLoc;\n default: \n return null;\n }\n }", "function pickTarget(radius = 10) {\r\n let elements = intersect.FindDynaPhysElems(myPos, radius).toArray();\r\n\r\n // Log how many objects are around.\r\n console.log(\"search radius\", radius, \"found\", elements.length, \"objects\");\r\n\r\n // Filter blacklisted objects.\r\n elements = elements.filter((a) => !blacklist.includes(a.getName()));\r\n\r\n // Make sure we don't recurse too far by pruning blacklist.\r\n if (radius > 100) {\r\n blacklist.shift();\r\n }\r\n\r\n // Increase radius if no match.\r\n if (elements.length == 0) {\r\n return pickTarget(radius + 1);\r\n }\r\n\r\n // Pick the first acceptable object.\r\n return elements.shift();\r\n}", "function selectTruckForService(trucks, service, airport, options) {\n const TRIP_TO_REFILL = 10 * 60 // 10 minutes in seconds\n if (trucks.length > 0) { // we have at least one truck, can we reuse it?\n let availTruck = null\n let idx = 0\n let availFrom, neededAt\n while (!availTruck && idx < trucks.length) {\n let loctruck = trucks[idx]\n availFrom = moment(loctruck.getProp(\"busyTo\"))\n // can the truck deliver the qty?\n if (service.qty > loctruck.getProp(\"load\")) { // if not, add an average trip to refill\n const time_to_refill = 2 * TRIP_TO_REFILL + loctruck.refillTime(loctruck.getProp(\"capacity\") - loctruck.getProp(\"load\"))\n availFrom.add(time_to_refill, \"seconds\")\n debug.print(loctruck.getName(), \"need refill\", moment.duration(time_to_refill, 'seconds').humanize())\n }\n neededAt = moment(service.datetime)\n if (availFrom.isBefore(neededAt)) {\n availTruck = trucks[idx]\n }\n idx++\n }\n if (availTruck) { // prepare/reserve it for service\n debug.print(\"found truck\", idx - 1 + '/' + trucks.length, availFrom.toISOString(), neededAt.toISOString())\n availTruck.setProp(\"busyTo\", service.endtime)\n return availTruck\n }\n } // no truck found to serve on time, create a new one...\n debug.print(\"no truck found\", trucks.length, service.endtime)\n\n // create a new truck and add it to the list (infinity)\n const serviceData = airport.config.services[service.service]\n const serviceTrucks = serviceData[\"trucks\"]\n\n // clone first one to start with\n const truck = geojson.cleanCopy(serviceTrucks[0])\n\n let device = new vehicle.Device(service.service + \":\" + trucks.length, truck)\n device.setProp(\"service\", service.service)\n\n if (!device.hasOwnProperty(\"serviceTime\"))\n device.serviceTime = serviceData.serviceTime\n if (!device.hasOwnProperty(\"refillTime\"))\n device.refillTime = serviceData.refillTime\n if (!device.hasOwnProperty(\"rate\"))\n device.setProp(\"rate\", serviceData.rate ? serviceData.rate : 60)\n if (!device.hasOwnProperty(\"speed\"))\n device.setProp(\"speed\", serviceData.speed ? serviceData.speed : 30)\n\n // they all start full\n device.setProp(\"load\", truck.capacity)\n device.setProp(\"syncCount\", 0)\n\n // place new device at its refill station (they all start from there.)\n let rsn\n let db = 'pois'\n if (options.start) {\n const startplace = options.start.split(\":\")\n db = startplace[0]\n rsn = startplace[1]\n if (!airport.hasOwnProperty(db)) {\n debug.error(\"cannot find position database '\" + db + \"'\")\n return false\n }\n } else {\n rsn = selectRefillStation(service, device, airport) // no check\n }\n debug.print(rsn, db)\n let rs = geojson.findFeature(rsn, airport[db], \"name\") // no check\n if (!rs) {\n debug.error(\"cannot find position '\" + rsn + \"' in database '\" + db + \"'\")\n return false\n }\n device.setProp(\"position\", rs.geometry.coordinates)\n device.setProp(\"busyTo\", service.endtime)\n\n trucks.push(device)\n\n debug.print('new', trucks.length, service.endtime, device.getName())\n return device\n}", "function funcIsCarBlocked(i) {\n var blockingRow;\n for (var k = 0; k < Config.x; k++) {\n for (var p = 0; p < Config.y; p++) {\n if (mainarr[k * 10 + p].userID != null && mainarr[k * 10 + p].exitT == i + 1) {//check if the parking slot is'nt empty and if the exit hour is i+1\n //when the row is 'isParking' row:\n if (k == 0) blockingRow = 1;\n else if (k == 4) blockingRow = 3;\n else if (k == 5) blockingRow = 6;\n else if (k == 9) blockingRow = 8;\n //when the row is not 'isParking' row:\n else blockingRow == null;\n if (blockingRow != null)//when the row is 'isParking' row\n {\n if (mainarr[blockingRow * 10 + p].userID != null)//check if there is a blocking car\n {\n if (mainarr[k * 10 + p].exitT < mainarr[blockingRow * 10 + p].exitT)//check if exit time of this car< exit time of the blocked car\n {\n //userRequest(k * 10 + p, mainarr[k * 10 + p].exitT); //call\n countMoves++;\n console.log('countermoves: ' + countMoves);\n\n }\n }\n }\n }\n }\n }\n}//end of funcIsCarBlocked", "function callbackSpawnVehicle(player, callbackname, value) {\n alt.offClient(callbackname, callbackSpawnVehicle);\n // Don't proceed further without a callback.\n if (player.job.callback === undefined) {\n return;\n }\n\n let forwardPos = {\n x: player.pos.x + value.x * 3,\n y: player.pos.y + value.y * 3,\n z: player.pos.z\n };\n\n player.job.currentVehicle = new alt.Vehicle(\n player.job.vehicle.model,\n forwardPos.x,\n forwardPos.y,\n forwardPos.z,\n 0,\n 0,\n 0\n );\n\n player.job.currentVehicle.setSyncedMeta('job:Owner', player.data.name);\n player.job.currentVehicle.lockState = player.job.vehicle.lockState;\n player.job.currentVehicle.engineOn = true;\n player.vehicles.push(player.job.currentVehicle);\n\n if (player.job.vehicle.preventHijack) {\n player.job.currentVehicle.preventHijack = true;\n }\n\n player.job.currentVehicle.job = player;\n\n player.job.callback(true);\n}", "function optimizeSchedule(meetingList, hours) {\n //get the length of all the meetings combined.\n function reducer(total, current) {\n return total + current.hour;\n }\n let totalHours = meetingList.reduce(reducer, 0);\n if (totalHours <= hours) {\n return meetingList;\n }\n //if I can't go to all the meetings I want to remove the longest meeting and check again.\n //now I need to find the meeting or combination of meetings that is closest to the difference between my totalHours\n //and my hours.\n else {\n let difference = totalHours - hours;\n let meetingIndex = -1;\n let meetingToAxe;\n\n //loop through all the meetings to find the closest time that is larger than the difference\n meetingList.forEach((meeting, idx) => {\n if (meeting.hour === difference) {\n meetingIndex = idx;\n break;\n }\n if (meeting.hour >= difference) {\n console.log('diff', difference);\n console.log('meeting.hour', meeting.hour);\n if (meetingIndex < 0) {\n meetingIndex = idx;\n console.log('now we have an idx', meetingIndex);\n } else if (meeting.hour - difference < meetingToAxe.hour - difference) {\n meetingIndex = idx;\n console.log('we changed the idx', meetingIndex);\n }\n meetingToAxe = meetingList[meetingIndex];\n }\n console.log(meetingToAxe);\n });\n meetingList.splice(meetingIndex, 1);\n return meetingList;\n }\n}", "function avancer_polygone() {\n\n\tfor (var p = 0; p<18; p++) {\n\n\t\tpolygone[p][1] = polygone[p][1] + vitesse_ver_route;\t\t/* on fait avancer le point verticalement */\n\n\t\tif (polygone[p][1] > 100) {\t\t\t\t/* test : si le point est sorti en bas de l'écran, on le redessine en haut */\n\t\t\tvitesse_lat_route = vitesse_lat_route + Math.floor(3*Math.random())/10 - 0.1;\n\t\t\tif (vitesse_lat_route > 1 || vitesse_lat_route < -1) {\n\t\t\t\tvitesse_lat_route = 0;\t\t\t/* rétroaction négative pour éviter une trop grande difficulté */\n\t\t\t}\n\t\t\tif (xroute+vitesse_lat_route <0 \n\t\t\t\t|| xroute+vitesse_lat_route+largeur > 100) {\n\t\t\t\t\tvitesse_lat_route = -vitesse_lat_route;\t\t/* pour faire tourner la route dans l'autre sens si on atteind le bord */\n\t\t\t}\n\t\t\txroute = xroute + vitesse_lat_route;\n\t\t\tpolygone[p][0] = xroute;\n\t\t\tpolygone[p][1] = polygone[p][1] % 100;\n\t\t\tpremierpoint = p;\n\t\t}\n\t}\n\n}", "function click_near_object(x, y){\n let obj = null;\n if (system){\n for (let i = 0; i < system['stars'].length; i++){\n system['stars'][i]['highlighted'] = false;\n if (!obj && distance_to(x, y, system['stars'][i]['x'], system['stars'][i]['y']) < CLICK_DISTANCE * Math.sqrt(zoom)){\n system['stars'][i]['highlighted'] = true;\n obj = system['stars'][i];\n }\n }\n for (let i = 0; i < system['planets'].length; i++){\n system['planets'][i]['highlighted'] = false;\n if (!obj && distance_to(x, y, system['planets'][i]['x'], system['planets'][i]['y']) < CLICK_DISTANCE * Math.sqrt(zoom)){\n system['planets'][i]['highlighted'] = true;\n obj = system['planets'][i];\n }\n }\n }\n\n return obj;\n}" ]
[ "0.64993197", "0.6336433", "0.55648494", "0.5564525", "0.54301274", "0.5417086", "0.53659356", "0.52854806", "0.5267247", "0.52330995", "0.5229277", "0.5125344", "0.5106067", "0.50674766", "0.50449854", "0.5040505", "0.49897933", "0.49877164", "0.49752247", "0.49747247", "0.49176908", "0.49137706", "0.4912478", "0.48817405", "0.48726892", "0.48568174", "0.48536694", "0.48515683", "0.48310903", "0.47910714", "0.47736204", "0.47656274", "0.47524917", "0.47468802", "0.47345242", "0.4719103", "0.47187504", "0.47165787", "0.47122017", "0.46982473", "0.46954936", "0.46838605", "0.46714887", "0.466885", "0.46655646", "0.4662269", "0.4661661", "0.4658846", "0.46547896", "0.4652614", "0.46524593", "0.46470016", "0.4645479", "0.4642924", "0.46308795", "0.46304718", "0.46178895", "0.46158", "0.46158", "0.46145692", "0.46126214", "0.4612083", "0.46103433", "0.460656", "0.46010852", "0.45827442", "0.45803398", "0.45623225", "0.456087", "0.45607266", "0.45595753", "0.45511487", "0.45365816", "0.4528083", "0.4517924", "0.45072645", "0.45072424", "0.45023495", "0.44886574", "0.44814944", "0.44766304", "0.4476601", "0.4474462", "0.44731608", "0.44718462", "0.44670498", "0.4462878", "0.4454256", "0.44541916", "0.44541705", "0.44526756", "0.44505247", "0.44489458", "0.4448765", "0.44475746", "0.444695", "0.44418338", "0.4440601", "0.44395834", "0.44321814" ]
0.75456023
0
Function that would unpark a vehicle. accepts a vehicle object as a paramater. returns the total parking fee amount for how long the vehicle stayed at the parking slot.
unpack_vehicle(vehicle) { //Loops through the parking slots. for(var i = 0; i < this.sizes.length; i++) { //check if the parking slot is occupied and there is a vehicle parked. if(this.sizes[i].occupied && this.sizes[i].vehicle !== undefined) { //check if the vehicle provided in the parameter is the same with the vehicle parked in the parking slot. if(this.sizes[i].vehicle.plate_number === vehicle.plate_number) { //checks if the vehicle size is in a small parking slot. if(this.sizes[i].slot_size === SMALL_SLOT) { //calculate the total amount of parking fee the vehicle consumed. // small parking slot cause a 20/hour rate. // and every exceeding 24 hours the vehicles is charge for 5000 PHP. let total_charge = this.sizes[i].charge let time_out = new Date().getHours() let time_difference = Math.ceil(Math.abs(parseInt(this.sizes[i].time_in.getHours()) - parseInt(time_out))) while(time_difference > 24) { if(time_difference > 24) { total_charge += this.sizes[i].charge + 5000 time_difference -= 24; } } total_charge = total_charge + (20 * time_difference) this.sizes[i].occupied = false; this.sizes[i].vehicle = null; this.sizes[i].time_in = null; return `Total Parking Charge is: ${total_charge} PHP for vehicle ${vehicle.plate_number}` } //checks if the vehicle size is in a medium parking slot. else if (this.sizes[i].slot_size === MEDIUM_SLOT) { //calculate the total amount of parking fee the vehicle consumed. // medium parking slot cause a 60/hour rate. // and every exceeding 24 hours the vehicles are charged for 5000 PHP. let total_charge = this.sizes[i].charge; let time_out = new Date().getHours() let time_difference = Math.ceil(Math.abs(parseInt(this.sizes[i].time_in.getHours()) - parseInt(time_out))) while(time_difference > 24) { if(time_difference > 24) { total_charge += this.sizes[i].charge + 5000 time_difference -= 24; } } total_charge = total_charge + (60 * time_difference) this.sizes[i].occupied = false; this.sizes[i].vehicle = null; this.sizes[i].time_in = null; return `Total Parking Charge is: ${total_charge} PHP for vehicle ${vehicle.plate_number}` } //checks if the vehicle size is in a medium parking slot. else if (this.sizes[i].slot_size === LARGE_SLOT) { // calculate the total amount of parking fee the vehicle consumed. // large parking slot cause a 60/hour rate. // and every exceeding 24 hours the vehicles are charged for 5000 PHP. let total_charge = this.sizes[i].charge; let time_out = new Date().getHours() let time_difference = Math.ceil(Math.abs(parseInt(this.sizes[i].time_in.getHours()) - parseInt(time_out))) while(time_difference > 24) { if(time_difference > 24) { total_charge += this.sizes[i].charge + 5000 time_difference -= 24; // console.log(total_charge) } } total_charge = total_charge + (100 * time_difference) this.sizes[i].occupied = false; this.sizes[i].vehicle = null; this.sizes[i].time_in = null; return `Total Parking Charge is: ${total_charge} PHP for vehicle ${vehicle.plate_number}` } } } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function unPark(){\n setDetail(selected, 'lat', 0);\n setDetail(selected, 'lng', 0);\n setDetail(selected, 'adress', '');\n clearMarkers();\n }", "function carLeaving(car){\n car.timeRemaining--;\n if (car.remainingElectricity <= 0){ //car is fully fuelled\n //Prevents cars that spawn outside of the graphing time from being included in the pie chart.\n if (car.timeArrived > 12 && car.timeArrived < 60){\n successfulFuels++;\n }\n return true;\n }\n else if (car.timeRemaining <= 0){ //car has ran out of time\n if (car.timeArrived > 12 && car.timeArrived < 60){\n\n var percentageLeft = car.remainingElectricity / car.electricityRequirement;\n if (percentageLeft < pieChartThreshold){\n partialSuccessfulFuels++; //car is mostly fuelled\n }\n else if (percentageLeft == 1){\n failedFuels++; //car received no fuelling at all\n }\n else{\n unsuccessfulFuels++; //car received less than half of fuel\n }\n }\n return true;\n }\n return false; //car is not yet ready to leave\n}", "park_vehicle(vehicle) {\n //Initial Loop through the list of parking slots\n for(var i=0 ; i<this.sizes.length; i++) {\n //check if the slot is occupied and if the vehicle size is SMALL\n //Small vehicles can park either of the three, Small, Medium, Large Parking Slot\n if(vehicle.vehicle_size === 'S' && !this.sizes[i].occupied) {\n //check if where would be the vehicle coming from entry point 1;\n if(vehicle.entry_point === 1) {\n // calculate for the closest distance from where the vehicle is coming from\n var currDistance = Math.abs(1 - this.map[0].entry_point1);\n var newDistance = Math.abs(1 - this.map[i].entry_point1);\n // check if the new distance is less than the curr distance if so park the vehicle\n // else park the vehicle with the lowest distance from the entry point of the vehicle\n if(newDistance < currDistance) {\n currDistance = newDistance;\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n } else {\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n }\n }\n //check if where would be the vehicle coming from entry point 2;\n else if(vehicle.entry_point == 2) {\n // calculate for the closest distance from where the vehicle is coming from\n var currDistance = Math.abs(1 - this.map[0].entry_point2);\n var newDistance = Math.abs(1 - this.map[i].entry_point2);\n // check if the new distance is less than the curr distance if so park the vehicle\n // else park the vehicle with the lowest distance from the entry point of the vehicle\n if(newDistance < currDistance) {\n currDistance = newDistance;\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n } else {\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n }\n }\n //check if where would be the vehicle coming from entry point 3;\n else if(vehicle.entry_point == 3) {\n // calculate for the closest distance from where the vehicle is coming from\n var currDistance = Math.abs(1 - this.map[0].entry_point3);\n var newDistance = Math.abs(1 - this.map[i].entry_point3);\n // check if the new distance is less than the curr distance if so park the vehicle\n // else park the vehicle with the lowest distance from the entry point of the vehicle\n if(newDistance < currDistance) {\n currDistance = newDistance;\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n } else {\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n }\n }\n }\n //check the size of the vehicle and if the parking slot is occupied\n else if (vehicle.vehicle_size === 'M' && !this.sizes[i].occupied) {\n //if the vehicle size is medium it can only be parked at medium slot and large slot\n if(this.sizes[i].slot_size === MEDIUM_SLOT || this.sizes[i].slot_size === LARGE_SLOT) {\n if(vehicle.entry_point === 1) {\n var currDistance = Math.abs(1 - this.map[0].entry_point1);\n var newDistance = Math.abs(1 - this.map[i].entry_point1);\n if(newDistance < currDistance) {\n currDistance = newDistance;\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n } else {\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n }\n }\n else if(vehicle.entry_point == 2) {\n var currDistance = Math.abs(1 - this.map[0].entry_point2);\n var newDistance = Math.abs(1 - this.map[i].entry_point2);\n if(newDistance < currDistance) {\n currDistance = newDistance;\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n } else {\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n }\n }\n else if(vehicle.entry_point == 3) {\n var currDistance = Math.abs(1 - this.map[0].entry_point3);\n var newDistance = Math.abs(1 - this.map[i].entry_point3);\n if(newDistance < currDistance) {\n currDistance = newDistance;\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n } else {\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n return [this.map[i], this.sizes[i]]\n }\n }\n // if there is no more available slot for the vehicle to parked\n // return no avaialable parking slot\n } else {\n return 'No available Parking Slot'\n }\n }\n //checks if the vehicle size is Large and if the parking slot is occupied\n //Large vehicles can only be parked at Large Parking Slot\n else if (vehicle.vehicle_size === 'L' && !this.sizes[i].occupied) {\n if(this.sizes[i].slot_size === LARGE_SLOT) {\n if(vehicle.entry_point === 1) {\n var currDistance = Math.abs(1 - this.map[0].entry_point1);\n var newDistance = Math.abs(1 - this.map[i].entry_point1);\n if(newDistance < currDistance) {\n currDistance = newDistance;\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n } else {\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n }\n }\n else if(vehicle.entry_point == 2) {\n var currDistance = Math.abs(1 - this.map[0].entry_point2);\n var newDistance = Math.abs(1 - this.map[i].entry_point2);\n if(newDistance < currDistance) {\n currDistance = newDistance;\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n } else {\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n }\n }\n else if(vehicle.entry_point == 3) {\n var currDistance = Math.abs(1 - this.map[0].entry_point3);\n var newDistance = Math.abs(1 - this.map[i].entry_point3);\n if(newDistance < currDistance) {\n currDistance = newDistance;\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n } else {\n this.sizes[i].occupied = true;\n this.sizes[i].charge = 40;\n this.sizes[i].time_in = new Date()\n this.sizes[i].vehicle = vehicle;\n return [this.map[i], this.sizes[i]]\n }\n }\n } else {\n return 'No available Parking Slot'\n }\n } \n }\n }", "removeWallet() {}", "update(t) {\r\n this.vehicle.v = this.vehicleSpeed * this.speedFactor;\r\n this.vehicle.update(t, this.freezeVehiclePos);\r\n }", "separate(vehicles) {\n let desiredseparation = this.separationDistance;\n // the steering force is the average of all the force sum/count\n let steer = createVector(0, 0);\n let count = 0;\n // For every boid in the system, check if it's too close\n for (let i = 0; i < vehicles.length; i++) {\n let d = p5.Vector.dist(this.location, vehicles[i].location);\n // If the distance is greater than 0 and less than an arbitrary amount (0 when you are yourself)\n if ((d > 0) && (d < desiredseparation)) {\n // Calculate vector pointing away from neighbor\n let diff = p5.Vector.sub(this.location, vehicles[i].location);\n diff.normalize();\n diff.div(d); // Weight by distance\n steer.add(diff);\n count++; // Keep track of how many\n }\n }\n // Average -- divide by how many\n if (count > 0) {\n steer.div(count);\n // Our desired vector is the average scaled to maximum speed\n steer.normalize();\n steer.mult(this.maxSpeed);\n // Implement Reynolds: Steering = Desired - Velocity\n steer.sub(this.velocity);\n steer.limit(this.maxForce);\n }\n return steer;\n }", "async function deleteObj(licensenumber, timestamp, parking_lot_id) {\n\n var parkingLog_name;\n var parkingInfo_name;\n if(parking_lot_id) {\n parkingLog_name = 'parkingLog_' + parking_lot_id;\n parkingInfo_name = 'parkingInfo_' + parking_lot_id;\n }\n else {\n parkingLog_name = 'parkingLog';\n parkingInfo_name = 'parkingInfo';\n }\n\n await createTable(parkingLog_name, parkingInfo_name);\n\n // check if the vehicle exiting the parking lot is in the snapshot\n const snapshot = await getObj(parking_lot_id);\n if(!snapshot.rows || snapshot.rows.length == 0) {\n console.log(\"Query failed!\");\n throw new Error(\"Query failed!\");\n }\n let found = false;\n snapshot.rows.forEach(function(element) {\n if(element.licensenumber == licensenumber) {\n found = true;\n }\n });\n\n if(!found) {\n console.log(\"Missing vehicle in the snapshot!\");\n throw new Error(\"Missing vehicle in the snapshot!\");\n }\n\n // select the start time and the vehicle type\n const selectQuery = \"select * from \" + parkingLog_name + \" where licenseNumber = ? and enterOrExit = 0 order by enterOrExitTime desc limit 1 allow filtering\";\n let selectParam = [licensenumber];\n const selectResult = await client.execute(selectQuery, selectParam, { prepare: true });\n if(enableLog >= 1)console.log('Result: ', selectResult.rows);\n\n if(!selectResult.rows || selectResult.rows.length == 0) {\n console.log(\"Query failed!\");\n throw new Error(\"Query failed!\");\n }\n\n \n\n // calculate the start time and end time of the parking\n let startTime = Date.parse(selectResult.rows[0].enterorexittime);\n let endTime = Date.parse(timestamp);\n console.log(\"startTime:\", startTime);\n console.log(\"endTIme:\", endTime);\n\n // calculate the parking fee\n var parkingFee = (endTime - startTime) / (3600 * 1000) * price;\n console.log(\"parkingFee:\", parkingFee);\n\n let parkingSlotType = selectResult.rows[0].parkingslottype; // avoid inconsistency in case the map is modified\n let vehicleType = selectResult.rows[0].vehicletype;\n\n // log the exiting information\n const insertQuery = 'insert into ' + parkingLog_name + ' (licenseNumber, vehicleType, enterOrExitTime, enterOrExit, parkingSlotType) values (?, ?, ?, ?, ?)';\n let insertParam = [licensenumber, vehicleType, timestamp, 1, parkingSlotType];\n const insertResult = await client.execute(insertQuery, insertParam, { prepare: true });\n if(enableLog == 2)console.log('InsertResult: ', insertResult);\n\n // delete the vehicle from the snapshot\n const deleteQuery = 'delete from ' + parkingInfo_name + ' where licenseNumber = ?'\n let deleteParam = [licensenumber];\n const deleteResult = await client.execute(deleteQuery, deleteParam, { prepare: true });\n if(enableLog == 2)console.log('DeleteResult: ', deleteResult);\n\n\n let parkingFeeObj = {'parkingfee': parkingFee};\n\n return parkingFeeObj;\n}", "destroy() {\n if (this.world !== undefined) {\n this.car.getComponent('car').fitness = 0\n this.car.getComponent('car').frontWheel.steerValue = 0\n let body = this.car.getComponent('physics').body\n fillNaN(body, 0.0)\n body.allowSleep = false\n if (body.sleepState === p2.Body.SLEEPING) {\n body.wakeUp()\n }\n body.setZeroForce()\n body.position = [this.position[0], this.position[1]]\n body.angularVelocity = 0\n body.velocity = [0, 0]\n body.angle = 0\n this.roadDirector.reset()\n } else {\n this.position = [400, 400]\n this.velocity = [0, 0]\n }\n }", "function vehicle() {\n this.wheels = null;\n this.tires = null;\n}", "decreaseFuelLevel() {\n this._fuelLevel--;\n }", "function Park(data) {\n this.name = data.name;\n this.description = data.description;\n this.address = `${data.addresses[0].linel} ${data.addresses[0].city} ${data.addresses[0].linel} ${data.addresses[0].statecode} ${data.addresses[0].postalcode} `;\n this.fee = data.fees[0] || '0.00';\n this.Park_url = data.url;\n}", "decrementAvailability() {\n this.slotsAvailability--;\n }", "function placeBet() {\n if(amountBet ) balance) {\n balance = 0;\n } else {\n balance -= amountBet;\n }\n}", "travel(miles) {\n this.currentFuel = this.currentFuel - (miles/this.mpg);\n console.log(\"The car \" + this.make + this.model + \" has \" + this.currentFuel.toFixed(1) + \" gallons of \" + this.engineType + \" left.\");\n}", "function stopGuarding () {\n guardPos = null\n bot.pvp.stop()\n bot.pathfinder.setGoal(null)\n}", "function Park(parkData) {\n this.name = parkData.fullName;\n this.description = parkData.description;\n this.address = `${parkData.addresses[0].line1}${parkData.addresses[0].city}${parkData.addresses[0].stateCode}${parkData.addresses[0].postalCode}`\n this.fees = parkData.fees[0] || '0.00';\n this.url = parkData.url;\n}", "function offCourse() {\n getCurrentPosition().then(function (position) {\n if (!routeExists()) {\n return;\n }\n var startPoint = turf.point([position.coords.longitude, position.coords.latitude]);\n var nextRoutePoint = turf.along(currentRoute.geom, currentRoute.stepped + stepLengthMiles, 'miles');\n var currentBearing = turf.bearing(startPoint, nextRoutePoint);\n var bearing = currentBearing + 90;\n if (bearing > 180) {\n bearing -= 360;\n }\n var reroutePoint = turf.destination(startPoint, stepLengthMiles * 2, bearing, 'miles');\n $rootScope.$broadcast(events.positionOffCourse, reroutePoint);\n });\n }", "function releasePokemon (pokemon) {\n let poke = document.getElementById(`trainer-${pokemon.trainer_id}-pokemon-${pokemon.id}`)\n poke.remove()\n deletePokemon(pokemon)\n}", "function calculateUnlockedEarnings(lockups) {\n return lockups.reduce((total, lockup) => {\n if (lockup.confirmed && lockup.end <= moment.utc()) {\n const earnings = BigNumber(lockup.amount)\n .times(lockup.bonusRate)\n .div(BigNumber(100))\n .toFixed(0, BigNumber.ROUND_UP)\n return total.plus(earnings)\n }\n return total\n }, BigNumber(0))\n}", "function vehicleDropType(player, callback) {\n const dist = utilityVector.distance(player.pos, player.job.currentPoint.position);\n if (dist > player.job.currentPoint.range) return callback(false);\n\n if (player.job.currentVehicle !== player.vehicle) callback(false);\n\n player.ejectSlowly();\n player.job.timeout = setTimeout(() => {\n let index = player.vehicles.findIndex(x => x === player.job.currentVehicle);\n if (index !== -1) {\n player.vehicles.splice(index, 1);\n }\n\n player.job.currentVehicle.destroy();\n player.job.currentVehicle = undefined;\n }, 2500);\n\n callback(true);\n}", "function calculateUnlockedEarnings(lockups) {\n return lockups.reduce((total, lockup) => {\n if (lockup.confirmed && lockup.end <= moment.utc()) {\n const earnings = BigNumber(lockup.amount)\n .times(lockup.bonusRate)\n .div(BigNumber(100))\n .toFixed(0, BigNumber.ROUND_HALF_UP)\n return total.plus(earnings)\n }\n return total\n }, BigNumber(0))\n}", "function removeVehicles() {\n Object.keys(vehicles).map(function(k) {\n vehicles[k].setMap(null);\n });\n has_vehicles = false;\n vehicles = {};\n }", "function unfreezePlayer() {\n\n // Set the local variable to indicate the new state\n _isPlayerFrozen = false;\n\n // Inform other code modules that the player's character is now free to move around\n // the game board\n Frogger.observer.publish(\"player-unfreeze\");\n }", "function clearVehicles (vehicle) {\r\n // Get that vehicle types' data\r\n if (vehicle == \"nswtrains\") {markers = markersNSWTrains; lastNSWTrainsIds = [];}\r\n if (vehicle == \"sydneytrains\") {markers = markersTrains; lastTrainsIds = [];}\r\n if (vehicle == \"ferries\") {markers = markersFerries; lastFerriesIds = [];}\r\n if (vehicle == \"lightrail\") {markers = markersLight; lastLightIds = [];}\r\n if (vehicle == \"buses\") {markers = markersBuses; lastBusesIds = [];}\r\n // Remove all the markers from the map\r\n for (i = 0; i < markers.length; i++) {\r\n markers[i].setMap(null);\r\n }\r\n // Clear the marker array\r\n markers = [];\r\n // Tell the user no vehicles of its type is being shown\r\n document.getElementById(vehicle + \"-count\").innerHTML = 0;\r\n}", "die(){\n this.alive = false;\n this.unstageUnit();\n }", "unenroll() {\r\n return super._unenroll(new core.Credential(core.Credential.PIN));\r\n }", "unenroll() {\r\n return super._unenroll(new core.Credential(core.Credential.ProximityCard));\r\n }", "function payUpVan() {\n if(currentPosition.rentStatus == \"own1\"){\n if(turn == \"player\"){\n playerCash -= currentPosition.own1;\n enemyCash += currentPosition.own1;\n playerUpdate(\"Vehicle rental will cost you \"+ currentPosition.own1)\n updateCash()\n }else if( turn == \"enemy\"){\n enemyCash -= currentPosition.own1;\n playerCash += currentPosition.own1;\n enemyUpdate(\"Vehicle rental costs our enemy \"+ currentPosition.own1)\n updateCash()\n }\n }else if(currentPosition.rentStatus == \"own2\"){\n if(turn == \"player\"){\n playerCash -= currentPosition.own2;\n enemyCash += currentPosition.own2;\n playerUpdate(\"Vehicle rental will cost you \"+ currentPosition.own2)\n updateCash()\n }else if( turn == \"enemy\"){\n enemyCash -= currentPosition.own2;\n playerCash += currentPosition.own2;\n enemyUpdate(\"Vehicle rental costs our enemy \"+ currentPosition.own2)\n updateCash()\n }\n }else if(currentPosition.rentStatus == \"own3\"){\n if(turn == \"player\"){\n playerCash -= currentPosition.own3;\n enemyCash += currentPosition.own3;\n playerUpdate(\"Vehicle rental will cost you \"+ currentPosition.own3)\n updateCash()\n }else if( turn == \"enemy\"){\n enemyCash -= currentPosition.own3;\n playerCash += currentPosition.own3;\n enemyUpdate(\"Vehicle rental costs our enemy \"+ currentPosition.own3)\n updateCash()\n }\n }else if(currentPosition.rentStatus == \"own4\"){\n if(turn == \"player\"){\n playerCash -= currentPosition.own4;\n enemyCash += currentPosition.own4;\n playerUpdate(\"Vehicle rental will cost you \"+ currentPosition.own4)\n updateCash()\n }else if( turn == \"enemy\"){\n enemyCash -= currentPosition.own4;\n playerCash += currentPosition.own4;\n enemyUpdate(\"Vehicle rental costs our enemy \"+ currentPosition.own4)\n updateCash()\n }\n }\n}", "function excludingVatPrice($price){\n\n\nif($price===null){\n return -1;\n }else{\n return ($price - ($price * 15/115)).toFixed(2)/1;\n \n }\n\n}", "function withdraw(account, amount) {\n account.total -= amount;\n}", "removeVehicle(location, houseVehicle) {\n const houseVehicles = this.locationVehicles_.get(location);\n if (!houseVehicles)\n throw new Error('Invalid |location| passed while removing a house vehicle.');\n\n if (!houseVehicles.has(houseVehicle))\n throw new Error('The |houseVehicle| is not associated with the |location|.');\n\n const streamableVehicle = this.streamableVehicles_.get(houseVehicle);\n if (!streamableVehicle)\n throw new Error('Invalid |houseVehicle| passed while removing a house vehicle.');\n\n this.streamableVehicles_.delete(houseVehicle);\n this.streamer_().deleteVehicle(streamableVehicle);\n\n houseVehicles.delete(houseVehicle);\n if (!houseVehicles.size)\n this.locationVehicles_.delete(location);\n }", "function relieveDuty(vehicle, day){\t\t\t// create a function that takes a vehicle object and a day of the week\n\t\n var offDuty = [];\t\t\t\t\t\t\t\t// create two new arrays for sorting rangers: on and off duty\n var onDuty = [];\n //here numRangers is 4\n for( var i =0; i < vehicle.numRangers; i++){\t\t\t// loop through rangers, if passed in day of week is same as their day off...\n if(day == [\"ranger\"+[\"numRanger\"]].dayOff){\n offDuty.push([\"ranger\"+[\"numRanger\"]]); \t// add ranger to end of offDuty group\n\t\t} else {\n \tonDuty.push([\"ranger\"+ [\"numRanger\"]]);\t\t\t\t\t// otherwise add ranger to end of onDuty group\n }\n \n\t\t\n for (var j = 0; j < onDuty.length; j++){\t\t\t//loop through onDuty list\n\t\tdelete [\"ranger\"+[\"numRanger\"]]; \t\t\t\t\t//remove each ranger so we can renumber and reassign them\n\t\tvehicle[\"ranger\"+[\"numRanger\"]] = onDuty[j];\t\t\t// for each ranger object in onDuty group, add that object to the vehicle object with a new number\n\t};\t\t\t\t\t\t\t\t\t\t\t//This part is causing a problem?\n\treturn offDuty;\t\t\t\t\t\t\t//return the offDuty group\n }\n}", "function handleTravel( venue ) {\n Player.radius = Math.max( 0, Player.radius - venue.location.distance );\n\n // cannot continue, your travel radius is 0 !\n\n if ( Player.radius === 0 )\n PubSub.publish( Actions.GAME_OVER );\n\n // update player location\n\n Player.latitude = venue.location.lat;\n Player.longitude = venue.location.lng;\n\n PubSub.publish( Actions.POSITION_PLAYER );\n}", "function removeStake(addr) {\n result = linkgearPOS.removeStake(addr)\n console.log(result)\n}", "removeFundFromWallet({ commit }, { walletId, fundId }) {\n commit('removeFundFromWallet', { walletId, fundId });\n commit('resetPercentages', { walletId });\n }", "function calculateRelease(currentBalanceP1,currentBalanceP2,arbPaidFee,arbFeePayorName,person1,person2,arbAccount,feeAccount) {\r\n \r\n var person1Release = 0;\r\n var person2Release = 0;\r\n var doneeRelease = 0;\r\n var totalWallet = Number(currentBalanceP1) + Number(currentBalanceP2);\r\n\r\n // validate the totalWallet\r\n if (totalWallet < 0) {\r\n outputMessage = \"error2000\";\r\n totalWallet = 0;\r\n }\r\n\r\n // check that the total wallet is bigger than the fee\r\n if (totalWallet <= Number(arbPaidFee)) {\r\n \r\n // if balances are too small, dust goes to fee\r\n arbPaidFee = totalWallet; \r\n\r\n } else {\r\n\r\n // calculate the ruling amounts from the percentages - ensure 4 decimals of precision\r\n if (Number(rulingDonee) > 0) {\r\n person1Release = (parseFloat(ruling1)/100) * totalWallet;\r\n person1Release = Number(person1Release.toFixed(4));\r\n person2Release = (parseFloat(ruling2)/100) * totalWallet;\r\n person2Release = Number(person2Release.toFixed(4));\r\n doneeRelease = totalWallet - person1Release - person2Release; \r\n } else if (Number(ruling2) > 0) { \r\n person1Release = (parseFloat(ruling1)/100) * totalWallet;\r\n person1Release = Number(person1Release.toFixed(4));\r\n person2Release = totalWallet - person1Release;\r\n doneeRelease = 0; \r\n } else {\r\n person2Release = (parseFloat(ruling2)/100) * totalWallet;\r\n person2Release = Number(person2Release.toFixed(4));\r\n person1Release = totalWallet - person2Release;\r\n doneeRelease = 0; \r\n }\r\n\r\n // remove the fee from the appropriate person\r\n if (arbFeePayorName == person1) {\r\n person1Release = Number(person1Release) - Number(arbPaidFee);\r\n }\r\n\r\n // remove the fee from the appropriate person\r\n if (arbFeePayorName == person2) {\r\n person2Release = Number(person2Release) - Number(arbPaidFee);\r\n }\r\n\r\n // validate the release amount\r\n if (person1Release < 0) { \r\n\r\n // adjust the arbPaidFee to come from donee, if person doesn't have enough balance\r\n if (Number(doneeRelease) >= Number(person1Release) * (-1)) {\r\n // person 1 is negative, so adding reduces it\r\n doneeRelease = Number(doneeRelease) + Number(person1Release); \r\n } else {\r\n // donee doesn't have enough balance either, just reduce fee rather than taking from person2\r\n // because person2 should have good ruling if no doneeRelease balance \r\n arbPaidFee = Number(arbPaidFee) + Number(person1Release);\r\n }\r\n\r\n person1Release = 0;\r\n } \r\n\r\n if (person2Release < 0) {\r\n \r\n // adjust the arbPaidFee to come from donee, if person doesn't have enough balance\r\n if (Number(doneeRelease) >= Number(person2Release) * (-1)) {\r\n // person 2 is negative, so adding reduces it\r\n doneeRelease = Number(doneeRelease) + Number(person2Release); \r\n } else {\r\n // donee doesn't have enough balance either, just reduce fee rather than taking from person1\r\n // because person1 should have good ruling if no doneeRelease balance \r\n arbPaidFee = Number(arbPaidFee) + Number(person2Release);\r\n }\r\n\r\n person2Release = 0;\r\n }\r\n\r\n\r\n // convert to 4 decimal precision\r\n person1Release = person1Release.toFixed(4);\r\n person2Release = person2Release.toFixed(4);\r\n doneeRelease = doneeRelease.toFixed(4);\r\n\r\n // validate the total released is the total wallet - 4 digits of precision\r\n if (Math.abs(Number(person1Release) + Number(person2Release) + Number(doneeRelease) + Number(arbPaidFee) - Number(totalWallet.toFixed(4))) < 0.00001 ) {\r\n \r\n // validate all balances are positive\r\n if (Number(person1Release) < 0) {\r\n outputMessage = \"error3001\";\r\n }\r\n\r\n // validate all balances are positive\r\n if (Number(person2Release) < 0) {\r\n outputMessage = \"error3002\";\r\n }\r\n\r\n // validate all balances are positive\r\n if (Number(doneeRelease) < 0) {\r\n outputMessage = \"error3003\";\r\n }\r\n\r\n // validate all balances are positive\r\n if (Number(arbPaidFee) < 0) {\r\n outputMessage = \"error3004\";\r\n }\r\n\r\n } else {\r\n\r\n // balance error, fee too big for balances\r\n outputMessage = \"error3000\";\r\n \r\n }\r\n\r\n }\r\n\r\n if (outputMessage == \"success\") {\r\n // update contract\r\n updateContract(person1Release,person2Release,doneeRelease,arbPaidFee,person1,person2,arbAccount,feeAccount);\r\n } else {\r\n finalReturn(outputMessage);\r\n }\r\n \r\n}", "deselectBuyBuilding() {\n let gameScene = this.gameScene;\n let gameEngine = gameScene.gameEngine;\n\n GameUtils.clearTintArray(this.uiVillageButtons);\n\n gameEngine.board.unhighlightTiles(gameEngine.possibleMoves);\n gameEngine.possibleMoves = null;\n\n gameEngine.selectedBuyBuilding = null;\n }", "function updateVehicles() {\n\t\t\tcar.update();\n\t\tif(car.x() < 300)\n\t\t\tcar.driveForward(5);\n\t\t\n\t\t\n\t\t\n\t\tfor(var i in cops) {\n\t\t\tif(streak >= 6) {\n\t\t\t\tcops[i].update(car.y()-20-(i*30));\n\t\t\t\tif(cops[i].x() < car.x()-220-(i*20))\n\t\t\t\t\tcops[i].driveForward(5);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcops[i].driveBack(speed*5);\n\t\t\t}\n\t\t}\n\t}", "async stop() {\n this._clear();\n await this.config.rpc.sendJsonRequest(\"stop_wallet\");\n }", "unstageUnit(){\n this.image.parent.removeChild(this.image);\n this.healthBar.parent.removeChild(this.healthBar);\n }", "refineKnotsUV(uklist, vklist) {\r\n this.refineKnotsU(uklist);\r\n this.refineKnotsV(vklist);\r\n }", "function deduct(memberObj, amount){\n let shopUser = getShopUser(memberObj);\n\n shopUser.balance -= amount;\n data.budget += amount;\n\n fs.writeFileSync(\"./data/shop/data.json\", JSON.stringify(data), (err) => console.log(err));\n\n return `${memberObj} has had ${amount} Simbits deducted from them and added back to the budget.`\n}", "function Remove_all_markers_of_parking() {\n var keys = Object.keys(parking_Markers);\n keys.forEach(function (key) {\n parking_Markers[key].remove();\n delete parking_Markers[key];\n });\n}", "function moveFleetUp(){\n moveFleetRequest('u');\n}", "_passengersLeave () {\n this.passengers.forEach((passenger, index) => {\n \n // If a passenger's destination floor matches the current floor...\n if (passenger.destinationFloor === this.floor) {\n \n // We will delete that person from the \"passenger's\" array\n this.passengers.splice(index, 1);\n\n // We will show a message to indicate what has happened.\n console.log(`${passenger.name} has left the elevator`);\n }\n })\n }", "movePole() {\n this.x -= poleSpeed;\n }", "function remove (name) {\n delete barriers[name];\n}", "function unFreeze() {\n if ($(\".freeze\").size() == 0) {\n return;\n }\n\n $(\".freeze\").remove();\n }", "withdrawal(amount)\n {\n this.accountBalance -= amount;\n }", "async function runAway(tank, angleToDrive) {\n for (let i = 0; i <= 10; i++) {\n await tank.drive(angleToDrive + 45, 100)\n }\n}", "Kill() { \n\t\tthis.alive = false;\n\t\twhile ( this.fleets.length ) { this.fleets[0].Kill(); }\n\t\twhile ( this.planets.length ) { this.planets[0].Reset(false); }\n\t\tthis.ai.objectives = [];\n\t\tthis.ai.completed = [];\n\t\tthis.empire_box = {x1:0,x2:0,y1:0,y2:0};\n\t\tthis.power_score = 0;\n\t\tfor ( let [civ,acct] of this.diplo.contacts ) { \n\t\t\tciv.diplo.contacts.delete(this);\n\t\t\tthis.diplo.contacts.delete(civ);\n\t\t\t}\n\t\t}", "function OnCollisionStay(collision:Collision){\n\tif(collision.gameObject.tag == \"Squelette\"){\n\t\tpointsVie -= 0.5;\n\t}\n}", "function LandVehicle(speed, wheels) {\n Vehicle.apply(this, arguments);\n }", "function up(object){\n object.y -= speed;\n }", "pillage() {\n let storage = Game.rooms[this.room].storage;\n let terminal = Game.rooms[this.room].terminal;\n let target = undefined;\n if (storage) {\n if (storage.store.getUsedCapacity(RESOURCE_ENERGY) > 0) {\n target = storage;\n } else {\n if (!storage.my) storage.destroy();\n }\n } else if (terminal) {\n if (terminal.store.getUsedCapacity(RESOURCE_ENERGY) > 0) {\n target = terminal;\n } else {\n if (!terminal.my) terminal.destroy();\n }\n } else if (Game.rooms[this.room].find(FIND_RUINS).length > 0 || this.memory.ruin) {\n let targetRuin = Game.getObjectById(this.memory.ruin);\n\n if (targetRuin && targetRuin.store.getUsedCapacity(RESOURCE_ENERGY) > 0) {\n target = targetRuin;\n } else {\n let ruins = Game.rooms[this.room].find(FIND_RUINS);\n for (let ruin of ruins) {\n if (ruin.structure.structureType == STRUCTURE_STORAGE && ruin.store.getUsedCapacity(RESOURCE_ENERGY) > 0) {\n this.memory.ruin = ruin.id;\n target = ruin;\n }\n }\n }\n }\n\n if (target === undefined) {\n this.noPillage = true;\n delete this.memory.ruin;\n return false;\n }\n\n if (this.pos.inRangeTo(target, 1)) {\n this.liveObj.withdraw(target, RESOURCE_ENERGY);\n } else {\n this.liveObj.travelTo(target);\n }\n return true;\n }", "killPlant(plant){\n this.plants.splice(this.plants.indexOf(plant), 1);\n plant.cells.forEach(function(cell){\n this.cells[cell.x][cell.y] = null;\n }, this);\n }", "function removeFreeKitFromCustomer() {\n var Transaction = require('dw/system/Transaction');\n if (customer && customer.authenticated && customer.profile) {\n Transaction.wrap(function () {\n customer.profile.custom.freeMaternityEligible = false;\n });\n }\n}", "function C007_LunchBreak_Natalie_PlayerRelease() {\r\n PlayerUnlockAllInventory();\r\n}", "function voltooienObject(){\n\tafspelenGeluid(\"schroeven_compleet\");\n\tobjectenCompleet++;\n\tvolgenInstructies = false;\n}", "function reportPark(allParks) {\n\n console.log('------ PARK REPORT ------');\n\n const parkTotal = allParks.length;\n let parkAges = 0;\n\n allParks.forEach(curPark => {\n\n // Add to total park age\n parkAges += curPark.getAge();\n\n // Loop park data\n console.log(`${curPark.name} has a tree density of ${curPark.trees / curPark.area} trees per square km`);\n\n if (curPark.trees > 1000) {\n console.log(`${curPark.name} has more than 1000 trees`);\n }\n });\n\n console.log(`Our ${parkTotal} parks have an average age of ${parkAges / parkTotal} years`);\n}", "deleteParkingLot() {\n defaultLot = new ParkingLot();\n this.db.deleteParkingLot({parkingSpots: defaultLot.parkingSpots});\n }", "leaveTeam(){\n axios.patch('/remove:team', {user:this.props.user, teamId:this.props.team._id}).then(this.props.onParticipationChange);\n }", "function Vehicle(_fuelTankSize, _range) {\n // Instance property assignments\n this.fuelTankSize = _fuelTankSize;\n this.range = _range;\n }", "function kill(error, par, cb) {\n var step = par;\n var head = null;\n var tail = null;\n var count = 0;\n var kills = {};\n var tmp, kid;\n\n loop: while (true) {\n tmp = null;\n\n switch (step.tag) {\n case FORKED:\n if (step._3 === EMPTY) {\n tmp = fibers[step._1];\n kills[count++] = tmp.kill(error, function (result) {\n return function () {\n count--;\n\n if (count === 0) {\n cb(result)();\n }\n };\n });\n } // Terminal case.\n\n\n if (head === null) {\n break loop;\n } // Go down the right side of the tree.\n\n\n step = head._2;\n\n if (tail === null) {\n head = null;\n } else {\n head = tail._1;\n tail = tail._2;\n }\n\n break;\n\n case MAP:\n step = step._2;\n break;\n\n case APPLY:\n case ALT:\n if (head) {\n tail = new Aff(CONS, head, tail);\n }\n\n head = step;\n step = step._1;\n break;\n }\n }\n\n if (count === 0) {\n cb(util.right(void 0))();\n } else {\n // Run the cancelation effects. We alias `count` because it's mutable.\n kid = 0;\n tmp = count;\n\n for (; kid < tmp; kid++) {\n kills[kid] = kills[kid]();\n }\n }\n\n return kills;\n } // When a fiber resolves, we need to bubble back up the tree with the", "function VehicleConstructor(name, wheels, passengerNumber,speed){\n if (!(this instanceof VehicleConstructor)){\n return new VehicleConstructor(name,wheels,passengerNumber, speed);\n }\n /* Privates */\n var distanceTraveled = 0;\n var self = this;\n function updateDistanceTraveled(){\n distanceTraveled += self.speed;\n console.log(distanceTraveled);\n }\n /* public */\n this.speed = speed;\n this.name = name || \"unicycle\";\n this.wheels = wheels || 1;\n this.passengerNumber = passengerNumber || 0;\n\n this.makeNoise = function(noise){\n var noise = noise || \"Honk Honk\";\n console.log(noise)\n };\n this.move = function(){\n this.makeNoise();\n updateDistanceTraveled();\n };\n this.checkMiles = function(){\n console.log(distanceTraveled);\n };\n\n}", "function unlock_market() {\n marketLockedForPlayer = null;\n marketCategoryChosen = false\n\n console.log(\"market unlocked\")\n}", "function Vehicle(make, model, year) {\n this.make = make;\n this.model = model;\n this.year = year;\n this.isRunning = false;\n}", "reduceArmor(amount) {\n this._armor -= amount;\n if(this._armor <= 0) {\n console.log(this.toString()+' ran out of armor and expired');\n if (this._contained != null) {\n this.place.placeContained(this._contained);\n } else {\n this.place = undefined;\n }\n }\n }", "removeAllVehicles(){\n \n console.log('removing all vehicles: ', Vehicle.tags)\n Vehicle.tags.forEach((tag, index) => this.removeVehicle(tag, index), this)\n Vehicle.tags = []\n \n }", "function tally() {\n\n // Ethereum Account needs to be unlocked.\n if(!addressChosen) {\n alert(\"Please unlock your Ethereum address\");\n return;\n }\n\n // Make sure we are in the correct phase.\n if(state != 2) {\n alert(\"Please wait until VOTE Phase\");\n return;\n }\n var reg = anonymousvotingAddr.totalregistered();\n var voted = anonymousvotingAddr.totalvoted();\n\n // Make sure everyone has voted!\n if(!reg.equals(voted)) {\n alert(\"Please wait for everyone to vote\");\n return;\n }\n\n //TODO: Check that all votes have been cast..\n // Can do this by checking the public 'votecast' mapping...\n web3.personal.unlockAccount(web3.eth.accounts[accountindex],password);\n var res = anonymousvotingAddr.computeTally.sendTransaction({from:web3.eth.accounts[accountindex], gas: 4200000});\n document.getElementById(\"tallybutton\").innerHTML = \"Waiting for Ethereum to confirm tally\";\n txlist(\"Compute Tally: \" + res);\n}", "function truckTour(petrolpumps) {\n let start = 0, cur = 0, gas = 0, count = 0;\n\n while (count !== petrolpumps.length) {\n gas += petrolpumps[cur][0]; // add gas at current pump\n gas -= petrolpumps[cur][1]; // subtract distance to next pump\n cur = getNextIndex(petrolpumps.length, cur);\n\n if (gas < 0) {\n start = cur; // restart at next nump\n gas = 0;\n count = 0;\n } else {\n count += 1;\n }\n }\n\n return start;\n}", "function stopVM(uuid, timeout, callback)\n{\n VM.log('DEBUG', 'DEBUG stop(' + uuid + ')');\n\n if (!timeout) {\n return callback(new Error('stopVM() requires timeout to be set.'));\n }\n\n /* We load here to get the zonepath and ensure it exists. */\n VM.load(uuid, function (err, obj) {\n var socket;\n var q = new Qmp(function () {return;});\n\n if (err) {\n VM.log('DEBUG', 'Unable to load vm: ' + err.message, err);\n return callback(err);\n }\n\n if (obj.brand !== 'kvm') {\n return callback(new Error('vmadmd only handles \"stop\" for kvm (' +\n 'your brand is: ' + obj.brand + ')'));\n }\n\n socket = obj.zonepath + '/root/tmp/vm.qmp';\n q.connect(socket, function(err) {\n if (err) {\n return callback(err);\n }\n q.command('system_powerdown', null, function (err, result) {\n VM.log('DEBUG', 'result: ' + JSON.stringify(result));\n q.disconnect();\n\n // Setup to send kill when timeout expires\n setStopTimer(uuid, timeout * 1000);\n\n return callback(null);\n });\n });\n });\n}", "function sync(dt) {\n let speed = vehicle.getCurrentSpeedKmHour();\n\n drawSpeedo(Math.abs(speed), 0, 0, 160);\n\n breakingForce = 0;\n engineForce = 0;\n\n if (actions.acceleration) {\n if (speed < -1) breakingForce = maxBreakingForce;\n else engineForce = maxEngineForce;\n }\n if (actions.braking) {\n if (speed > 1) breakingForce = maxBreakingForce;\n else engineForce = -maxEngineForce / 2;\n }\n if (actions.left) {\n if (vehicleSteering < steeringClamp)\n vehicleSteering += steeringIncrement;\n } else {\n if (actions.right) {\n if (vehicleSteering > -steeringClamp)\n vehicleSteering -= steeringIncrement;\n } else {\n if (vehicleSteering < -steeringIncrement)\n vehicleSteering += steeringIncrement;\n else {\n if (vehicleSteering > steeringIncrement)\n vehicleSteering -= steeringIncrement;\n else {\n vehicleSteering = 0;\n }\n }\n }\n }\n\n vehicle.applyEngineForce(engineForce, BACK_LEFT);\n vehicle.applyEngineForce(engineForce, BACK_RIGHT);\n vehicle.applyEngineForce(engineForce, FRONT_LEFT);\n vehicle.applyEngineForce(engineForce, FRONT_RIGHT);\n\n vehicle.setBrake(breakingForce / 2, FRONT_LEFT);\n vehicle.setBrake(breakingForce / 2, FRONT_RIGHT);\n vehicle.setBrake(breakingForce, BACK_LEFT);\n vehicle.setBrake(breakingForce, BACK_RIGHT);\n\n vehicle.setSteeringValue(vehicleSteering, FRONT_LEFT);\n vehicle.setSteeringValue(vehicleSteering, FRONT_RIGHT);\n\n let tm, p, q, i;\n let n = vehicle.getNumWheels();\n for (i = 0; i < n; i++) {\n vehicle.updateWheelTransform(i, true);\n tm = vehicle.getWheelTransformWS(i);\n p = tm.getOrigin();\n q = tm.getRotation();\n\n wheelMeshes[i].position.set(p.x(), p.y(), p.z());\n wheelMeshes[i].quaternion.set(q.x(), q.y(), q.z(), q.w());\n }\n\n tm = vehicle.getChassisWorldTransform();\n p = tm.getOrigin();\n q = tm.getRotation();\n chassisMesh.position.set(p.x(), p.y(), p.z());\n chassisMesh.quaternion.set(q.x(), q.y(), q.z(), q.w());\n\n if (mesh != null) {\n mesh.position.set(p.x(), p.y(), p.z());\n mesh.quaternion.set(q.x(), q.y(), q.z(), q.w());\n }\n controls.target.set(p.x(), p.y(), p.z());\n }", "function removeHold(student) {\n let resultStudent = student\n resultStudent.student_hold = 0\n // modifies the student object by posting new object to server\n axios.post(props.url + \"/modify\", resultStudent).then((response) => {\n window.location.reload()\n });\n }", "function payVirtuo() {\n rentals.forEach(element => {\n var returnDate = new Date(element.returnDate);\n var pickup = new Date(element.pickupDate)\n var duration = parseInt(dayDiff(pickup, returnDate));\n if (duration == 0)\n duration += 1\n element.commission = element.price * 0.3\n element.insurance = element.commission / 2\n element.treasury = duration\n element.virtuo = element.commission - element.insurance - element.treasury\n });\n}", "fear() {\n\t\tthis.mentalScore--;\n\t\tif (this.mentalScore < 0) {\n\t\t\tthis.mentalScore = 0;\n\t\t}\n\t}", "function LandVehicle(speed,wheels) {\n\t\tVehicle.apply(this,arguments);\n\n\t}", "clearVotesFromPlayer(votingPlayer) {\n var votingName = this.getNameFromPlayer(votingPlayer);\n for (var name in this.players) {\n var player = this.players[name];\n delete player.mafiaVotes[votingName];\n delete player.copVotes[votingName];\n delete player.doctorVotes[votingName];\n delete player.townVotes[votingName];\n }\n }", "function sync(dt) {\n\n let speed = vehicle.getCurrentSpeedKmHour();\n\n speedometer.innerHTML = (speed < 0 ? '(R) ' : '') + Math.abs(speed).toFixed(1) + ' km/h';\n\n breakingForce = 0;\n engineForce = 0;\n\n if (actions.acceleration) {\n if (speed < -1)\n breakingForce = maxBreakingForce;\n else engineForce = maxEngineForce;\n }\n if (actions.braking) {\n if (speed > 1)\n breakingForce = maxBreakingForce;\n else engineForce = -maxEngineForce / 2;\n }\n if (actions.left) {\n if (vehicleSteering < steeringClamp)\n vehicleSteering += steeringIncrement;\n } else {\n if (actions.right) {\n if (vehicleSteering > -steeringClamp)\n vehicleSteering -= steeringIncrement;\n } else {\n if (vehicleSteering < -steeringIncrement)\n vehicleSteering += steeringIncrement;\n else {\n if (vehicleSteering > steeringIncrement)\n vehicleSteering -= steeringIncrement;\n else {\n vehicleSteering = 0;\n }\n }\n }\n }\n\n vehicle.applyEngineForce(engineForce, BACK_LEFT);\n vehicle.applyEngineForce(engineForce, BACK_RIGHT);\n\n vehicle.setBrake(breakingForce / 2, FRONT_LEFT);\n vehicle.setBrake(breakingForce / 2, FRONT_RIGHT);\n vehicle.setBrake(breakingForce, BACK_LEFT);\n vehicle.setBrake(breakingForce, BACK_RIGHT);\n\n vehicle.setSteeringValue(vehicleSteering, FRONT_LEFT);\n vehicle.setSteeringValue(vehicleSteering, FRONT_RIGHT);\n\n let tm, p, q, i;\n let n = vehicle.getNumWheels();\n for (i = 0; i < n; i++) {\n vehicle.updateWheelTransform(i, true);\n tm = vehicle.getWheelTransformWS(i);\n p = tm.getOrigin();\n q = tm.getRotation();\n wheelMeshes[i].position.set(p.x(), p.y(), p.z());\n wheelMeshes[i].quaternion.set(q.x(), q.y(), q.z(), q.w());\n }\n\n tm = vehicle.getChassisWorldTransform();\n p = tm.getOrigin();\n q = tm.getRotation();\n chassisMesh.position.set(p.x(), p.y(), p.z());\n chassisMesh.quaternion.set(q.x(), q.y(), q.z(), q.w());\n }", "function solve(input) {\n let numOfCars = Number(input.shift())\n let garage = {};\n\n for (let i = 0; i < numOfCars; i++) {\n let [car, mileage, fuel] = input[i].split(\"|\");\n mileage = Number(mileage);\n fuel = Number(fuel);\n\n if (!garage.hasOwnProperty(car)) {\n garage[car] = {};\n garage[car].mileage = mileage;\n garage[car].fuel = fuel;\n }\n\n }\n\n for (let i = numOfCars; i < input.length; i++) {\n let line = input[i];\n if (line.includes(\"Drive\")) {\n let tokens = line.split(\" : \")\n let car = tokens[1];\n let distance = Number(tokens[2]);\n let fuel = Number(tokens[3])\n\n if (garage[car].fuel < fuel) {\n console.log(\"Not enough fuel to make that ride\");\n } else {\n garage[car].mileage += distance\n garage[car].fuel -= fuel\n console.log(`${car} driven for ${distance} kilometers. ${fuel} liters of fuel consumed.`);\n }\n if (garage[car].mileage >= 100000) {\n delete garage[car]\n console.log(`Time to sell the ${car}!`);\n }\n } else if (line.includes(\"Refuel\")) {\n let tokens = line.split(\" : \")\n let car = tokens[1];\n let fuel = Number(tokens[2]);\n let oldFuel = garage[car].fuel\n if (garage[car].fuel + fuel >= 75) {\n garage[car].fuel = 75\n fuel = 75 - oldFuel\n } else {\n garage[car].fuel += fuel\n }\n console.log(`${car} refueled with ${fuel} liters`);\n } else if (line.includes(\"Revert\")) {\n let tokens = line.split(\" : \");\n let car = tokens[1];\n let mileage = Number(tokens[2])\n garage[car].mileage -= mileage\n if (garage[car].mileage < 10000) {\n garage[car].mileage = 10000;\n } else {\n console.log(`${car} mileage decreased by ${mileage} kilometers`);\n }\n } else if (line == \"Stop\") {\n let sorted = Object.entries(garage).sort((a, b) => b[1].mileage - a[1].mileage || a[0].localeCompare(b[0]))\n for (let kvp of sorted) {\n console.log(`${kvp[0]} -> Mileage: ${kvp[1].mileage} kms, Fuel in the tank: ${kvp[1].fuel} lt.`);\n\n }\n }\n }\n }", "removeVehiclesForLocation(location) {\n const houseVehicles = this.locationVehicles_.get(location);\n if (!houseVehicles)\n return;\n\n for (const houseVehicle of houseVehicles) {\n const streamableVehicle = this.streamableVehicles_.get(houseVehicle);\n if (!streamableVehicle)\n throw new Error('No streamable vehicle for the given |houseVehicle|.');\n\n this.streamableVehicles_.delete(houseVehicle);\n this.streamer_().deleteVehicle(streamableVehicle);\n }\n\n this.locationVehicles_.delete(location);\n }", "function unmortgageProperty() {\n var currentOption = $(\"select\").val();\n function getChoice (obj){\n if(obj.name == currentOption){\n return true\n }\n }\n var toUnmortgage = propertyCards.filter(getChoice);\n if(playerCash>=toUnmortgage[0].mortgage){\n toUnmortgage[0].inPlay = \"yes\";\n playerCash -= toUnmortgage[0].mortgage;\n updateCash();\n playerUpdate(\"You just unmortgaged the \"+ toUnmortgage[0].name)\n checkMortgages();\n checkUnmortgages();\n }else{\n alert(\"Not enough cash! Sorry :(\")\n }\n}", "function C012_AfterClass_Bed_StopMasturbate() {\n\tC012_AfterClass_Bed_PleasureUp = 0;\n\tC012_AfterClass_Bed_PleasureDown = 0;\n}", "approaches() {\n this._time_until_arrival--;\n }", "function updateGetränke() {\r\n return getränkeItem.inventory -= 1;\r\n}", "function deleteVehicle() {\r\n\t\t\t\t\r\n\t\t\t\tself.confirm_title = 'Delete';\r\n\t\t\t\tself.confirm_type = BootstrapDialog.TYPE_DANGER;\r\n\t\t\t\tself.confirm_msg = self.confirm_title+ ' ' + self.vehicle.vehicle_regno + ' vehicle reg no?';\r\n\t\t\t\tself.confirm_btnclass = 'btn-danger';\r\n\t\t\t\tConfirmDialogService.confirmBox(self.confirm_title, self.confirm_type, self.confirm_msg, self.confirm_btnclass)\r\n\t\t\t\t.then(\r\n\t\t\t\t\t\tfunction (res) {\r\n\t\t\t\t\t\t\tVehicleService.deleteVehicle(self.vehicle.vehicle_id)\r\n\t\t\t\t\t\t\t.then(\r\n\t\t\t\t\t\t\t\t\tfunction (msg) {\r\n\t\t\t\t\t\t\t\t\t\tself.message = self.vehicle.vehicle_regno+ \" vehicle reg no Deleted..!\";\r\n\t\t\t\t\t\t\t\t\t\tsuccessAnimate('.success');\r\n\t\t\t\t\t\t\t\t\t\twindow.setTimeout(function(){\r\n\t\t\t\t\t\t\t\t\t\t\tnewOrClose();\r\n\t\t\t\t\t\t\t\t\t\t},5000);\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tvar index=self.vehicles.indexOf(self.vehicle);\r\n\t\t\t\t\t\t\t\t\t\tself.vehicles.splice(index,1);\r\n\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t},function(referdata) {\r\n\t\t\t\t\t\t\t\t\t\tself.message = self.vehicle.vehicle_regno+ \" referred in Add Manifest..!\";\r\n\t\t\t\t\t\t\t\t\t\tsuccessAnimate('.failure');\r\n\t\t\t\t\t\t\t\t\t\twindow.setTimeout(function(){\r\n\t\t\t\t\t\t\t\t\t\t\tnewOrClose();\r\n\t\t\t\t\t\t\t\t\t\t},5000);\r\n\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\tfunction (errResponse) {\r\n\t\t\t\t\t\t\t\t\t\tconsole.error('Error while Delete vehicle' + errResponse);\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}\r\n\t\t\t\t\t )\r\n\t\t\t}", "function C012_AfterClass_Jennifer_Untie() {\n\tActorUntie();\n\tC012_AfterClass_Jennifer_CalcParams();\n\tCurrentTime = CurrentTime + 50000;\n}", "function Vehicle(name, wheels,passengers,speed) {\n this.name = name;\n this.speed = speed;\n this.wheels = wheels;\n this.passengers = passengers;\n this.makeNoise = function (noise) {\n console.log(noise,noise);\n };\n var self = this;\n var distance_travelled = 0; //privateMethod\n var updateDistanceTravelled = function () {\n distance_travelled += self.speed;\n };//privateMethod\n // Object can access the privateMethod;\n // privateMethod uses self to refer object and access object attribute\n this.move = function (noise) {\n updateDistanceTravelled();\n this.makeNoise(noise);\n return this;\n };\n //use return to chain function \n this.checkMiles = function () {\n console.log(distance_travelled);\n };\n }", "function remove_waypoint(obj) {\n (function ($) {\n $(obj).parent().parent().remove();\n return false;\n })(jQuery);\n}", "payment(time, available) {\n if (this.paid_off > time) {\n const { payment, balance } = this.opts.mortgage_payment(\n this.mortgage,\n this.mortgage_rate,\n this.mortgage_term,\n time - this.bought\n );\n // Adjust mortgage rate every 5 years.\n if (((time - this.bought) % (5 * 12)) === 0) {\n this.rate(time, balance);\n }\n // Balance remaining.\n this.balance = balance;\n // Make the payment.\n available -= payment;\n // Default?\n if (available < 0) {\n this.defaulted = true;\n this.balance += payment; // payment didn't go through\n }\n }\n\n return available;\n }", "function calculatePayable() {\n var total_amount = (parseFloat($(\"#invoice_payable\").val()) - parseFloat($(\"#invoice_vat\").val()) ).toFixed(2);\n\n\n $(\"#invoice_total_amount\").val(total_amount);\n}", "unguard() {\n this.guardMode = false;\n }", "function profit(obj){\n return Math.round((obj.sellPrice - obj.costPrice) * obj.inventory)\n}", "function Vehicle(make, model, year){\n this.make = make;\n this.model = model;\n this.year = year;\n this.isRunning = false;\n this.turnOn = function(){\n this.isRunning = true;\n }\n this.turnOff = function(){\n this.isRunning = false;\n }\n this.honk = function(){\n if(this.isRunning){\n console.log(\"beep\");\n }\n }\n}", "deactivateHold() {\n this._isHoldWaypoint = false;\n }", "function makeBet(){\n\tif($('#betAmount').spinner('value') > wallet)\n\t\t$('#betAmount').val(wallet);\n\n\twallet -= $('#betAmount').spinner('value');\n\tvar betIndex = $('input[name=\"horseSelect\"]:checked').val();\n\traceHorses[betIndex].bet += $('#betAmount').spinner('value');\n\n\t$('#betAmount').val(0);\n\tupdatePlayerTable();\n\tupdateHorseTable();\n\tbettingMenu.dialog('close');\n}", "function evalPuck() {\n if (puck.y > paddle.y) {\n puck.isAlive = false;\n }\n if (puck.y > canvas.height + 200) {\n puck.y = bricks[0].y + bricks[0].height + 40;\n puck.x = canvas.width / 2;\n puck.velX *= -1;\n puck.isAlive = true;\n combo = 0;\n lives--;\n }\n }", "function getRemainingLiver() {\n return (0, _kolmafia.inebrietyLimit)() - (0, _kolmafia.myInebriety)();\n}", "function preconditionCarStop(vin) {\n var url = BASE_URL + getVehicleId(vin) + '/command/auto_conditioning_stop';\n var options = {\n \"headers\": {\n \"authorization\": \"Bearer \" + ACCESS_TOKEN\n },\n \"method\": \"post\",\n 'contentType': 'application/json'\n };\n var response = UrlFetchApp.fetch(url, options);\n return response;\n}", "killBody() {\n world.DestroyBody(this.body);\n }" ]
[ "0.5062176", "0.4862876", "0.48605102", "0.4858638", "0.48046634", "0.47867355", "0.47271547", "0.47139263", "0.46507627", "0.44915405", "0.44779438", "0.4468146", "0.43742844", "0.4372816", "0.4326032", "0.4316641", "0.43007958", "0.4283456", "0.42807347", "0.4271828", "0.42406276", "0.42329422", "0.42129162", "0.42121464", "0.41884974", "0.4180688", "0.41788828", "0.4173378", "0.41622213", "0.41575462", "0.41466075", "0.41460073", "0.41441283", "0.41349632", "0.41309077", "0.4128065", "0.41249606", "0.40865037", "0.40801004", "0.4078436", "0.40574583", "0.40569893", "0.40553966", "0.40506145", "0.404446", "0.4038946", "0.40331432", "0.4031991", "0.40277255", "0.40217966", "0.4009359", "0.39942798", "0.39940038", "0.39907277", "0.3981572", "0.39789566", "0.39768043", "0.39731407", "0.39727673", "0.3968139", "0.39603287", "0.39585143", "0.39561582", "0.39559332", "0.3953317", "0.39528844", "0.39393905", "0.39339322", "0.39288896", "0.392479", "0.3922119", "0.39160058", "0.39138976", "0.3912936", "0.3909005", "0.39029816", "0.3900966", "0.38988733", "0.389315", "0.38842148", "0.387474", "0.38700482", "0.38694108", "0.386933", "0.38669756", "0.38664004", "0.38638067", "0.38587472", "0.38565943", "0.3855152", "0.38535908", "0.38512155", "0.38510558", "0.3847261", "0.38452694", "0.38443652", "0.38429254", "0.38408446", "0.383822", "0.38336828" ]
0.5479308
0
Create a string representation of the date.
function formatDate(date) { return date.getFullYear() + "/" + months[date.getMonth()] + "/" + check_zero(date.getDate()); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "toString()\n {\n /// UC13 -- Adding the date in short representation\n const options = { year: 'numeric', month: 'long', day: 'numeric'};\n const emplpyeeStartDate = this.startDate == undefined ? \"Undefined\" : this.startDate.toLocaleDateString(\"en-US\", options);\n return `\\n ID : ${this.id} , Name : ${this.name} , Salary : ${this.salary}, Gender = ${this.gender}, Start Date : ${emplpyeeStartDate}`;\n }", "function dateString () {\n now = new Date();\n year = \"\" + now.getFullYear();\n month = \"\" + (now.getMonth() + 1); if (month.length == 1) { month = \"0\" + month; }\n day = \"\" + now.getDate(); if (day.length == 1) { day = \"0\" + day; }\n hour = \"\" + now.getHours(); if (hour.length == 1) { hour = \"0\" + hour; }\n minute = \"\" + now.getMinutes(); if (minute.length == 1) { minute = \"0\" + minute; }\n second = \"\" + now.getSeconds(); if (second.length == 1) { second = \"0\" + second; }\n return year + \"-\" + month + \"-\" + day + \" \" + hour + \"_\" + minute + \"_\" + second;\n}", "function dateToString(date) {\n return date.year + '-' + date.month + '-' + date.day\n}", "function getDateString() {\n // Initializing variables for date, month and year\n let day = date.getDate();\n let month = date.getMonth() + 1;\n let year = date.getFullYear() - 2000;\n \n let strDate = month.toString() + \"/\" + day.toString() + \"/\" + year.toString();\n return strDate\n }", "function toString(date) {\n return date.getFullYear() + '-' + ((date.getMonth() + 1) < 10 ? \n '0' + (date.getMonth() + 1) : (date.getMonth() + 1)) + '-' + \n date.getDate()\n }", "function toString(date) {\n return date.getFullYear() + '-' + ((date.getMonth() + 1) < 10 ? \n '0' + (date.getMonth() + 1) : (date.getMonth() + 1)) + '-' + \n date.getDate()\n }", "function date2str(date) {\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;\n }", "function _getDateString() {\n var myDate = new Date();\n // forward compatability with ES5 Shims\n if (typeof myDate.getFullYear !== \"function\") {\n myDate.getFullYear = function() {\n return (myDate.getYear + 1900); // offset from year 1900\n };\n }\n\n var myYear = myDate.getFullYear().toString();\n var myMonth = _zeroPad(myDate.getMonth() + 1, 2); // counts from 0\n var myDay = _zeroPad(myDate.getDate(), 2);\n var myHours = _zeroPad(myDate.getHours(), 2);\n var myMinutes = _zeroPad(myDate.getMinutes(), 2);\n var mySeconds = _zeroPad(myDate.getSeconds(), 2);\n\n return myYear + \n \"-\" + myMonth + \n \"-\" + myDay + \n \"T\" + myHours + \n ':' + myMinutes + \n ':' + mySeconds +\n '.' + (myDate.getMilliseconds() / 1000).toFixed(3).slice(2, 5);\n }", "function getFormattedDateString() {\n const now = new Date();\n const date_string = `${now.getFullYear().toString()}${(now.getMonth() < 10 ? (\"0\" + (now.getMonth() + 1).toString()) : (now.getMonth() + 1).toString())}${(now.getDate < 10 ? (\"0\" + now.getDate().toString()) : now.getDate().toString())}`;\n return date_string;\n }", "function buildStringFromDate(date){\r\n\tvar year = date.getFullYear();\r\n\tvar month = date.getMonth();\r\n\tvar day = date.getDate();\r\n\tvar hours = date.getHours();\r\n\tvar minutes = date.getMinutes();\r\n\tvar seconds = date.getSeconds();\r\n\t\r\n\tif(month < 10){\r\n\t\tmonth = \"0\" + month;\r\n\t}\r\n\t\r\n\tif(day < 10){\r\n\t\tday = \"0\" + day;\r\n\t}\r\n\t\r\n\tif(hours < 10){\r\n\t\thours = \"0\" + hours;\r\n\t}\r\n\t\r\n\tif(minutes < 10){\r\n\t\tminutes = \"0\" + minutes;\r\n\t}\r\n\t\r\n\tif(seconds < 10){\r\n\t\tseconds = \"0\" + seconds;\r\n\t}\r\n\t\t\r\n\tvar sDate = year + \"-\" + month + \"-\" + day + \" \" + hours + \":\" + minutes + \":\"+ seconds + \" AST\";\r\n\treturn sDate;\r\n}", "function Date$prototype$toString() {\n var x = isNaN(this.valueOf()) ? NaN : this.toISOString();\n return 'new Date(' + toString(x) + ')';\n }", "function makeDateStr(date) {\n let day = date.getDate();\n let month = date.getMonth() + 1;\n let year = date.getFullYear();\n let hours = date.getHours();\n let minutes = date.getMinutes();\n\n if (day < 10) {\n day = '0' + day;\n }\n if (month < 10) {\n month = '0' + month;\n }\n if (hours < 10) {\n hours = '0' + hours;\n }\n if (minutes < 10) {\n minutes = '0' + minutes;\n }\n\n let dateStr = day + '.' + month + '.' + year + ' ' + hours + ':' + minutes + ' Uhr';\n return dateStr;\n}", "function toString(dateObj) {\n return `\\\n${dateObj.getFullYear()}-\\\n${leadingZero(dateObj.getMonth() + 1)}-\\\n${leadingZero(dateObj.getDate())}T\\\n${leadingZero(dateObj.getHours())}:\\\n${leadingZero(dateObj.getMinutes())}:\\\n${leadingZero(dateObj.getSeconds())}\\\n`\n}", "function getDateString() {\n var now = new Date();\n var day = (\"0\" + now.getDate()).slice(-2);\n var month = (\"0\" + (now.getMonth() + 1)).slice(-2);\n return (month) + \"/\" + (day) + \"/\" + now.getFullYear();\n }", "function createDateString(data){\n var months = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"];\n var date = new Date(data);\n var day = date.getDate();\n var month = months[date.getMonth()];\n var year = date.getFullYear();\n return day + ' ' + month + ' ' + year;\n}", "function getDateString(date)\n{\n\tlet year = date.getFullYear();\n\tlet month = date.getMonth() + 1;\n\tlet day = date.getDate();\n\tlet content = \"\";\n\n\tcontent += year;\n\tif(month < 9) content += \"-0\" + month;\n\telse content += \"-\" + month;\n\n\tif(day < 9) content += \"-0\" + day;\n\telse content += \"-\" + day;\n\treturn content;\n\t\n}", "static getDateString(date)\r\n\t{\r\n\t\tlet month = date.getMonth() + 1; //months are counted from zero, we need to format it correctly.\r\n\t\tlet addZero = '';\r\n\t\tlet addZeroToDay = '';\r\n\t\tif(month < 10) //add a leading zero in case month is one digit, needed for correct formatting.\r\n\t\t\taddZero = '0';\r\n\t\tif(date.getDate() < 10)\r\n\t\t\taddZeroToDay = '0'\r\n\r\n\t\treturn date.getFullYear() + '-' + addZero + month + '-' + addZeroToDay + date.getDate();\r\n\t}", "function dateTimeString(date) {\n return `${date.getDate()} ${convertMonthInWord(\n date.getMonth()\n )} ${date.getFullYear()}`;\n}", "function getDateString() {\n var d = new Date();\n return d.getDate() + \" \" + months[d.getMonth()] + \" \" + (d.getYear() + 1900);\n}", "dateToString(date) {\n let year = date.getFullYear();\n let month = (1 + date.getMonth()).toString().padStart(2, '0');\n let day = date.getDate().toString().padStart(2, '0');\n \n return month + '/' + day + '/' + year;\n }", "function createDateStr(date)\n{\n\tif (date == null) { return \"No or improper date provided\"; }\n\t\n\tvar day;\n\tswitch (date.getDay())\n\t{\n\t\tcase 0: day = getLocalizedString(\"Sunday\"); break;\n\t\tcase 1: day = getLocalizedString(\"Monday\"); break;\n\t\tcase 2: day = getLocalizedString(\"Tuesday\"); break;\n\t\tcase 3: day = getLocalizedString(\"Wednesday\"); break;\n\t\tcase 4: day = getLocalizedString(\"Thursday\"); break;\n\t\tcase 5: day = getLocalizedString(\"Friday\"); break;\n\t\tcase 6: day = getLocalizedString(\"Saturday\"); break;\n\t\tdefault: day = \"\";\n\t}\n\n\tvar month;\n\tswitch (date.getMonth())\n\t{\n\t\tcase 0: month = getLocalizedString(\"January\"); break;\n\t\tcase 1: month = getLocalizedString(\"February\"); break;\n\t\tcase 2: month = getLocalizedString(\"March\"); break;\n\t\tcase 3: month = getLocalizedString(\"April\"); break;\n\t\tcase 4: month = getLocalizedString(\"May\"); break;\n\t\tcase 5: month = getLocalizedString(\"June\"); break;\n\t\tcase 6: month = getLocalizedString(\"July\"); break;\n\t\tcase 7: month = getLocalizedString(\"August\"); break;\n\t\tcase 8: month = getLocalizedString(\"September\"); break;\n\t\tcase 9: month = getLocalizedString(\"October\"); break;\n\t\tcase 10: month = getLocalizedString(\"November\"); break;\n\t\tcase 11: month = getLocalizedString(\"December\"); break;\n\t\tdefault: month = \"\";\n\t}\n\t\n\tif (day == \"\" && month == \"\")\n\t{\n\t\treturn null;\n\t}\n\telse {\n\t\treturn day + \", \" + month + \" \" + date.getDate() + \", \" + date.getFullYear();\n\t}\n}", "function stringifiedDate(){\r\n var date=new Date();\r\n var d = date.getDate();\t\r\n var m = date.getMonth()+1;\t\r\n var y = date.getFullYear().toString().substr(-2);\t\r\n\r\n if(d<10)d=\"0\"+d;\r\n if(m<10)m=\"0\"+m;\r\n \r\n return fullDate=d+\"-\"+m+\"-\"+y;\r\n}", "getFormattedDate(date) {\n const year = date.getFullYear();\n const month = (date.getUTCMonth() + 1).toString().padStart(2, '0');\n const day = (date.getUTCDate()).toString().padStart(2, '0');\n // Logger.log(`Day: ${day}, Month: ${month}, Year:${year}`)\n const dateFormatted = `${year}-${month}-${day}`;\n return dateFormatted;\n }", "getDateString() {\n return this.month.toString().padStart(2, \"0\") + \"/\" + this.year.toString().padStart(2, \"0\");\n }", "function getDateString()\n{ \n var d = new Date();\n var year = d.getUTCFullYear();\n var month = d.getUTCMonth()+1;\n var day = d.getUTCDay()+1;\n var date=\"\";\n if(day<10)\n {\n date = \"\"+year+\"\"+month+\"0\"+day;\n }\n else\n {\n date = \"\"+year+\"\"+month+\"\"+day;\n }\n return date;\n}", "function dateToString(date) {\r\n var month = \"\" + (date.getMonth() + 1),\r\n day = \"\" + date.getDate(),\r\n year = date.getFullYear();\r\n\r\n if (month.length < 2) month = \"0\" + month;\r\n if (day.length < 2) day = \"0\" + day;\r\n\r\n return [day, month, year].join(\"-\");\r\n}", "function getFormattedDate() {\n return \"[\" + new Date().toISOString().replace(/T/, ' ').replace(/\\..+/, '') + \"] \";\n}", "function getDate()\n\t\t\t{\n\t\t\t\tvar date = new Date();\n\t\t\t\treturn date.toDateString();\n\t\t\t}", "function dateToString(date) {\n let dd = date.getDate();\n let mm = date.getMonth() + 1;\n if (dd < 10) {\n dd = '0' + dd\n }\n if (mm < 10) {\n mm = '0' + mm\n }\n return date.getFullYear() + '-' + mm + '-' + dd;\n}", "function get_formatted_date(date) {\n function get_formatted_num(num, expected_length) {\n var str = \"\";\n var num_str = num.toString();\n var num_zeros = expected_length - num_str.length;\n for (var i = 0; i < num_zeros; ++i) {\n str += '0';\n }\n str += num_str;\n return str;\n }\n var msg = get_formatted_num(date.getFullYear(), 4) + \"-\";\n msg += get_formatted_num(date.getMonth() + 1, 2) + \"-\";\n msg += get_formatted_num(date.getDate(), 2) + \" \";\n msg += get_formatted_num(date.getHours(), 2) + \":\";\n msg += get_formatted_num(date.getMinutes(), 2) + \":\";\n msg += get_formatted_num(date.getSeconds(), 2);\n return msg;\n}", "_stringify(date){\n date = date.toLocaleDateString();\n return date;\n }", "function datestring () {\n var d = new Date(Date.now() - 5*60*60*1000); //est timezone\n return d.getUTCFullYear() + '-'\n + (d.getUTCMonth() + 1) + '-'\n + d.getDate();\n}", "function datestring () {\n var d = new Date(Date.now() - 5*60*60*1000); //est timezone\n return d.getUTCFullYear() + '-'\n + (d.getUTCMonth() + 1) + '-'\n + d.getDate();\n}", "static formatDate(date) {\n return new Date(date).toLocaleDateString();\n }", "function getDate()\n {\n var date = new Date();\n\n var month = date.getMonth()+1;\n var day = date.getDate();\n\n if (date.getMonth() < 10)\n {\n month = \"0\" + month;\n }\n\n if (date.getDate() < 10)\n {\n day = \"0\" + day;\n }\n\n var datestring = \"\" + date.getFullYear() + month + day;\n\n return datestring;\n }", "function dateString() {\n recipe.forEach(date => {\n let dateStr = `${date.created_at.getFullYear()}-${date.created_at.getMonth()+1}-${date.created_at.getDate()}`\n date.display_date = dateStr\n });\n return recipe\n }", "function str(date) {\n return [\n date.getUTCFullYear(),\n _.padLeft(date.getUTCMonth() + 1, 2, '0'),\n _.padLeft(date.getUTCDate(), 2, '0')\n ].join('-');\n }", "function date()\n{\n let dateObj = new Date();\n // current date\n let date = (\"0\" + dateObj.getDate()).slice(-2);\n let month = (\"0\" + (dateObj.getMonth() + 1)).slice(-2);\n let year = dateObj.getFullYear();\n let hours = dateObj.getHours();\n let minutes = dateObj.getMinutes();\n let seconds = dateObj.getSeconds();\n\n return year + \"_\" + month + \"_\" + date + \"_\" + hours + \"_\" + minutes + \"_\" + seconds;\n}", "function getDateAsString() {\n var currentDate = new Date(); //We use the JavaScript Date object/function and then configure it\n\n var currentMonth;\n var currentDay;\n\n if(currentDate.getMonth() < 10) {\n currentMonth = \"0\" + String(currentDate.getMonth()+1); //0 indexed month, january is 0\n } else {\n currentMonth = String(currentDate.getMonth()+1);\n }\n\n if(currentDate.getDate() < 10) {\n currentDay = \"0\" + String(currentDate.getDate());\n } else {\n currentDay = String(currentDate.getDate());\n }\n\n var date = currentDate.getFullYear() + \".\" + currentMonth + \".\" + currentDay;\n return date; //returns the date string\n}", "function dateToString(date) {\n let yangi = new Date(date).toDateString().slice(4);\n return yangi;\n}", "function convertDateToString(date)\n{\n var dateStr = {day: \"\", month : \"\", year : \"\"};\n\n if(date.day <10)\n {\n dateStr.day = \"0\" + date.day;\n }\n else{\n dateStr.day = date.day.toString();\n }\n\n if(date.month <10)\n {\n dateStr.month = \"0\" + date.month;\n }\n else{\n dateStr.month = date.month.toString();\n }\n\n dateStr.year = date.year.toString();\n\n return dateStr;\n}", "get date_string() {\n return dayjs__WEBPACK_IMPORTED_MODULE_3__(this.date).format('DD MMM YYYY');\n }", "function get_date(){\n var d = new Date();\n var date_string = \"\" + d.getFullYear().toString() + \"-\";\n var month = (d.getMonth() + 1);\n date_string += (month < 10 ? \"0\" + month.toString() : month.toString());\n date_string += \"-\" + d.getDate().toString();\n return date_string;\n}", "function getFormatedDate(date) {\n return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;\n}", "function toDateStr( input ) {\n var str = \" \";\n let date = new Date(input);\n str += date.getFullYear() + '/' + addZero(date.getMonth()+1) + '/' + addZero(date.getDate()) + ' ';\n\n var week = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n str += week[date.getDay()] + ' ' + addZero(date.getHours()) + ':' + addZero(date.getMinutes());\n return str;\n }", "function showDate() {\n return `The date is: '01.01.1990'`;\n }", "function getDate() {\n document.write((new Date()).toDateString());\n}", "function date_to_str(date)\n{\n return format(\"%02u/%02u/%02u\", date.getUTCMonth()+1, date.getUTCDate(), date.getUTCFullYear()%100);\n}", "fullDateString(date) {\n return {\n day: this.getDayName(date.getDay()),\n month: this.getMonthName(date.getMonth()),\n year: date.getFullYear(),\n d: date.getDate()\n };\n }", "function date_str() {\n return Date().substring(0,24);\n}", "function getDateString(date) {\n var m = date.getMonth() + 1;\n if (m < 10) m = '0' + m;\n\n var d = date.getDate();\n if (d < 10) d = '0' + d;\n \n return '' + date.getFullYear() + m + d;\n }", "function getDateString() {\n var today = new Date();\n var month = monthNames[today.getMonth()];\n var day = getOrdinal(today.getDate());\n var year = today.getFullYear();\n return month + ' ' + day + ', ' + year;\n}", "function date(pretty) {\n if (pretty === void 0) { pretty = false; }\n var now = new Date();\n var date = now.getDate().toString().padStart(2, \"0\");\n var month = (now.getMonth() + 1).toString().padStart(2, \"0\");\n var year = now.getFullYear().toString().padStart(4, \"0\");\n var hours = now.getHours().toString().padStart(2, \"0\");\n var minutes = now.getMinutes().toString().padStart(2, \"0\");\n var seconds = now.getSeconds().toString().padStart(2, \"0\");\n if (pretty) {\n return year + \"-\" + month + \"-\" + date + \"_\" + hours + \"-\" + minutes + \"-\" + seconds;\n }\n return \"\" + year + month + date + hours + minutes + seconds;\n}", "function dateMaker (){\n var d = new Date();\n var date = d.toString().split(\" \")\n var arrayDate = [];\n for(i = 0; i < 4; i ++){\n arrayDate.push(date[i]);\n }\n var dateSentence = arrayDate.join(\" \");\n return dateSentence;\n}", "function PrintDate(date) {\n\tvar str = new String();\n\tvar dateMethods = new Array(\n\t\t\"getDay\",\n\t\t\"getFullYear\",\n\t\t//\"getYear\", // Deprecated. Use getFullYear() instead.\n\t\t\"getMonth\",\n\t\t\"getDate\",\n\t\t\"getHours\",\n\t\t\"getMinutes\",\n\t\t\"getSeconds\",\n\t\t\"getMilliseconds\",\n\t\t\"getTime\",\n\t\t\"getTimezoneOffset\",\n\t\t\"getUTCDay\",\n\t\t\"getUTCFullYear\",\n\t\t\"getUTCMonth\",\n\t\t\"getUTCDate\",\n\t\t\"getUTCHours\",\n\t\t\"getUTCMinutes\",\n\t\t\"getUTCSeconds\",\n\t\t\"getUTCMilliseconds\",\n\t\t//\"getVarDate\", // IE Only\n\t\t\"toDateString\",\n\t\t\"toTimeString\",\n\t\t\"toString\",\n\t\t\"toLocaleDateString\",\n\t\t\"toLocaleTimeString\",\n\t\t\"toLocaleString\",\n\t\t\"toUTCString\",\n\t\t//\"toGMTString\", // Deprecated. Use toUTCString() instead.\n\t\t\"valueOf\");\n\tvar i;\n\ttry {\n\t\tfor (i = 0; i < dateMethods.length; i++) {\n\t\t\tstr += dateMethods[i] + \"() \\t -> \" + eval(\"date.\" + dateMethods[i] + \"()\") + \"\\n\";\n\t\t}\n\t}\n\tcatch (ex) {\n\t\tstr = \"Error evaluating function: \" + dateMethods[i] + \"()\";\n\t}\n\treturn str;\n}", "function dateTodayStr() {\n\n var today = new Date();\n return dateFmtStr(today);\n}", "function datetoisostring() { // @return String:\r\n return uudate(this).ISO();\r\n}", "function makeDateString(theDate, what) {\r\n\t\tif (theDate != null && theDate.getFullYear() > 0) {\r\n\t\t\tswitch (what) {\r\n\t\t\t\tcase 6:\r\n\t\t\t\t\treturn (theDate.getFullYear() + \"-\" + pad(theDate.getMonth() + 1) + \"-\" + pad(theDate.getDate())+\"T\"+pad(theDate.getHours())+\":\"+pad(theDate.getMinutes())+\":\"+pad(theDate.getSeconds()));\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase 5:\r\n\t\t\t\t\treturn (theDate.getFullYear() + \"-\" + pad(theDate.getMonth() + 1) + \"-\" + pad(theDate.getDate()));\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase 2:\r\n\t\t\t\t\treturn (theDate.getDate() + \".\" + (theDate.getMonth() + 1) + \".\" + theDate.getFullYear());\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase 3:\r\n\t\t\t\t\treturn (theDate.getFullYear());\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase 4:\r\n\t\t\t\t\treturn (theDate.getDate() + \".\" + (theDate.getMonth() + 1) + \".\" + theDate.getFullYear() + \" \" + theDate.getHours() + \":\" + pad(theDate.getMinutes()));\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase 1:\r\n\t\t\t\tdefault:\r\n\t\t\t\t\treturn (pad(theDate.getDate()) + \".\" + pad(theDate.getMonth() + 1) + \".\" + theDate.getFullYear());\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn (\"\");\r\n\t}", "function formatDateString (date) {\n var month = (date.getMonth() + 1); \n var day = date.getDate();\n if (month < 10) month = '0' + month;\n if (day < 10) day = '0' + day;\n var dateString = date.getFullYear() + '-' + month + '-' + day;\n return dateString;\n }", "function serializedStringForDate(date) {\n\tvar month = date.getMonth() + 1; // 0-based month, eg 0 == Jan, 11 == Dec so add 1\n\tvar day = date.getDate(); \t // 1-based day of month eg 1 thru 31\n\n\tmonth = (month < 10) ? \"0\" + month : \"\" + month;\t// pad single digits\n\tday = (day < 10) ? \"0\" + day : \"\" + day;\t\t// pad single digits\n\n\tvar year = date.getFullYear();\n\treturn year + \"-\" + month + \"-\" + day;\n}", "function dateToFullAussieString(d){\r\n return d.getDate() + \"/\" + (d.getMonth() + 1) + \"/\" + d.getFullYear() + \" \" + d.getHours() + \":\" + d.getMinutes() + \":\" + d.getSeconds();\r\n}", "function convertDateToString(date) {\n return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();\n }", "function createDateString(date) {\n var dateArray = date.split(' ');\n return dateArray[1] + dateArray[2] + dateArray[3];\n}", "function getDateTimeString(date) {\n\tfunction pad10(n) {\n\t\treturn n < 10 ? '0' + n : n;\n\t}\t\n\treturn date.getFullYear() + \"-\" + pad10(date.getMonth()) + \"-\" + pad10(date.getDate()) + \" \" + pad10(date.getHours()) + \":\" + pad10(date.getMinutes()) + \":\" + pad10(date.getSeconds());\n}", "function dateToString(date, duration) {\n if(!date) date = new Date();\n\n var year = date.getFullYear();\n var month = ['January', 'Febuary', 'March', 'April', 'May', 'June', 'July', 'August', 'September','October','November','December'][date.getMonth()];\n\n var ordinal = function (i) {\n var j = i % 10,\n k = i % 100;\n if (j == 1 && k != 11) {\n return i + \"st\";\n }\n if (j == 2 && k != 12) {\n return i + \"nd\";\n }\n if (j == 3 && k != 13) {\n return i + \"rd\";\n }\n return i + \"th\";\n}(date.getDate());\n var day = ['Monday','Tuesday','Wednesday', 'Thursday', 'Friday','Saturday', 'Sunday'][date.getDay()];\n\n var hour = date.getHours();\n var minutes = date.getMinutes();\n \n var time_string = timestring(hour, minutes);\n \n return day + \" the \" + ordinal + \" of \" + month + \" \" + year + \" at \" + time_string + (duration ? \" for \" + duration + \" minutes\" : \"\");\n}", "function _getDateString() {\n return Utilities.formatDate((new Date()), AdWordsApp.currentAccount().getTimeZone(), \"yyyy-MM-dd\");\n}", "function createDateString(currentdate)\n{\n var currentDay = checkDate(currentdate.getDate());\n var currentMonth = checkDate(currentdate.getMonth()+1);\n var currentYear = checkDate(currentdate.getFullYear());\n var currentHour = checkDate(currentdate.getHours());\n var currentMinutes = checkDate(currentdate.getMinutes()); \n var currentSecond = checkDate(currentdate.getSeconds()); \n\n var currentDateTime = currentDay + \"/\"\n + currentMonth + \"/\" \n + currentYear + \" ( \" \n + currentHour + \":\" \n + currentMinutes + \":\" \n + currentSecond + \" ) \" ;\n return currentDateTime;\n}", "function formatDate(date) {\n let source = new Date(date);\n let day = source.getDate();\n let month = source.getMonth() + 1;\n let year = source.getFullYear();\n\n return `${day}/${month}/${year}`;\n }", "function _date(obj) {\n return exports.PREFIX.date + ':' + obj.toISOString();\n}", "display_date_formate(date) {\n if (!date)\n return null;\n const [year, month, day] = date.split('-');\n let new_date = `${day}-${month}-${year}`;\n return new_date;\n }", "static getDateTimeString() {\n return `[${moment().format(\"DD.MM.YYYY HH:mm\")}] `;\n }", "static formatDate(date) {\n let formattedDate = '';\n\n formattedDate += date.getUTCFullYear();\n formattedDate += '-' + ('0' + (date.getUTCMonth() + 1)).substr(-2);\n formattedDate += '-' + ('0' + date.getUTCDate()).substr(-2);\n\n return formattedDate;\n }", "function formatDate(date) {\n const month = date.getMonth() + 1;\n const day = date.getDate();\n const year = date.getFullYear();\n \n return `${month}/${day}/${year}`;\n }", "function getDateString(d){\n\t\tvar days = ['SUN','MON','TUES','WED','THURS','FRI','SAT'];\n\t\tvar spaces = [' ',' '];\n\t\tvar t = days[d.getDay()] + spaces.join('') + d.getDate();\n\t\treturn t\n\t}", "function createDateStr(date)\n{\n if (!date) {\n return dashcode.getLocalizedString(\"Datum ungültig oder nicht verfügbar\");\n }\n\n var day;\n switch (date.getDay()) {\n case 0: day = dashcode.getLocalizedString(\"Sonntag\"); break;\n case 1: day = dashcode.getLocalizedString(\"Montag\"); break;\n case 2: day = dashcode.getLocalizedString(\"Dienstag\"); break;\n case 3: day = dashcode.getLocalizedString(\"Mittwoch\"); break;\n case 4: day = dashcode.getLocalizedString(\"Donnerstag\"); break;\n case 5: day = dashcode.getLocalizedString(\"Freitag\"); break;\n case 6: day = dashcode.getLocalizedString(\"Samstag\"); break;\n default: day = \"\";\n }\n\n var month;\n switch (date.getMonth()) {\n case 0: month = dashcode.getLocalizedString(\"Januar\"); break;\n case 1: month = dashcode.getLocalizedString(\"Februar\"); break;\n case 2: month = dashcode.getLocalizedString(\"März\"); break;\n case 3: month = dashcode.getLocalizedString(\"April\"); break;\n case 4: month = dashcode.getLocalizedString(\"Mai\"); break;\n case 5: month = dashcode.getLocalizedString(\"Juni\"); break;\n case 6: month = dashcode.getLocalizedString(\"Juli\"); break;\n case 7: month = dashcode.getLocalizedString(\"August\"); break;\n case 8: month = dashcode.getLocalizedString(\"September\"); break;\n case 9: month = dashcode.getLocalizedString(\"Oktober\"); break;\n case 10: month = dashcode.getLocalizedString(\"November\"); break;\n case 11: month = dashcode.getLocalizedString(\"Dezember\"); break;\n default: month = \"\";\n }\n\n if (day == \"\" && month == \"\") {\n return null;\n }\n else {\n return day + \", \" + month + \" \" + date.getDate() + \", \" + date.getFullYear();\n }\n}", "function _getFormattedDate(date) {\n var year = date.getFullYear();\n var month = (1 + date.getMonth()).toString();\n month = month.length > 1 ? month : '0' + month;\n var day = date.getDate().toString();\n day = day.length > 1 ? day : '0' + day;\n return month + '/' + day + '/' + year;\n }", "function nowAsString() {\n return new Date().toISOString().substring(0, 10);\n}", "function xl_GetDateStr()\n{\n\tvar today = new Date()\n\tvar year = today.getYear()\n\tif(year<1000) year+=1900\n\t\tvar todayStr = GetMonth(today.getMonth()) + \" \" + today.getDate()\n\ttodayStr += \", \" + year\n\treturn todayStr\n}", "function dateBuilder(d){ \r\n let months=[\"January\" , \"February\", \"March\", \"April\" ,\"May\" , \"June\" , \"July\" , \"August\" , \"September\" ,\"October\" , \"November\" , \"December\"];\r\n let days=[\"Sunday\" ,\"Monday\" , \"Tuesday\" , \"Wednesday\", \"Thursday\" ,\"Friday\" , \"Saturday\"];\r\n\r\n let day=days[d.getDay()];\r\n let date=d.getDate();\r\n let month=months[d.getMonth()];\r\n let year=d.getFullYear();\r\n return `${day} ${date} ${month} ${year}`;\r\n\r\n\r\n}", "function dateToString(date) {\n date = new Date(date);\n return monthNames[date.getMonth()] + \" \" + date.getFullYear();\n }", "formatDate (date){\n var d = new Date(date),\n month = (d.getMonth() + 1),\n day = d.getDate(),\n year = d.getFullYear();\n if (month.length < 2)\n month = '0' + month;\n if (day.length < 2)\n day = '0' + day;\n return [year, month, day].join('-');\n }", "function datestring() {\n var d = new Date(Date.now() - 5 * 60 * 60 * 1000); //est timezone - 5 hours\n return d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getDate();\n}", "formatDate(date) {\n\t\treturn date.toString()\n\t\t.replace(/(\\d{4})(\\d{2})(\\d{2})/, (string, year, month, day) => `${year}-${month}-${day}`);\n\t}", "function formattedDate(date) {\n\n // Récupération\n var month = String(date.getMonth() + 1);\n var day = String(date.getDate());\n var year = String(date.getFullYear());\n\n // Ajout du 0\n if (month.length < 2) \n month = '0' + month;\n\n // Ajout du 0\n if (day.length < 2) \n day = '0' + day;\n\n return day+'/'+month+'/'+year;\n }", "function convertDateToString(date)\n{\n\t// Add \"0\" ahead the month & day if needed\n\tvar month = date.getMonth()+1;\n\tvar day = date.getDate();\n\n\tif (month < 10) {\n\t\tmonth = \"0\"+month;\n\t}\n\tif (day < 10) {\n\t\tday = \"0\"+day;\n\t}\n\t// Date formating\n\tStringDateResult = month+\"/\"+day+\"/\"+(date.getFullYear());\n\n\treturn StringDateResult;\n}", "function createDateStrForDBRequest(date){\n var year = date.getFullYear().toString();\n var tmpMonth = date.getMonth() + 1; \n var month = tmpMonth>9 ? tmpMonth.toString() : ('0'+tmpMonth.toString());\n var tmpDay = date.getDate();\n var day = tmpDay>9 ? date.getDate().toString() : ('0'+tmpDay.toString());\n return year+'-'+month+'-'+day;\n}", "function createDateStrForDBRequest(date){\n var year = date.getFullYear().toString();\n var tmpMonth = date.getMonth() + 1; \n var month = tmpMonth>9 ? tmpMonth.toString() : ('0'+tmpMonth.toString());\n var tmpDay = date.getDate();\n var day = tmpDay>9 ? date.getDate().toString() : ('0'+tmpDay.toString());\n return year+'-'+month+'-'+day;\n}", "formatDate(x) {\n let date = new Date(x)\n let _month = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1\n let _date = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()\n let _hour = date.getHours() < 10 ? `0${date.getHours()}` : date.getHours()\n let _minute = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes()\n let _second = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds()\n let dateStr = `${date.getFullYear()}-${_month}-${_date} ${_hour}:${_minute}:${_second}`\n return dateStr\n }", "function formattedDate(d) {\n let month = String(d.getMonth() + 1);\n let day = String(d.getDate());\n const year = String(d.getFullYear());\n\n if (month.length < 2) month = '0' + month;\n if (day.length < 2) day = '0' + day;\n\n return `${year}-${month}-${day}`;\n }", "function formattedDate(date) {\r\n\t\t\t\t\tvar d = new Date(date),\r\n\t\t\t\t\t\tmonth = '' + (d.getMonth() + 1),\r\n\t\t\t\t\t\tday = '' + d.getDate(),\r\n\t\t\t\t\t\tyear = d.getFullYear();\r\n\r\n\t\t\t\t\tif (month.length < 2) month = '0' + month;\r\n\t\t\t\t\tif (day.length < 2) day = '0' + day;\r\n\t\t\t\t\treturn [year, month, day].join('-');\r\n\t\t\t\t}", "function generateDate(date) {\n return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;\n}", "function dateWriter(year, month, day) {\r\n var fullDate = new Date();\r\n var year = fullDate.getFullYear() + 2019;\r\n var month = fullDate.getMonth() + 12;\r\n var day = fullDate.getDate() + 07;\r\n return newDate = year + '\\n' + month + \"\" + day;\r\n\r\n\r\n}", "function getFormattedDate() {\n let date = new Date();\n let minutes = (date.getMinutes() < 10) ? \"0\" + date.getMinutes() : date.getMinutes();\n let seconds = (date.getSeconds() < 10) ? \"0\" + date.getSeconds() : date.getSeconds();\n let str = \"[\" + (date.getMonth() + 1) + \"-\" + date.getDate() + \"-\" + date.getFullYear() +\n \" \" + date.getHours() + \":\" + minutes + \":\" + seconds + \"]\";\n\n return str;\n}", "function formatDate (date) {\n if (date) {\n const year = date.getFullYear()\n const month = date.getMonth() + 1\n const day = date.getDate()\n return year + '-' + month.toString().padStart(2, '0') + '-' + day.toString().padStart(2, '0')\n } else {\n return ''\n }\n}", "function formattedDate(d = new Date()) {\n return [d.getDate(), d.getMonth() + 1, d.getFullYear()]\n .map((n) => (n < 10 ? `0${n}` : `${n}`))\n .join(\"/\")\n .concat(` at ${getTime(d)}`);\n }", "function getDateAsString(dateVal) {\n if (dateVal) {\n var dateAsYYYYMMDD = dateVal.toString(),\n year = dateAsYYYYMMDD.substr(2, 2),\n month = dateAsYYYYMMDD.substr(4, 2),\n day = dateAsYYYYMMDD.substr(6, 2);\n\n return month + '/' + day + '/' + year;\n }\n}", "function waBuildDate(pv_date) {\n\tvar dateString;\n pv_date=new Date(pv_date);\n var fullYear=pv_date.getFullYear().toString();\n var month=pv_date.getMonth()+1; //add 1 to month (othewise, date is 1 month behind)\n month=month.toString();\n\t\tif(month.length<2) {month=\"0\"+month;}\n var dayOfMonth=pv_date.getDate().toString();\n\t\tif(dayOfMonth.length<2) {dayOfMonth=\"0\"+dayOfMonth;}\n dateString=fullYear+month+dayOfMonth;\n\tif(isNaN(dateString)) { dateString=\"\"; }\n\treturn(dateString); //concatenate as YYYYMMDD\n}", "function datestring() {\n var d = new Date(Date.now() - 5 * 60 * 60 * 1000); //est timezone\n return d.getUTCFullYear() + \"-\" +\n (d.getUTCMonth() + 1) + \"-\" +\n d.getDate();\n}", "function formatDate(date) {\n let year = date.getFullYear();\n let month = date.getMonth() + 1;\n let day = date.getDate();\n return [year, month, day].join('-');\n}", "function dateToString(_date, symbol){\n if(symbol == undefined) symbol = \"/\";\n return _date.getFullYear() + symbol + \n (\"0\" + (_date.getMonth() + 1)).substr(-2) + symbol + \n (\"0\" + _date.getDate()).substr(-2);\n}", "createdString()\n {\n // create an empty string\n let dateStr = \"\";\n\n // grab values\n let hrs = this.created.getHours();\n let mins = this.created.getMinutes();\n let secs = this.created.getSeconds();\n let amOrPm = \"AM\";\n\n let month = this.created.getMonth() + 1;\n let day = this.created.getDate(); // interestingly not getDay()\n let year = this.created.getFullYear();\n\n // afternoon?\n if (hrs >= 12) {\n // subtract 12 from hours if it's 1PM or later\n hrs = hrs > 12 ? hrs - 12 : hrs;\n // set the string to PM\n amOrPm = \"PM\";\n }\n\n dateStr = dateStr + hrs + \":\" + (mins < 10 ? \"0\" : \"\") + mins + \":\" + (secs < 10 ? \"0\" : \"\")\n + secs + amOrPm + \" \" + month + \"/\" + day + \"/\" + year;\n return dateStr;\n }" ]
[ "0.75973916", "0.758846", "0.75825757", "0.75206596", "0.74422365", "0.74422365", "0.7434667", "0.7341156", "0.7329712", "0.7311691", "0.72395635", "0.71936864", "0.7193564", "0.71796143", "0.7157693", "0.7152163", "0.7072284", "0.7033385", "0.70333123", "0.7027442", "0.69415563", "0.69403917", "0.6940104", "0.6938357", "0.6938305", "0.6919861", "0.6919398", "0.6894408", "0.6879143", "0.6865223", "0.6807339", "0.67872345", "0.67872345", "0.67813265", "0.67761254", "0.6772244", "0.6747504", "0.6740586", "0.6738882", "0.6733593", "0.67327106", "0.67213744", "0.6719406", "0.67179155", "0.6712014", "0.6686973", "0.66850626", "0.66846085", "0.66751784", "0.667395", "0.6670526", "0.6665236", "0.6664647", "0.666261", "0.6650704", "0.6641322", "0.6637773", "0.6615859", "0.6597785", "0.65943944", "0.65873986", "0.65842885", "0.65787506", "0.65670127", "0.65667653", "0.65607953", "0.6554862", "0.65501624", "0.6549441", "0.653926", "0.65376896", "0.6534134", "0.65331095", "0.6502736", "0.64974284", "0.64904094", "0.6483612", "0.64644283", "0.64608794", "0.6435295", "0.6430115", "0.6428007", "0.642569", "0.64221996", "0.64048094", "0.64047337", "0.64047337", "0.6402751", "0.6402705", "0.639724", "0.6395021", "0.6389883", "0.6380232", "0.63751316", "0.63750654", "0.6371846", "0.6369882", "0.6369533", "0.6363665", "0.6358324", "0.63556826" ]
0.0
-1
20160421 fetch data after startdate or enddate is changed
function resignData(data) { if (data.d === 'undefined') { console.log('un'); } var results = JSON.parse(data.d); Object.keys(results).map(function (k) { var datefliter = results[k].sickdate; var city_name = results[k].city_name; var town_name = results[k].town_name; var lat = results[k].lat; var lng = results[k].lng; var loccnt = results[k].count; var latlngarr = [lng, lat, loccnt]; //var marker = L.marker(new L.LatLng(lat, lng), { time: datefliter }); //marker_list.push(marker); if (lat != null && lng != null) { //alert(lat + ", " + lng) geojson.features.push({ "type": "Feature", "properties": { "sickdate": datefliter, // "time": datefliter "city": city_name, "town": town_name }, "geometry": { "type": "Point", "coordinates": latlngarr } }); } }); // 20160410 update several operations // due to javascript core, the function setmarkers() must be after all cases put into the map setmarkers(); resetslider(); reloadmarker(); $('#MapLoader1').hide(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "ListDate(start = 0) {\r\n let end = start + (12 * 3600 * 1000);\r\n return new Promise((res, rej) => {\r\n this.db.query(\"SELECT C.* FROM \" + this.db.DatabaseName + \"._WSMK_Calendario AS C \" +\r\n \" LEFT JOIN \" + this.db.DatabaseName + \"._User as U on U.id = C.createdBy WHERE C.active=1 ;\").then(results => {\r\n let ret = results.filter((val) => {\r\n try {\r\n val.description = JSON.parse(val.description);\r\n if (val.description.start >= start && val.description.start <= end) return val;\r\n } catch (err) {\r\n\r\n }\r\n })\r\n res(ret);\r\n })\r\n })\r\n }", "function dateRangeCalculator(){\n\n\t//start date\n\n\t//end date\n\n\t//Api call request that reloads page/section based off of time span requested OR trimming original data object/array based off of new specified date range \n\n\n}", "UpdateData(startDate, endDate) {\n this.startDate = startDate;\n this.endDate = endDate;\n\n const data = this.currentData.filter(row => { \n return row.Date.getTime() >= startDate.getTime() && row.Date.getTime() < endDate.getTime()\n });\n this.mapObject.updateMap(data);\n this.plotObject.updatePlot(data);\n }", "_getAllDatesByData(data) {\n // Get the start and end date\n let startDate = '';\n let endDate = '';\n $.each(data, function (index, item) {\n $.each(item.status, function (date, value) {\n if (startDate === '' && endDate === '') {\n startDate = date;\n endDate = date;\n return true;\n }\n if (date < startDate) {\n startDate = date;\n }\n else if (date > endDate) {\n endDate = date;\n }\n });\n });\n\n // Get dates between the two dates\n startDate = new Date(startDate);\n endDate = new Date(endDate);\n let dateArray = [];\n let currentDate = startDate;\n while (currentDate <= endDate) {\n dateArray.push(currentDate.toISOString().substring(0, 10));\n currentDate.setDate(currentDate.getDate() + 1);\n }\n return dateArray;\n }", "function dateChanged(start, end) {\n\n let start_date = start.format('YYYY-MM-DD');\n let end_date = end.format('YYYY-MM-DD');\n\n datepicker_start_date = start_date;\n datepicker_end_date = end_date;\n\n console.log(\"A new date selection was made: \" + start_date + ' to ' + end_date );\n // Fetch new data each time a new sample is selected\n\n if( displayComparisonChart ){\n setComparisonChartRevenueCutoffDateWarning();\n }\n\n let numdays = end.diff(start, 'days') + 1;\n \n // let numdays_float = end.diff(start, 'days', true) + 1;\n // console.log(\"diff integer: \" + numdays);\n // console.log(\"diff float: \" + numdays_float);\n\n d3.select(\"#numberOfDays\").html(numdays);\n\n let api_call = \"/api/v1.0/daterange_pandas/\" + start_date + \"/\" + end_date; \n\n makeAPICall(api_call);\n\n}", "function getDates(callback) {\n var d = new Date();\n var queryObject = {};\n\n //check already there is one year data in db\n if (initialResults.data != null) {\n d.setDate(d.getDate());\n if (initialResults.data.updated < new Date()) {\n var endDate = initialResults.data.updated;\n endDate.setDate(endDate.getDate() + 1);\n var updated = moment(endDate).format('YYYY-MM-DD');\n d.setDate(d.getDate() + 1);\n var now = moment(d).format('YYYY-MM-DD');\n var query = initialResults.object.channelObjectId + \"/insights/\" + initialResults.metric.objectTypes[0].meta.fbMetricName + \"?since=\" + updated + \"&until=\" + now;\n queryObject = {\n query: query, metricId: initialResults.metric._id, metric: initialResults.metric,\n startDate: updated,\n endDate: now\n };\n callback(null, queryObject);\n }\n else {\n var endDate = initialResults.data.updated;\n endDate.setDate(endDate.getDate() + 1);\n var updated = moment(endDate).format('YYYY-MM-DD');\n d.setDate(d.getDate() + 1);\n var now = moment(d).format('YYYY-MM-DD');\n queryObject = {\n query: 'DataFromDb', metricId: initialResults.metric._id, metric: initialResults.metric,\n startDate: updated,\n endDate: now\n };\n callback(null, queryObject);\n }\n\n }\n }", "async getAll(params,res) {\n\n try{\n let query = \"SELECT * FROM events\";\n let queryParams = [\n this.table\n ];\n\n let result=null;\n \n if (params.from && params.to) { \n\n query += \" WHERE end_date >= $1 AND start_date < $2\";\n queryParams.push(params.from);\n queryParams.push(params.to);\n result = await this._db.query(query,[params.from,params.to]);\n }else result = await this._db.query(query);\n \n \n\n result.rows.forEach((entry) => {\n // format date and time\n entry.start_date = entry.start_date.format(\"YYYY-MM-DD hh:mm\");\n entry.end_date = entry.end_date.format(\"YYYY-MM-DD hh:mm\");\n });\n\n return result;\n }catch(err){\n console.log(err);\n }\n }", "dateChange(){\n if (this.date.start.getTime() > this.date.end.getTime())\n this.date.end = this.date.start;\n }", "function DateChangedEnd() {\n var perStart = $(\"#dpfrom\").datepicker(\"getDate\");\n var perEnd = $(\"#dpto\").datepicker(\"getDate\");\n \n if (perStart > perEnd) {\n $('#dpfrom').datepicker('setDate', perEnd);\n }\n GetInvoicesForPeriod();\n}", "function dt_add_rangedate_filter(begindate_id, enddate_id, dateCol) {\n $.fn.dataTableExt.afnFiltering.push(\n function( oSettings, aData, iDataIndex ) {\n\n var beginDate = Date_from_syspref($(\"#\"+begindate_id).val()).getTime();\n var endDate = Date_from_syspref($(\"#\"+enddate_id).val()).getTime();\n\n var data = Date_from_syspref(aData[dateCol]).getTime();\n\n if ( !parseInt(beginDate) && ! parseInt(endDate) ) {\n return true;\n }\n else if ( beginDate <= data && !parseInt(endDate) ) {\n return true;\n }\n else if ( data <= endDate && !parseInt(beginDate) ) {\n return true;\n }\n else if ( beginDate <= data && data <= endDate) {\n return true;\n }\n return false;\n }\n );\n}", "function init_dates(){\n domo.get('/data/v1/dataset?fields=date&groupby=date&orderby=date descending&limit=8').then(function(data){\n start_date = data[data.length-1].date;\n end_date = data[0].date;\n\n $(function() {\n $(\"#datepicker\").daterangepicker({\n datepickerOptions : {\n numberOfMonths : 2\n }\n });\n });\n $(\"#datepicker\").daterangepicker({\n initialText : moment(start_date, \"YYYY-MM-DD\").format(\"MMM DD, YYYY\") + \" - \" + moment(end_date, \"YYYY-MM-DD\").format(\"MMM DD, YYYY\")\n });\n\n // show filters\n $(\".filterpanel\").show();\n\n // Init main routine\n // update_data();\n\n });\n}", "function DateChangedStart() {\n var perStart = $(\"#dpfrom\").datepicker(\"getDate\");\n var perEnd = $(\"#dpto\").datepicker(\"getDate\");\n \n if (perStart > perEnd) {\n $('#dpto').datepicker('setDate', perStart);\n }\n GetInvoicesForPeriod();\n}", "function queryInstancesByDate(startDate, endDate) {\n // DEFINE LOCAL VARIABLES\n // RETURN ASYNC WORK\n return new Promise(function (resolve, reject) {\n\n var instances = firebase.database().ref('instances').orderByChild('opens').startAt(startDate).endAt(endDate);\n\n instances.once(\"value\")\n .then(function(snapshot) {\n resolve(snapshot.val());\n })\n .catch(function(e) {\n reject(e);\n });\n });\n }", "static async getDetailByDays({from, to}) {\n let sql = `SELECT t1.*, t2.* FROM ${TABLE_NAME} AS t1 INNER JOIN ${TABLE_JOIN} AS t2 ON t1.id = t2.id_trans WHERE t1.created_at >= '${from}' AND t1.created_at <= '${to}'`\n const options = {sql, nestTables: '_'}\n\n return OBJ_DB.query(options)\n }", "function getOrderDate(startDate,endDate,orderDetail){\r\n result = orderDetail.filter(d => {var time = new Date(d.orderdate).getTime();\r\n return (startDate <= time && time <= endDate);\r\n });\r\n return result;\r\n}", "findDates(id, d1, d2) {\n return db(\"users_sleep\")\n .where({ uid: id })\n .andWhereBetween(\"sleep_start\", [d1, d2])\n .limit(7);\n }", "function filtering(data, startdate, enddate)\r\n {\r\n return _.filter(data, function(value)\r\n {\r\n var month = parseInt(value.date.substr(3,4));\r\n var year = parseInt(value.date.substr(6,9));\r\n if((year == startdate.getYear()+1900) && year == (enddate.getYear()+1900))\r\n {\r\n if(month >= (startdate.getMonth()+1) && month <= (enddate.getMonth()+1))\r\n return true;\r\n else\r\n return false;\r\n }\r\n else\r\n {\r\n if(month >= (startdate.getMonth()+1) && year == (startdate.getYear()+1900))\r\n return true;\r\n else if(month <= (enddate.getMonth()+1) && year == (enddate.getYear()+1900))\r\n return true;\r\n else if(year > (startdate.getYear()+1900) && year < (enddate.getYear()+1900))\r\n return true;\r\n else\r\n return false;\r\n }\r\n });\r\n }", "function nextStates() {\n var maxEnd = moment.min(moment(filter.end).add(globalTime, globalTimeRange), moment(Date.now()));\n filter.end = maxEnd.format('YYYY-MM-DD HH:mm:ss');\n filter.start = maxEnd.subtract(globalTime, globalTimeRange).format('YYYY-MM-DD HH:mm:ss');\n $('#daterangepicker').data('daterangepicker').setStartDate(moment(filter.start).format('l[, ]LTS'));\n $('#daterangepicker').data('daterangepicker').setEndDate(moment(filter.end).format('l[, ]LTS'));\n refreshData();\n }", "async function getDate(ssn, startDt, endDt) {\n let firstDay = new Date(startDt);\n let lastDay = new Date(endDt);\n let obj = {};\n\n for (let d = firstDay; d <= lastDay; d.setDate(d.getDate() + 1)) {\n let day = new Date(d);\n let convertDay = moment(day).format('YYYY-MM-DD 00:00:00');\n\n obj.ssn = ssn;\n obj.date = convertDay;\n\n // query เพื่อดูว่าใน table info_summary_check และทำ auto_insert \n if (ssn !== '') {\n let data = await querySummary(obj);\n }\n }\n}", "backlogRecords(date){\n \n }", "findRangeofDates(){ \n\t\tlet min=new Date(2030,1,1); \n\t\tlet max=new Date(1990,1,1);\n\t\tconst ar=this.props.data;\n\t\tfor(let i=0;i<ar.length;i++){\n\t\t\tif(ar[i].start<min)\n\t\t\t\tmin=ar[i].start;\n\t\t\tif(ar[i].end>max)\n\t\t\t\tmax=ar[i].end;\n\t\t}\n\t\tthis.min=min;\n\t\tthis.max=max;\n\t}", "isAvailable(newStart, newEnd) {\n let plans = this.props.dailyPlans\n for (let i = 0; i < plans.length; i++) {\n let old = plans[i]\n\n if(old.fldOpRLogOn === true && old.fldOpRLogOut === true) continue\n\n let oldStart = this.createDate(old.fldOpRStartDate, old.fldOpRStartTime).getTime()\n let oldEnd = old.fldOpREndTime ? \n this.createDate(old.fldOpREndDate, old.fldOpREndTime).getTime() : null\n \n if (this.state.openEnded || !oldEnd) return true\n \n if (newStart <= oldEnd && oldStart <= newEnd) return\n } \n return true\n }", "function updateChart()\n{\n\tmin = new Date(document.getElementById(\"startDate\").value);\n\tmax = new Date(document.getElementById(\"endDate\").value);\n\n\t// Set the minString to midnight on minDate and the maxString to midnight on the day after maxDate\n\tvar minString = min.getFullYear() + \".\" + (min.getMonth() + 1) + \".\" + (min.getDate() + 1);\n\tvar maxString = max.getFullYear() + \".\" + (max.getMonth() + 1) + \".\" + (max.getDate() + 2);\n\n\tquery.setQuery(\"SELECT 'Date', '3379' FROM 1-UxIFELz001J7cR2JCWN8EJDf7nXTrstXKaSUb5t WHERE 'Date' >= '\"\n\t+ minString + \"' AND 'Date' <= '\" + maxString + \"' ORDER BY 'Date'\");\n\n\tquery.send(handleQueryResponse);\n}", "function filterData (data, startdate, enddate)\r\n {\r\n\r\n _.forEach(data, function(value)\r\n {\r\n var filtered = filtering(value.database, startdate, enddate);\r\n _.forEach(filtered, function(value)\r\n {\r\n storeData.push({\r\n \"date\": parseDate.parse(value.date),\r\n \"literacy_rate\": value.val\r\n });\r\n });\r\n filterData(value.place,startdate,enddate);\r\n });\r\n }", "getAllInBetweenDates(sStartDate, sEndDate) {\n let aDates = [];\n //to avoid modifying the original date\n const oStartDate = new Date(sStartDate);\n const oEndDate = new Date(sEndDate);\n while (oStartDate <= oEndDate) {\n aDates = [...aDates, new Date(oStartDate)];\n oStartDate.setDate(oStartDate.getDate() + 1)\n }\n return aDates;\n }", "function fillCurrent() {\n for (let i = startDay; i < endDate + startDay; i++) {\n dateArray.push(i - startDay + 1)\n }\n }", "index( {params, query, user} , res) {\n\n\t\t\tlet includeTotal = false;\n\t\t\tif ('today' in query) {\n\t\t\t\treturn todayHolidays(res);\n\t\t\t}\n\t\t\tlet queryDbParams = {order: 'date ASC'};\n\t\t\tif (query._sort) {\n\t\t\t\tqueryDbParams.order = ((query._sort != 'date_f') ? query._sort: 'date')\n\t\t\t\t\t+' '+ (query._order || 'ASC');\n\t\t\t}\n\t\t\tif (query._start && query._end) {\n\t\t\t\tqueryDbParams.offset = query._start;\n\t\t\t\tqueryDbParams.limit = query._end - query._start;\n\t\t\t}\n\t\t\tif (query.limit) {\n\t\t\t\tqueryDbParams.offset = query.offset ? query.offset : 0;\n\t\t\t\tqueryDbParams.limit = query.limit;\n\t\t\t\tincludeTotal = true;\n\t\t\t}\n\n\t\t\tlet m1, m2;\n\t\t\tlet where = {};\n\t\t\tlet modifiedQMap = {...queryMap};\n\t\t\tif ('passed' in query) {\n\t\t\t\tqueryDbParams.order = [['date','DESC'], ['id', 'DESC']];\n\t\t\t\tm1 = moment().startOf('year');\n\t\t\t\tm2 = moment().subtract(1, 'day');\n\t\t\t\tmodifiedQMap.include = [\n\t\t\t\t\t...modifiedQMap.include,\n\t\t\t\t\t{\n model: Bookmark,\n required:true,\n where: {\n locationId: {$eq: null},\n userId: user.id\n },\n attributes: ['id']\n\t\t\t\t\t}\n\t\t\t\t];\n\t\t\t\tmodifiedQMap.distinct = true;\n\t\t\t} else\n\t\t\tif (query.month) {\n\t\t\t\tlet m = moment(query.month);\n\t\t\t\tif (m.isValid()) {\n\t\t\t\t\tm1 = m.clone();\n\t\t\t\t\tm2 = m.endOf('month');\n\t\t\t\t}\n\t\t\t} else if (query.week) {\n\t\t\t\tlet m = moment(query.week);\n\t\t\t\tif (m.isValid()) {\n\t\t\t\t\tm1 = m.clone();\n\t\t\t\t\tm2 = m.endOf('isoWeek');\n\t\t\t\t}\n\t\t\t} else if (query.date1 && query.date2) {\n\t\t\t \tlet d1 = moment(query.date1);\n\t\t\t\tlet d2 = moment(query.date2);\n\t\t\t \tif (d1.isValid() && d2.isValid()) {\n\t\t\t \t\tm1 = d1;\n\t\t\t\t\tm2 = d2;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (m1 && m2) {\n\t\t\t\twhere.date = {\n\t\t\t\t\t$between: [\n\t\t\t\t\t\tm1.format(DATE_FORMAT),\n\t\t\t\t\t\tm2.format(DATE_FORMAT)\n\t\t\t\t]};\n\t\t\t}\n\t\t\tif (query.q) {\n\t\t\t\tconst search = query.q;\n\t\t\t\tlet m = moment(search, parseformat(search));\n\t\t let conds = m.isValid() ? [{ date: { $eq: m.format(DATE_FORMAT) }\t} ] : [];\n\t\t where = {...where,\n\t\t $or: [...conds,\n\t\t {\tdescription: { $iLike: `%${search}%`\t}\t},\n\t\t {\tname: { $iLike: `%${search}%`\t}\t}\n\t\t ],\n\t\t }\n\t\t\t}\n\n\n\t\t\tHolidays.findAndCount({\n\t\t\t\t...modifiedQMap,\n\t\t\t\t...queryDbParams,\n\t\t\t\twhere\n\t\t\t})\n\t\t\t.then( ( {count: total, rows: holidays} ) => {\n\t\t\t\tif (includeTotal) {\n\t\t\t\t\tres.json({holidays, total})\n\t\t\t\t} else {\n\t\t\t\t\tres.setHeader(\"X-Total-Count\", total);\n\t\t\t\t\tres.json(holidays);\n\t\t\t\t}\n\t\t\t})\n\n\t\t}", "function findNextEventByDate(startDate, endDate) {\n gapi.client.sheets.spreadsheets.values.get({\n spreadsheetId: '1xn0_Qahjb2CrXrXGYAtQ3fqZCu0Ycee3xYo-AmaGTg0',\n range: 'Sheet1!A1:D'\n }).then(async function(response) {\n var range = response.result;\n if (range.values.length>0) {\n appendPre('Time, Sensor, Event');\n for (i = 0; i < range.values.length; i++) {\n var row = range.values[i];\n // Print columns A, B and D\n appendPre(row[0] + ', ' + row[1] + ', ' + row[3]);\n await sleep(500);\n updateActivity(row[0], row[1], row[3]);\n }\n } else {\n appendPre('No data found.');\n }\n }, function(response) {\n appendPre('Error: ' + response.result.error.message);\n });\n}", "setDateParams([start, end]) {\n this.set('tableIsLoading', true);\n Ember.run.debounce(this, this.get('actions.setNewDate'), { start, end }, 500);\n }", "function get_records (min_date, device_in) {\n var max_date = new Date(Date.now());\n var test_1;\n database.collection(\"people_presence_db\").find({\n device: device_in,\n date: {\n $gte: min_date,\n $lt: max_date\n }\n }).toArray(function (err,res) {\n if (err) throw err;\n test_1 = res\n \n console.log(res);\n console.log(typeof(res))\n return res;\n })\n }", "function cb_stat(start, end) {\n stat_dt_start = start.format('YYYY-MM-DD') + ' ' + String(moment().hour())+':00',\n stat_dt_end = end.format('YYYY-MM-DD') + ' ' + String(moment().hour()+1)+':00';\n\n if (moment(stat_dt_start).hour() == 0) {\n stat_dt_start = start.format('YYYY-MM-DD') + ' ' + '00:00'; \n };\n if (moment(stat_dt_end).hour() == 0) {\n stat_dt_end = end.format('YYYY-MM-DD') + ' ' + '00:00'; \n };\n \n $('#statdaterange span').html(stat_dt_start + ' - ' + stat_dt_end);\n }", "onRangeChange({\n startDate,\n endDate\n }) {\n this.startDate = startDate;\n this.endDate = endDate;\n this.refresh();\n }", "updateData() {\n // filter data from selected time period\n const filteredData = this.data.filter(\n // the \"minDate\" and \"maxDate\" are set in the main controller\n (data) => data.date >= minDate && data.date <= maxDate\n );\n\n this.update(filteredData);\n }", "function filterRequestByDate(requestList) {\n const filteredData = requestList.filter(function (request) {\n // console.log(\"Request Date : \", request.date);\n // console.log(\"dateQuery.starDate : \", dateQuery.startDate);\n // console.log(\"request.date >= dataQuery.startDate\", (request.date >= dateQuery.startDate))\n return (\n request.date >= dateQuery.startDate && request.date <= dateQuery.endDate\n );\n });\n return filteredData;\n }", "function searchHotelsByDate(){\n totalNight();\n resultHotel= [];\n const start = new Date (dateFrom.value).getTime();\n const end = new Date (dateTo.value).getTime();\n if(start <= end){\n resultHotel = hotels.filter((hotel)=>{\n let available = false\n hotel.availability.forEach( date =>{\n var availableFrom = new Date(date.from.split('-').reverse().join('-')).getTime();\n var availableTo = new Date(date.to.split('-').reverse().join('-')).getTime();\n if(start <= availableFrom && end >= availableTo ){\n return available = true\n }\n // let fromString = date.from.split('-');\n // let toString = date.to.split('-');\n // let fromDate = new Date(fromString[2], fromString[1]-1, fromString[0]);\n // let toDate = new Date(toString[2], toString[1]-1, toString[0]);\n // if(fromDate.getTime() >= start && toDate.getTime() <= end)\n // {\n // // resultHotel.push(hotel);\n // return available = true;\n // }\n\n })\n return available;\n }) \n }else{\n alerts(\"Select Correct Range\",3000);\n }\n // console.log(resultHotel)\n display(resultHotel);\n range();\n filterByPrice();\n}", "function loadData(start, end){\n var filter = $('#filter').val();\n if ($.isNumeric(filter) == false){\n filter = 1;\n }\n isNewData = true;\n\n var rest_request_values = \"/stream/getstreamdata?streamid=\"+streamId\n +\"&startdate=\"+start.format('YYYY-MM-DD')\n +\"&enddate=\"+end.format('YYYY-MM-DD')\n +\"&filter=\" + filter;\n\n console.log(start.format('YYYY-MM-DD'))\n console.log(end.format('YYYY-MM-DD'))\n\n var rest_request_info = \"/stream/getstreaminfo?streamid=\"+streamId;\n var rest_request_setting = \"/streams/settings?streamid=\"+streamId+\"&msgtype=\"+messageType;\n\n queue()\n .defer(d3.json, rest_request_values)\n .defer(d3.json, rest_request_info)\n .defer(d3.json, rest_request_setting)\n .awaitAll(handleData);\n}", "function loadOpportunitiesByDate(fromDate, toDate) {\r\n return ServeOpportunities.ServeDays.query({\r\n id: Session.exists('userId'),\r\n from: fromDate / 1000,\r\n to: toDate / 1000\r\n }).$promise;\r\n }", "function getEventsForArtistWithinDateRange (artistString,dateRange) {\n\n var artistString = encodeURIComponent(artistString); //convert artist string into correct format for Bandsintown API\n\n\n var dateRange = dateRange;\n\n\n // console.log(\"DATERANGE :\" + dateRange);\n\n var startOfDateRange;\n var endOfDateRange;\n\n //if user gives no time period, then make date range from now until a year from now\n if (dateRange == 'nothing'){\n startOfDateRange = new Date().toJSON().substring(0,10); //get date now and convert into correct format for Bandsintown API\n endOfDateRange = new Date(new Date().setFullYear(new Date().getFullYear() + 1)).toJSON().substring(0,10); //get date a year from now and convert into correct format for Bandsintown API\n\n }\n else {\n //get start and end date from the given date range\n startOfDateRange = dateRange.slice(0, dateRange.indexOf(\"/\"));\n endOfDateRange = dateRange.substring(dateRange.indexOf(\"/\") + 1);\n }\n\n console.log(startOfDateRange)\n console.log(endOfDateRange)\n\n\n\n //return promise to events for artist within date range\n return rp('https://rest.bandsintown.com/artists/'+ artistString + '/events?app_id=concertfinder&date='+startOfDateRange+'%2C'+endOfDateRange); //send request to Bandsintown API\n}", "createDateRange_backup(startDate, endDate, cycle, cyclePeriod)\n {\n \n let out = [];\n let currentDate = moment(startDate);\n let stopDate = moment(endDate);\n\n let period = cycle == enums.timecard.frequency.semimonthly ? 15 : cyclePeriod;\n\n if(cycle == enums.timecard.frequency.daterange)\n {\n out.push( {\n startDate : moment(currentDate).clone().format('YYYY-MM-DD'),\n endDate : moment(endDate).clone().format('YYYY-MM-DD')\n })\n \n }\n else\n { \n while (currentDate <= stopDate) \n {\n // if (maxDate && moment(currentDate).isAfter(maxDate, 'day')) {\n // break;\n // }\n if(cycle == enums.timecard.frequency.monthly)\n {\n out.push( {\n startDate : moment(currentDate).format('YYYY-MM-DD'),\n endDate : moment(currentDate).endOf('month').format('YYYY-MM-DD')\n })\n \n currentDate = moment(currentDate).endOf('month').add(1, 'days');\n }\n else if(cycle == enums.timecard.frequency.semimonthly)\n { \n \n let dt = moment(new Date(currentDate.clone().format('YYYY')+'-'+(currentDate.clone().format('MM'))+'-'+15));\n \n if( currentDate < dt )\n {\n \n out.push({\n startDate : moment(currentDate).format('YYYY-MM-DD'),\n endDate : dt.format('YYYY-MM-DD')\n })\n currentDate = moment(dt.add(1, 'days').format('YYYY-MM-DD'))\n }\n else\n {\n out.push({\n startDate : moment(currentDate).format('YYYY-MM-DD'),\n endDate : dt.endOf('month').format('YYYY-MM-DD')\n })\n currentDate = moment(currentDate.endOf('month').add(1, 'days').format('YYYY-MM-DD'))\n }\n }\n else if(cycle == enums.timecard.frequency.specialcycle)\n {\n \n if( moment(currentDate).clone().format('MM') != moment(currentDate).clone().add(period, 'days').format('MM') )\n {\n out.push( {\n startDate : moment(currentDate).format('YYYY-MM-DD'),\n endDate : moment(currentDate).endOf('month').format('YYYY-MM-DD')\n })\n \n currentDate = moment(currentDate).endOf('month').add(1, 'days');\n }\n else\n {\n out.push( {\n startDate : moment(currentDate).format('YYYY-MM-DD'),\n endDate : moment(currentDate).clone().add(period, 'days').format('YYYY-MM-DD')\n })\n \n currentDate = moment(currentDate).add(period+1, 'days');\n }\n \n }\n else if(cycle == enums.timecard.frequency.biweekly) \n {\n out.push( {\n startDate : moment(currentDate).format('YYYY-MM-DD'),\n endDate : moment(currentDate).endOf('isoWeek').add(1, 'days').endOf('isoWeek').format('YYYY-MM-DD')\n })\n currentDate = moment(currentDate).endOf('isoWeek').add(1, 'days').endOf('isoWeek').add(1, 'days');\n }\n else if(cycle == enums.timecard.frequency.weekly) \n {\n if( moment(currentDate).clone().format('MM') != moment(currentDate).clone().endOf('isoWeek').add(1, 'days').format('MM') )\n {\n out.push( {\n startDate : moment(currentDate).format('YYYY-MM-DD'),\n endDate : moment(currentDate).endOf('month').format('YYYY-MM-DD')\n })\n \n currentDate = moment(currentDate).endOf('month').add(1, 'days');\n }\n else\n {\n out.push( {\n startDate : moment(currentDate).format('YYYY-MM-DD'),\n endDate : moment(currentDate).endOf('isoWeek').format('YYYY-MM-DD')\n })\n currentDate = moment(currentDate).endOf('isoWeek').add(1, 'days');\n }\n }\n else\n {\n out.push([])\n }\n }\n }\n\n\n return _.orderBy(out, ['startDate'],['desc']);\n \n }", "function getdata() {\n faxianSearchInfo.addition_search.first_start_time_or = getMonthStartDate()\n faxianSearchInfo.addition_search.last_start_time_or = getMonthEndDate()\n}", "function dieselBetweenDates(startDate, endDate, list) {\n let datearray = [];\n return new Promise((resolve, reject) => {\n list.forEach(element => { //filter list according to date comparison\n // console.log(moment(element.createdDate, \"YYYY-MM-DD\"))\n let dbdate = moment(element.date, \"YYYY-MM-DD\");\n // console.log(moment(inputdate).isSame(dbdate,'date'))\n if (moment(startDate).isSame(endDate, 'date')) {\n if (moment(startDate).isSame(dbdate, 'date')) {\n datearray.push(element);\n }\n }\n else {\n if (moment(dbdate).isBetween(startDate, endDate, null, '[]')) {\n console.log('date matched')\n datearray.push(element);\n // console.log(montharray)\n }\n }\n\n })\n resolve(datearray)\n })\n}", "dateChanged(changedData) {\n const value = changedData.day;\n const isLeft = changedData.isLeft;\n if (isLeft) {\n this.fromDate = value;\n if (this.fromDate.isAfter(this.toDate, 'date')) {\n this.toDate = this.fromDate.clone();\n }\n }\n else {\n this.toDate = value;\n if (this.toDate.isBefore(this.fromDate, 'date')) {\n this.fromDate = this.toDate.clone();\n }\n }\n this.setFromToMonthYear(this.fromDate, this.toDate);\n if (this.isAutoApply() && (this.options.singleCalendar || !isLeft) && this.fromDate) {\n this.toggleCalendarVisibility(false);\n this.setRange();\n this.emitRangeSelected();\n }\n }", "function move2Latest() {\r\nconsole.log('move2Latest:', sensorEndDate);\r\n //$(\"#date2\").val(new Date(sensorEndDate).toISOString().split('T')[0]); //DAY AFTER\r\n setEndRange(new Date(sensorEndDate), 0);\r\n setStartRange(new Date(sensorEndDate), $(\"#qryRangeDD\").val());\r\n $('#fwd').addClass('disabled');\r\n $('#fwdEnd').addClass('disabled');\r\n //timelineType();\r\n}", "function previousStates() {\n filter.end = filter.start;\n filter.start = moment(filter.start).subtract(globalTime, globalTimeRange).format('YYYY-MM-DD HH:mm:ss');\n $('#daterangepicker').data('daterangepicker').setStartDate(moment(filter.start).format('l[, ]LTS'));\n $('#daterangepicker').data('daterangepicker').setEndDate(moment(filter.end).format('l[, ]LTS'));\n refreshData();\n }", "linkOperationIfExist (entry, callback) {\n let date = new Date(entry.paidDate || entry.date)\n let startDate = moment(date).subtract(this.minDateDelta, 'days')\n let endDate = moment(date).add(this.maxDateDelta, 'days')\n\n let startkey = `${startDate.format('YYYY-MM-DDT00:00:00.000')}Z`\n let endkey = `${endDate.format('YYYY-MM-DDT00:00:00.000')}Z`\n\n BankOperation.all({\n date: {\n '$gt': startkey,\n '$lt': endkey\n }\n }, (err, operations) => {\n if (err) {\n debug(err, 'error while fetching all the bank operations')\n return callback(err)\n }\n this.linkRightOperation(operations, entry, callback)\n })\n }", "get dates() {\n const { from, to, query, timeRegistrations } = this.store;\n let dates = [];\n if (query) {\n dates = [...new Set(timeRegistrations.map(r => r.date))].sort((a, b) => a < b);\n } else {\n let days = differenceInDays(to, from) + 1;\n for (let i = 0; i < days; i++) {\n let date = new Date(from);\n date.setDate(date.getDate() + i);\n dates.push(date);\n }\n }\n return dates;\n }", "function Query_If_RangeHasChanged(){\n\n var sFrom = document.getElementById(\"txt_dtmFrom\").value;\n var sTo = document.getElementById(\"txt_dtmTo\").value;\n\n if(sFrom != sParamDateFrom || sTo != sParamDateTo)\n ExecuteNewSearch();\n}", "function setupDateQuery( params ) {\n if( 'all' !== params.dateFrom ) {\n // we will not always provide a time range\n if( !params.duration && !params.dateTo ) {\n params.duration = 'day';\n }\n\n if( 'now' === params.dateFrom ) {\n params.dateFrom = moment();\n } else if( 'today' === params.dateFrom ) {\n params.dateFrom = moment().startOf( 'day' );\n }\n\n if( params.duration ) {\n params.dateFrom = moment( params.dateFrom );\n if( !params.dateFrom.isValid() ) {\n return false;\n }\n }\n }\n return true;\n }", "function blinds_1(result)\n{\n console.log(\"blinds_1\")\n console.log(result);\n var date = new Date(1528214746 *999);\n if(first)\n {\n fakehistoricadata(date.toString().substr(0,24))\n first = false;\n }\n \n updateBlinds(result);\n}", "function filterDataByDate(sample){\r\n\t\t\treturn (Date.parse(sample.date_local) == Date.parse(dateselector.node().value));\r\n\t\t\t}", "findShallowIntersectingRange(date1, date2) {\n const thisRange = date1.toRange();\n const otherRange = date2.toRange(); // Start with infinite start and end dates\n\n let start = null;\n let end = null; // This start date exists\n\n if (thisRange.start) {\n // Use this definite start date if other start date is infinite\n if (!otherRange.start) {\n start = thisRange.start;\n } else {\n // Otherwise, use the earliest start date\n start = thisRange.start < otherRange.start ? thisRange.start : otherRange.start;\n } // Other start date exists\n\n } else if (otherRange.start) {\n // Use other definite start date as this one is infinite\n start = otherRange.start;\n } // Assign end date to this one if it is valid\n\n\n if (thisRange.end && (!start || thisRange.end >= start)) {\n end = thisRange.end;\n } // Assign end date to other one if it is valid and before this one\n\n\n if (otherRange.end && (!start || otherRange.end >= start)) {\n if (!end || otherRange.end < end) end = otherRange.end;\n } // Return calculated range\n\n\n return {\n start,\n end\n };\n }", "findShallowIntersectingRange(date1, date2) {\n const thisRange = date1.toRange();\n const otherRange = date2.toRange(); // Start with infinite start and end dates\n\n let start = null;\n let end = null; // This start date exists\n\n if (thisRange.start) {\n // Use this definite start date if other start date is infinite\n if (!otherRange.start) {\n start = thisRange.start;\n } else {\n // Otherwise, use the earliest start date\n start = thisRange.start < otherRange.start ? thisRange.start : otherRange.start;\n } // Other start date exists\n\n } else if (otherRange.start) {\n // Use other definite start date as this one is infinite\n start = otherRange.start;\n } // Assign end date to this one if it is valid\n\n\n if (thisRange.end && (!start || thisRange.end >= start)) {\n end = thisRange.end;\n } // Assign end date to other one if it is valid and before this one\n\n\n if (otherRange.end && (!start || otherRange.end >= start)) {\n if (!end || otherRange.end < end) end = otherRange.end;\n } // Return calculated range\n\n\n return {\n start,\n end\n };\n }", "getComingEvnts() {\n let today = new Date()\n return new Promise ((resolve, reject) => {\n connection.query('SELECT * FROM Arrangement WHERE Arrangement.start > ?',[today], (error, result) => {\n if (error) throw error;\n resolve(result)\n });\n });\n }", "function findWatcherMatches(ticketRecord){\n console.log('findTicketMatches: called');\n var maxDate = new Date(ticketRecord.date);\n var minDate = new Date(ticketRecord.date);\n minDate.setHours(minDate.getHours() - 24);\n \n console.log(minDate, maxDate);\n db.Watcher.findAll({\n where: {\n OrganizationId: ticketRecord.OrganizationId,\n eventDate: {\n [Op.lte]: maxDate,\n [Op.gte]: minDate \n }\n }\n }).then(function(dbWatchers) {\n console.log(\"hey\", JSON.stringify(dbWatchers, null, 4));\n\n dbWatchers.forEach(function(singleWatcherMatch) {\n writeMatch(singleWatcherMatch, ticketRecord);\n });\n }).catch(function(err) {\n \n res.status(500).json(err);\n });\n }", "function getDateRange(dataPassed){\r\n //called by slider start & end dates\r\n //get first object in dataPassed array, and get the date\r\n firstObj=dataPassed.filter(function(d,i){\r\n return i==0\r\n });\r\n //get last object in dataPassed array, and get the date\r\n lastObj = dataPassed.filter(function(d,i){\r\n return i==dataPassed.length-1\r\n });\r\n datefrom = firstObj[0].Day;\r\n dateto=lastObj[0].Day;\r\n datejson = {'start':datefrom,'end':dateto};\r\n return datejson;\r\n }", "resetDateRange() {\n var beg, end;\n beg = Data.toDateStr(Data.begDay, Data.monthIdx);\n end = Data.advanceDate(beg, Data.numDays - 1);\n return this.res.dateRange(beg, end, this.resetRooms);\n }", "static getData() {\r\n return getWeatherReports({\r\n startDate: new Date(new Date().setDate(new Date().getDate() - 7)),\r\n endDate: new Date()\r\n });\r\n }", "function getMonthlyPatrons (startDate, endDate) {\n let queryString = `SELECT DISTINCT clients.id, clients.name FROM invoices INNER JOIN sales ON invoices.id = sales.invoiceId INNER JOIN products ON sales.productId = products.id INNER JOIN conversionFactors ON products.id = conversionFactors.productId INNER JOIN clients ON invoices.clientId = clients.id WHERE invoices.date BETWEEN '${startDate}' AND '${endDate}' ORDER BY clients.id;`\n return db.sequelize\n .query(queryString)\n .spread((data, meta) => Promise.resolve(data))\n .catch(error => {\n logging.error(\n error,\n './modules/queries/products.getMonthlyPatrons() errored'\n )\n return Promise.reject(error)\n })\n}", "filterBySearchDate(fieldName, operator, searchTerms, version) {\n let query = '';\n let searchValues;\n if (Array.isArray(searchTerms) && searchTerms.length > 1) {\n searchValues = searchTerms;\n if (operator !== OperatorType.rangeExclusive && operator !== OperatorType.rangeInclusive) {\n operator = this._gridOptions.defaultFilterRangeOperator;\n }\n }\n // single search value\n if (!Array.isArray(searchValues) && Array.isArray(searchTerms) && searchTerms.length === 1 && searchTerms[0]) {\n const searchValue1 = this.odataQueryVersionWrapper('dateTime', version, fieldName, parseUtcDate(searchTerms[0], true));\n if (searchValue1) {\n return `${fieldName} ${this.mapOdataOperator(operator)} ${searchValue1}`;\n }\n }\n // multiple search value (date range)\n if (Array.isArray(searchValues) && searchValues.length === 2 && searchValues[0] && searchValues[1]) {\n // date field needs to be UTC and within DateTime function\n const searchValue1 = this.odataQueryVersionWrapper('dateTime', version, fieldName, parseUtcDate(searchValues[0], true));\n const searchValue2 = this.odataQueryVersionWrapper('dateTime', version, fieldName, parseUtcDate(searchValues[1], true));\n if (searchValue1 && searchValue2) {\n if (operator === OperatorType.rangeInclusive) {\n // example:: (Finish >= DateTime'2019-08-11T00:00:00Z' and Finish <= DateTime'2019-09-12T00:00:00Z')\n query = `(${fieldName} ge ${searchValue1} and ${fieldName} le ${searchValue2})`;\n }\n else if (operator === OperatorType.rangeExclusive) {\n // example:: (Finish > DateTime'2019-08-11T00:00:00Z' and Finish < DateTime'2019-09-12T00:00:00Z')\n query = `(${fieldName} gt ${searchValue1} and ${fieldName} lt ${searchValue2})`;\n }\n }\n }\n return query;\n }", "filterBySearchDate(fieldName, operator, searchTerms, version) {\n let query = '';\n let searchValues;\n if (Array.isArray(searchTerms) && searchTerms.length > 1) {\n searchValues = searchTerms;\n if (operator !== OperatorType.rangeExclusive && operator !== OperatorType.rangeInclusive) {\n operator = this._gridOptions.defaultFilterRangeOperator;\n }\n }\n // single search value\n if (!Array.isArray(searchValues) && Array.isArray(searchTerms) && searchTerms.length === 1 && searchTerms[0]) {\n const searchValue1 = this.odataQueryVersionWrapper('dateTime', version, fieldName, parseUtcDate(searchTerms[0], true));\n if (searchValue1) {\n return `${fieldName} ${this.mapOdataOperator(operator)} ${searchValue1}`;\n }\n }\n // multiple search value (date range)\n if (Array.isArray(searchValues) && searchValues.length === 2 && searchValues[0] && searchValues[1]) {\n // date field needs to be UTC and within DateTime function\n const searchValue1 = this.odataQueryVersionWrapper('dateTime', version, fieldName, parseUtcDate(searchValues[0], true));\n const searchValue2 = this.odataQueryVersionWrapper('dateTime', version, fieldName, parseUtcDate(searchValues[1], true));\n if (searchValue1 && searchValue2) {\n if (operator === OperatorType.rangeInclusive) {\n // example:: (Finish >= DateTime'2019-08-11T00:00:00Z' and Finish <= DateTime'2019-09-12T00:00:00Z')\n query = `(${fieldName} ge ${searchValue1} and ${fieldName} le ${searchValue2})`;\n }\n else if (operator === OperatorType.rangeExclusive) {\n // example:: (Finish > DateTime'2019-08-11T00:00:00Z' and Finish < DateTime'2019-09-12T00:00:00Z')\n query = `(${fieldName} gt ${searchValue1} and ${fieldName} lt ${searchValue2})`;\n }\n }\n }\n return query;\n }", "function refreshDateList(currentDate) {\n currentDate = resetHMSM(currentDate);\n $scope.currentDate = angular.copy(currentDate);\n\n var firstDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1).getDate();\n var lastDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0).getDate();\n\n $scope.monthsList = [];\n if ($scope.mainObj.monthsList && $scope.mainObj.monthsList.length === 12) {\n $scope.monthsList = $scope.mainObj.monthsList;\n } else {\n $scope.monthsList = IonicDatepickerService.monthsList;\n }\n\n $scope.yearsList = IonicDatepickerService.getYearsList($scope.mainObj.from, $scope.mainObj.to);\n\n $scope.dayList = [];\n $scope.eventList = [];\n\n var tempDate, disabled;\n $scope.firstDayEpoch = resetHMSM(new Date(currentDate.getFullYear(), currentDate.getMonth(), firstDay)).getTime();\n $scope.lastDayEpoch = resetHMSM(new Date(currentDate.getFullYear(), currentDate.getMonth(), lastDay)).getTime();\n\n $scope.eventList = [];\n var hasEvents = false;\n var eventsTimestamps = [];\n var eventsContent = [];\n\n if ($scope.mainObj.events != null && $scope.mainObj.events.length > 0) {\n\n hasEvents = true;\n for (var i = 0; i < $scope.mainObj.events.length; i++) {\n var exists = false;\n var event = $scope.mainObj.events[i];\n\n eventsTimestamps.push(parseInt(event.date.getFullYear() + \"\" + event.date.getMonth() + \"\" + event.date.getDate()));\n eventsContent.push(event);\n\n for (var j = 0; j < $scope.eventList.length; j++) {\n if ($scope.eventList[j].type === event.type) {\n exists = true;\n break;\n }\n }\n\n if (exists) {\n continue;\n }\n\n $scope.eventList.push(event);\n\n }\n\n }\n\n for (var i = firstDay; i <= lastDay; i++) {\n tempDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), i);\n disabled = (tempDate.getTime() < $scope.fromDate) || (tempDate.getTime() > $scope.toDate) || $scope.mainObj.disableWeekdays.indexOf(tempDate.getDay()) >= 0;\n var _events = [];\n\n if (hasEvents) {\n var dateLong = parseInt(tempDate.getFullYear() + \"\" + tempDate.getMonth() + \"\" + tempDate.getDate());\n var index = -1;\n do {\n index = eventsTimestamps.indexOf(dateLong);\n if (index > -1) {\n var _event = getEvent(index, eventsTimestamps, eventsContent);\n if (_event.disabled) {\n disabled = true;\n }\n _events.push(_event);\n }\n } while (index > -1);\n }\n\n var dayList = {\n date: tempDate.getDate(),\n month: tempDate.getMonth(),\n year: tempDate.getFullYear(),\n day: tempDate.getDay(),\n epoch: tempDate.getTime(),\n disabled: disabled,\n eventList: _events\n };\n\n $scope.dayList.push(dayList);\n }\n\n //To set Monday as the first day of the week.\n var firstDayMonday = $scope.dayList[0].day - $scope.mainObj.mondayFirst;\n firstDayMonday = (firstDayMonday < 0) ? 6 : firstDayMonday;\n\n for (var j = 0; j < firstDayMonday; j++) {\n $scope.dayList.unshift({});\n }\n\n $scope.rows = [0, 7, 14, 21, 28, 35];\n $scope.cols = [0, 1, 2, 3, 4, 5, 6];\n\n $scope.hasValue = [];\n\n $scope.data.currentMonth = $scope.mainObj.monthsList[currentDate.getMonth()];\n $scope.data.currentYear = currentDate.getFullYear();\n $scope.data.currentMonthSelected = angular.copy($scope.data.currentMonth);\n $scope.currentYearSelected = angular.copy($scope.data.currentYear);\n $scope.numColumns = 7;\n\n for (var i = 0; i < $scope.rows.length; i++) {\n var hasValue = false;\n for (var j = 0; j < $scope.cols.length; j++) {\n var index = $scope.rows[i] + $scope.cols[j];\n if ($scope.dayList[index] !== undefined) {\n hasValue = true;\n break;\n }\n }\n $scope.hasValue.push(hasValue);\n }\n }", "function getFilteredReservationByDate(roomUsages, date, dateEnd){\n\tvar dateFilteredReservations = [];\n\tif(date == null && dateEnd == null){\n\t\tlog(reservations);\n\t\treturn reservations;\n\t} else if (date != null && dateEnd == null) {\n\t\t$.when($.each(roomUsages , function(index, reservation){\n\t\t\tif(reservation.reservedDate == date){\n\t\t\t\tdateFilteredReservations.push(reservation);\n\t\t\t}\n\t\t})).then(function(noResult){\n\t\t\tlog(dateFilteredReservations);\n\t\t\treturn dateFilteredReservations;\n\t\t});\n\t} else if (date != null && dateEnd != null) {\n\t\t$.when($.each(roomUsages , function(index, reservation){\n\t\t\tif(date <= reservation.reservedDate && reservation.reservedDate <= dateEnd){\n\t\t\t\tdateFilteredReservations.push(reservation);\n\t\t\t}\n\t\t})).then(function(noResult){\n\t\t\tlog(dateFilteredReservations);\n\t\t\treturn dateFilteredReservations;\n\t\t});\n\t} else {\n\t\talert(\"No Result Cursed by Missing of Argument\");\n\t}\n}", "function getFBPageData(initialResults, callback) {\n graph.setAccessToken(initialResults.profile.accessToken);\n async.auto({\n get_start_end_dates: getDates,\n get_object_list: ['get_start_end_dates', passQueryToGraphApi]\n }, function (err, results) {\n if (err) {\n return callback(err, null);\n }\n callback(null, results.get_object_list[0]);\n });\n\n //To get the start date ,end date required for query\n function getDates(callback) {\n var d = new Date();\n var queryObject = {};\n\n //check already there is one year data in db\n if (initialResults.data != null) {\n d.setDate(d.getDate());\n if (initialResults.data.updated < new Date()) {\n var endDate = initialResults.data.updated;\n endDate.setDate(endDate.getDate() + 1);\n var updated = moment(endDate).format('YYYY-MM-DD');\n d.setDate(d.getDate() + 1);\n var now = moment(d).format('YYYY-MM-DD');\n var query = initialResults.object.channelObjectId + \"/insights/\" + initialResults.metric.objectTypes[0].meta.fbMetricName + \"?since=\" + updated + \"&until=\" + now;\n queryObject = {\n query: query, metricId: initialResults.metric._id, metric: initialResults.metric,\n startDate: updated,\n endDate: now\n };\n callback(null, queryObject);\n }\n else {\n var endDate = initialResults.data.updated;\n endDate.setDate(endDate.getDate() + 1);\n var updated = moment(endDate).format('YYYY-MM-DD');\n d.setDate(d.getDate() + 1);\n var now = moment(d).format('YYYY-MM-DD');\n queryObject = {\n query: 'DataFromDb', metricId: initialResults.metric._id, metric: initialResults.metric,\n startDate: updated,\n endDate: now\n };\n callback(null, queryObject);\n }\n\n }\n }\n\n //To pass the query to graph api\n function passQueryToGraphApi(query, callback) {\n if (typeof query.query == 'string')\n async.map([query], getDataForAllQuery, callback);\n else\n async.map(query, getDataForAllQuery, callback);\n }\n\n //Get final data for all queries\n function getDataForAllQuery(query, callback) {\n var queryResponse = {};\n if (query.query == 'DataFromDb') {\n queryResponse = {\n res: 'DataFromDb',\n metricId: query.metricId,\n queryResults: initialResults,\n channelId: initialResults.metric.channelId,\n startDate: query.startDate,\n endDate: query.endDate,\n metric: initialResults.metric\n }\n callback(null, queryResponse);\n }\n else {\n graph.get(query.query, function (err, fbQueryRes) {\n if (err) {\n if (err.code === 190)\n return res.status(401).json({error: 'Authentication required to perform this action'})\n else if (err.code === 4)\n return res.status(4).json({error: 'Forbidden Error'})\n else\n return res.status(500).json({error: 'Internal server error'})\n }\n\n else {\n queryResponse = {\n res: fbQueryRes,\n metricId: query.metricId,\n queryResults: initialResults,\n channelId: initialResults.metric.channelId,\n metric: initialResults.metric,\n startDate: query.startDate,\n endDate: query.endDate,\n }\n callback('', queryResponse);\n }\n })\n\n }\n }\n }", "function validateSelectedDates(dataSource, startDate, endDate){\n\t\t for(var i in dataSource) {\t\n \t \tif((dataSource[i].startDate.getTime() >= startDate.getTime() && dataSource[i].startDate.getTime() <= endDate.getTime())\t||\n \t \t (dataSource[i].endDate.getTime() <= endDate.getTime() && dataSource[i].endDate.getTime() >= startDate.getTime()) ||\n \t \t (startDate.getTime() >= dataSource[i].startDate.getTime() && startDate.getTime() <= dataSource[i].endDate.getTime())){\n \t \t\treturn false;\n \t \t}\n }\n\t\t return true;\n\t}", "onUpdateDailyDate(date) {\n const utcDate = moment.utc(date.format('YYYY-MM-DD'), 'YYYY-MM-DD');\n const params = propOrDefault(this.props, true);\n const start = utcDate.clone().startOf('day');\n const end = utcDate.clone().endOf('day');\n\n const minDiffernceHour = getMinDiffHours();\n const isAheadOfUTC = isAheadUTC();\n\n\n this.props.fetchResultSummary({\n ...params,\n 'start_time': isAheadOfUTC ? start.subtract(minDiffernceHour, 'h').format('X') : start.add(minDiffernceHour, 'h').format('X'),\n 'end_time': isAheadOfUTC ? end.subtract(minDiffernceHour, 'h').format('X') : end.add(minDiffernceHour, 'h').format('X'),\n 'summary_range': 60,\n 'fetchHoursPerDay': true,\n });\n }", "function loadBookings() {\n appointmentAPI.findAll()\n .then(res => {\n setRows(() => { \n for(let datas of res.data) {\n // Get today's date\n let todaysDate = new Date();\n \n let dateReq = datas.datereq;\n \n dateReq = new Date(dateReq);\n \n if (datas.iscompleted === false && dateReq > todaysDate ) {\n datas.iscompleted = true;\n rows.push(datas)\n }\n }\n })\n // console.log(rows);\n\n //sets the columns and rows with the data returned\n setDatatable({columns: [\n {\n label: 'Name',\n field: 'name',\n width: 150,\n attributes: {\n 'aria-controls': 'DataTable',\n 'aria-label': 'Name',\n },\n },\n {\n label: 'Phone',\n field: 'phone',\n width: 270,\n },\n {\n label: 'Adress',\n field: 'address1', \n width: 200,\n },\n {\n label: 'Zip',\n field: 'zip',\n width: 200,\n },\n {\n label: 'City',\n field: 'city',\n sort: 'disabled',\n width: 100,\n },\n {\n label: 'Date',\n field: 'datereq',\n sort: 'asc',\n width: 100,\n },\n {\n label: 'Time',\n field: 'timereq',\n sort: 'disabled',\n width: 150,\n },\n {\n label: 'Service',\n field: 'servicerequested',\n sort: 'disabled',\n width: 150,\n },\n {\n label: 'Email',\n field: 'email',\n width: 270,\n },\n ], rows : rows,\n });\n\n });\n }", "async getAll(params) {\n\t\tlet selectFrom;\n\t\tlet selectTo;\n\t\tif (params.from && params.to) {\n\t\t\tselectFrom = params.from.date();\n\t\t\tselectTo = params.to.date();\n\t\t}\n\n\t\tconst entriesToLoad = [];\n\t\tfor (let i in this._datastore) {\n\t\t\tconst event = this._datastore[i];\n\t\t\tif (selectFrom && selectTo) {\n\t\t\t\tif (event.end_date >= selectFrom && event.start_date < selectTo) {\n\t\t\t\t\tentriesToLoad.push(event);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tentriesToLoad.push(event);\n\t\t\t}\n\t\t}\n\n\t\tconst result = entriesToLoad.map((entry) => {\n\t\t\tvar serialized = Object.assign({}, entry);\n\t\t\tfor (let i in serialized) {\n\t\t\t\tif (Object.prototype.toString.call(serialized[i]) === \"[object Date]\") {\n\t\t\t\t\tserialized[i] = serialized[i].format(\"YYYY-MM-DD hh:mm\");\n\t\t\t\t} else if (typeof serialized[i] === \"string\") {\n\t\t\t\t\tserialized[i] = xssFilters.inHTMLData(serialized[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn serialized;\n\t\t});\n\n\t\tif(this._params.objectResult || this._params.collections){\n\t\t\tvar res = {\n\t\t\t\tdata: result\n\t\t\t};\n\t\t\tif(this._params.collections){\n\t\t\t\tres.collections = this._params.collections\n\t\t\t};\n\t\t\treturn res;\n\t\t}else{\n\t\t\treturn result;\n\t\t}\n\t}", "function getPlayerStatsStartEnd(team, startDate, endDate, player, format) {\n\n var allStats = new Array();\n if (format) {\n var startYear = startDate.substring(0, 4);\n var startMonth = startDate.substring(4, 6);\n var startDay = startDate.substring(6, 8);\n\n var endYear = endDate.substring(0, 4);\n var endMonth = endDate.substring(4, 6);\n var endDay = endDate.substring(6, 8);\n\n var start = new Date(startMonth + \"/\" + startDay + \"/\" + startYear);\n var end = new Date(endMonth + \"/\" + endDay + \"/\" + endYear);\n } else {\n var start = startDate;\n var end = endDate;\n }\n console.log(start);\n console.log(end);\n console.log(start < end)\n return promiseWhile(function() {\n return start < end;\n }, function() {\n\n var dateStr = moment(start).format('YYYY/MM/DD');\n var formattedDate = dateStr.split(\"/\").reduce((cur, value) => {\n return cur + value;\n })\n console.log(formattedDate)\n\n return getPlayerStats(team, formattedDate, player).then((response) => {\n if (!response) {} else {\n allStats.push(response[0]);\n console.log(allStats.length)\n }\n\n var newDate = start.setDate(start.getDate() + 1);\n start = new Date(newDate);\n return allStats;\n })\n }).then((response) => {\n //console.log(response)\n return allStats;\n })\n\n}", "function main() {\n // OBTIAN AN ARRAY OF START AND END DATES\n var startDate = findStartAndEndDate()[0];\n var endDate = findStartAndEndDate()[1];\n // var start = formatDate(findStartAndEndDate()[0]);\n // var end = formatDate();\n\n var listOfDates = [];\n listOfDates.push(formatDate(startDate));\n\n var year = parseInt(startDate.split(\"-\")[0]);\n var month = parseInt(startDate.split(\"-\")[1]);\n var date = parseInt(startDate.split(\"-\")[2]);\n\n do {\n var nextDate = findNdaysAfter(year, month, date, 1);\n year = parseInt(nextDate.split(\"-\")[0]);\n month = parseInt(nextDate.split(\"-\")[1]);\n date = parseInt(nextDate.split(\"-\")[2]);\n listOfDates.push(formatDate(nextDate));\n } while (nextDate != endDate);\n //console.log(listOfDates);\n // return listOfDates;\n module.exports = listOfDates;\n}", "function getDataUrl(){\n //var now = new Date().getTime();\n var lastDT = new Date(sensorEndDate).getTime();\n //console.log(typeof(now), now, typeof(sensorEndDate), sensorEndDate);\n var diff = 1000*3600*24*7;\n //var startSpan = new Date(now-diff);\n var startSpan = new Date(lastDT-diff);\n //console.log(startSpan.toISOString(), startSpan);\n// var startTxt = \"&time>=\"+startSpan.getFullYear().toString()+\"-\"+(\"0\" + (startSpan.getMonth() + 1)).slice(-2)+\"-01T00:00:00Z\"; //older.getMonth()+1;\n var startTxt = \"&time>=\"+startSpan.toISOString();\n\n // jsonUrl = baseJSON+'?station,time,'+attr;\n // csvUrl = baseERDDAP+'.csv'+'?station,time,'+attr;\n urlEnd = '?station,time,'+attr;\n if ($(\"#onlyQC\").prop('checked')) {\n // jsonUrl += '&'+attr+'_flagPrimary=1';\n if (flagsArr.indexOf(attr) > -1) urlEnd += '&'+attr+'_flagPrimary=1';\n } else if (flagsArr.indexOf(attr) > -1) {\n // jsonUrl += ','+attr+'_flagPrimary'+','+attr+'_flagSecondary';\n urlEnd += ','+attr+'_flagPrimary'+','+attr+'_flagSecondary';\n }\n //htmlUrl = baseERDDAP+'.html'+urlEnd+'&station=\"'+sensor+'\"'+'&orderBy(%22time%22)';\n // jsonUrl += '&station=\"'+sensor+'\"'+startTxt+'&orderBy(%22time%22)';\n urlEnd += '&station=\"'+sensor+'\"'+startTxt+'&orderBy(%22time%22)';\n jsonUrl = baseJSON+urlEnd;\n csvUrl = baseERDDAP+'.csvp'+urlEnd\n\n $('#getCSV').attr('href', csvUrl);\n //$('#access').attr('href', htmlUrl);\n return jsonUrl;\n}", "function refreshCurrentDate() {\n\t\t\t\tdateCurrent = getDateInRange(dateCurrent, dateShadow, before, after);\n\t\t\t}", "filterData(filter) {\r\n const scope = this,\r\n startDate = new Date(filter.dates.start),\r\n endDate = new Date(filter.dates.end),\r\n sTime = filter.time.start,\r\n eTime = filter.time.end;\r\n let filteredData = [], date, startTime, endTime;\r\n\r\n scope.tempData = [];\r\n startDate.setHours(0, 0, 0);\r\n endDate.setHours(23, 59, 59);\r\n\r\n sTime.meridian === \"AM\" ?\r\n (startTime = sTime.h * 60 + sTime.m) : (startTime = sTime.h * 60 + sTime.m + 720);\r\n eTime.meridian === \"AM\" ?\r\n (endTime = eTime.h * 60 + eTime.m) : (endTime = eTime.h * 60 + eTime.m + 720);\r\n\r\n scope.totalData.forEach(v => {\r\n date = new Date(v.interval_start);\r\n\r\n if(date.getTime() >= startDate.getTime() && endDate.getTime() >= date.getTime()){\r\n let selTime = date.getHours() * 60 + date.getMinutes();\r\n if(selTime >= startTime && endTime > selTime){\r\n filteredData.push(v)\r\n }\r\n }\r\n });\r\n\r\n for(let key = sTime.h; key <= (eTime.meridian === \"AM\" ? eTime.h : eTime.h + 12); key++){\r\n if(!(key === (eTime.meridian === \"AM\" ? eTime.h : eTime.h + 12) && eTime.m === 0))\r\n scope.tempData.push({time: key, occupancy: []})\r\n }\r\n\r\n return scope.hourlyData(filteredData)\r\n }", "function processData(data, previous) {\n results=data.results;\n for(i=0; i<results.length; i++){\n event=results[i];\n start_date=event.details.start_date;\n inDate=Date.parse(start_date);\n now =Date.now();\n if(inDate < now && !previous){\n continue;\n }\n if(inDate > now && previous){\n continue;\n }\n title=event.title;\n url=event.web_url;\n end_date=event.details.end_date;\n locations=event.details.location;\n booknow=event.details.booking_url;\n event_type=event.details.event_type;\n console.log(start_date);\n\n addEventToPage(title, url, start_date, locations, booknow, event_type, end_date);\n }\n}", "function loadDates(){\n var rest_request_dates = \"/stream/getstreamdates?streamid=\"+streamId;\n queue()\n .defer(d3.json, rest_request_dates)\n .awaitAll(loadDateRangePicker);\n}", "function retrieveAllOnDate(req, res, next){\n // *Getting the master resource id:\n let id = req.params.id;\n let date = req.params.date;\n\n // *Querying the database for all resources:\n let options = {\n sql: 'select ??.*, ??.* from ?? inner join ?? on ?? = ??.?? where ?? = ? and ? between DATE(??) and DATE(??)',\n nestTables: true\n };\n pooler.query(options, ['vehicle', 'schedule', 'vehicle', 'schedule', 'id_vehicle_fk', 'vehicle', 'id', 'id_user_fk', id, date, 'start_date', 'end_date'])\n .then(result => {\n // *Sending the resources as response:\n res.status(200)\n .json(result.rows)\n .end();\n })\n .catch(err => {\n // *If something went wrong:\n // *Sending a 500 error response:\n res.status(500)\n .json({err_code: 'ERR_INTERNAL', err_message: 'Something went wrong'})\n .end();\n });\n}", "onDateChanged(selectedDate, doctorIdHostpitalId) {\n\n let { selectedDatesByDoctorIds, selectedSlotByDoctorIds, selectedSlotItemByDoctorIds } = this.state;\n\n selectedDatesByDoctorIds[doctorIdHostpitalId] = selectedDate;\n selectedSlotByDoctorIds[doctorIdHostpitalId] = -1;\n selectedSlotItemByDoctorIds[doctorIdHostpitalId] = null;\n\n this.setState({ selectedDatesByDoctorIds, selectedSlotByDoctorIds, selectedSlotItemByDoctorIds, refreshCount: this.state.refreshCount + 1 });\n\n if (this.processedDoctorAvailabilityDates.includes(selectedDate) === false) {\n let endDateMoment = addMoment(getMoment(selectedDate), 7, 'days');\n\n this.callGetAvailabilitySlot(this.state.getSearchedDoctorIds, getMoment(selectedDate), endDateMoment);\n\n }\n \n }", "static async getDates(startDate, endDate, username){\n\n const user = await db.query(\n `SELECT id from users WHERE username = $1`, [username]\n );\n\n let id = user.rows[0].id\n\n const entries = await db.query(\n `SELECT user_weight, date_weighed\n FROM user_weights WHERE user_id = $1 AND\n date_weighed BETWEEN '${startDate}'\n AND '${endDate}'\n ORDER BY date_weighed ASC`, [id]\n );\n \n if(entries.rows.length === 0) {\n throw new ExpressError('No dates found', 404);\n }\n\n return entries.rows;\n }", "function getRec(start, end) {\r\n\r\n //var baseURL = \"https://wistg.toronto.ca/inter/edc/festevents.nsf/api/data/collections/name/export?start=<start>&count=100\";\r\n var baseURL = \"http://dom01d.toronto.ca/inter/edc/festevents.nsf/api/data/collections/name/export?start=<start>&count=100\"\r\n var url = baseURL.replace('<start>',start);\r\n var request = $.ajax({\r\n type: 'GET',\r\n url: url,\r\n cache: false,\r\n crossDomain: true,\r\n dataType: 'json',\r\n success: function (data) {\r\n console.log(\"Start: \" + start + \" - found \" + data.length + \" rows\");\r\n $.each(data, function( index, row ) {\r\n eventHeaderJson.push(row);\r\n });\r\n\r\n },\r\n error: function (xhr, ajaxOptions, thrownError) {\r\n console.log(xhr.status);\r\n console.log(thrownError);\r\n }\r\n });\r\n return request;\r\n}", "function queryEqualDate(path,key,date,criteria){\n\t\tif(!(date==null || date==\"\")) {\n\t\t\tstartAt=date+\"T00:00:00\";\n\t\t\tendAt=date+\" 23:59:59\";\n\t\t\tqueryBetween(path,key,startAt,endAt,criteria)\n\t\t}\n\t\telse throw {\"message\":\"Date cannot be null\"};\n\t}", "function queryNearlyAWeekWorkDetailInfo(){\n\t //queryNearlyAWeekWorkDetailInfo work\n\t var id = $(\"#eeid\").val();\n\t var dateStr = test();\n\t var dateTime = new Array();\n\t \tdateTime[0] = 0;\n\t\tdateTime[1] = 0;\n\t\tdateTime[2] = 0;\n\t\tdateTime[3] = 0;\n\t\tdateTime[4] = 0;\n\t\tdateTime[5] = 0;\n\t\tdateTime[6] = 0;\n\t$.post(\"onlineInformation/queryNearlyAWeekWorkDetailInfo.action\",{eeid:id},\n\t\t\tfunction(data) {\n\t\tif(data!=\"null\"){\n\t\t\t$.each(data, function() {\n\t\t\t\tvar i = 0;\n\t\t\t\tvar start = this.startime;\n\t\t\t\tvar end = this.endtime;\n\t\t\t\tif(compareDate(this.startime, dateStr[0])){\n\t\t\t\t\t// compareDate是 str1<=str2 返回true\n\t\t\t\t\t//DateDiff (大,小)\n\t\t\t\t\t\n\t\t\t\t\tif(compareDate(dateStr[0],start)){\n\t\t\t\t\t\t\n\t\t\t\t\t}else{\n\t\t\t\t\t\tstart = dateStr[0];\n\t\t\t\t\t}\n\t\t\t\t\t//当endtime=startime是才返回true\n\t\t\t\t\tif(compareDate(end,start)){\n\t\t\t\t\t\tdateTime[0] = dateTime[0] + DateDiff(end,start);\n\t\t\t\t\t}else if(compareDate(end,dateStr[1])){\n\t\t\t\t\t\tdateTime[0] = dateTime[0] + DateDiff(dateStr[1],start);\n\t\t\t\t\t\tdateTime[1] = dateTime[1] + DateDiff(end,dateStr[1]);\n//\t\t\t\t\t\tconsole.log(\"two\"+DateDiff(dateStr[1],start));\n//\t\t\t\t\t\tconsole.log(\"two\"+DateDiff(end,dateStr[1]));\n\t\t\t\t\t}else if(compareDate(end,dateStr[2])){\n\t\t\t\t\t\tdateTime[0] = dateTime[0] + DateDiff(dateStr[1],start);\n\t\t\t\t\t\tdateTime[1] = dateTime[1] + 86400;\n\t\t\t\t\t\tdateTime[2] = dateTime[2] +DateDiff(end,dateStr[2]);\n//\t\t\t\t\t\tconsole.log(\"three\"+DateDiff(dateStr[1],start));\n//\t\t\t\t\t\tconsole.log(\"three 24小时\");\n//\t\t\t\t\t\tconsole.log(\"three\"+DateDiff(end,dateStr[2]));\n\t\t\t\t\t}else if(compareDate(end,dateStr[3])){\n\t\t\t\t\t\t\n\t\t\t\t\t\tdateTime[0] = dateTime[0] + DateDiff(dateStr[1],start);\n\t\t\t\t\t\tdateTime[1] = dateTime[1] + 86400;\n\t\t\t\t\t\tdateTime[2] = dateTime[2] + 86400;\n\t\t\t\t\t\tdateTime[3] = dateTime[3] + DateDiff(end,dateStr[3]);\n//\t\t\t\t\t\tconsole.log(\"four\"+DateDiff(dateStr[1],start));\n//\t\t\t\t\t\tconsole.log(\"four 24小时\");\n//\t\t\t\t\t\tconsole.log(\"four 24小时\");\n//\t\t\t\t\t\tconsole.log(\"four\"+DateDiff(end,dateStr[3]));\n\t\t\t\t\t}else if(compareDate(end,dateStr[4])){\n\t\t\t\t\t\tdateTime[0] = dateTime[0] + DateDiff(dateStr[1],start);\n\t\t\t\t\t\tdateTime[1] = dateTime[1] + 86400;\n\t\t\t\t\t\tdateTime[2] = dateTime[2] + 86400;\n\t\t\t\t\t\tdateTime[3] = dateTime[3] + 86400;\n\t\t\t\t\t\tdateTime[4] = dateTime[4] + DateDiff(end,dateStr[4]);\n//\t\t\t\t\t\tconsole.log(\"five\"+DateDiff(dateStr[1],start));\n//\t\t\t\t\t\tconsole.log(\"five 24小时\");\n//\t\t\t\t\t\tconsole.log(\"five 24小时\");\n//\t\t\t\t\t\tconsole.log(\"five 24小时\");\n//\t\t\t\t\t\tconsole.log(\"five\"+DateDiff(end,dateStr[4]));\n\t\t\t\t\t}else if(compareDate(end,dateStr[5])){\n\t\t\t\t\t\t\n\t\t\t\t\t\tdateTime[0] = dateTime[0] + DateDiff(dateStr[1],start);\n\t\t\t\t\t\tdateTime[1] = dateTime[1] + 86400;\n\t\t\t\t\t\tdateTime[2] = dateTime[2] + 86400;\n\t\t\t\t\t\tdateTime[3] = dateTime[3] + 86400;\n\t\t\t\t\t\tdateTime[4] = dateTime[4] + 86400;\n\t\t\t\t\t\tdateTime[5] = dateTime[5] + DateDiff(end,dateStr[5]);\n//\t\t\t\t\t\tconsole.log(\"six\"+DateDiff(dateStr[1],start));\n//\t\t\t\t\t\tconsole.log(\"six 24小时\");\n//\t\t\t\t\t\tconsole.log(\"six 24小时\");\n//\t\t\t\t\t\tconsole.log(\"six 24小时\");\n//\t\t\t\t\t\tconsole.log(\"six 24小时\");\n//\t\t\t\t\t\tconsole.log(\"six\"+DateDiff(end,dateStr[5]));\n\t\t\t\t\t}else if(compareDate(end,dateStr[6])){\n\t\t\t\t\t\t\n\t\t\t\t\t\tdateTime[0] = dateTime[0] + DateDiff(dateStr[1],start);\n\t\t\t\t\t\tdateTime[1] = dateTime[1] + 86400;\n\t\t\t\t\t\tdateTime[2] = dateTime[2] + 86400;\n\t\t\t\t\t\tdateTime[3] = dateTime[3] + 86400;\n\t\t\t\t\t\tdateTime[4] = dateTime[4] + 86400;\n\t\t\t\t\t\tdateTime[5] = dateTime[5] + 86400;\n\t\t\t\t\t\tdateTime[6] = dateTime[6] + DateDiff(end,dateStr[6]);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n//\t\t\t\t\t\tconsole.log(\"seven\"+DateDiff(dateStr[1],start));\n//\t\t\t\t\t\tconsole.log(\"seven 24小时\");\n//\t\t\t\t\t\tconsole.log(\"seven 24小时\");\n//\t\t\t\t\t\tconsole.log(\"seven 24小时\");\n//\t\t\t\t\t\tconsole.log(\"seven 24小时\");\n//\t\t\t\t\t\tconsole.log(\"seven 24小时\");\n//\t\t\t\t\t\tconsole.log(\"seven\"+DateDiff(end,dateStr[6]));\n\t\t\t\t\t}\n\t\t\t\t}else if(compareDate(this.startime, dateStr[1])){\n\t\t\t\t\tif(compareDate(end,start)){\n\t\t\t\t\t\tdateTime[1] = dateTime[1] + DateDiff(end,start);\n\t\t\t\t\t}else if(compareDate(end,dateStr[2])){\n\t\t\t\t\t\tdateTime[1] = dateTime[1] + DateDiff(dateStr[2],start);\n\t\t\t\t\t\tdateTime[2] = dateTime[2] + DateDiff(end,dateStr[2]);\n\t\t\t\t\t}else if(compareDate(end,dateStr[3])){\n\t\t\t\t\t\tdateTime[1] = dateTime[1] + DateDiff(dateStr[2],start);\n\t\t\t\t\t\tdateTime[2] = dateTime[2] + 86400;\n\t\t\t\t\t\tdateTime[3] = dateTime[3] + DateDiff(end,dateStr[3]);\n\t\t\t\t\t}else if(compareDate(end,dateStr[4])){\n\t\t\t\t\t\tdateTime[1] = dateTime[1] +DateDiff(dateStr[2],start);\n\t\t\t\t\t\tdateTime[2] = dateTime[2] + 86400;\n\t\t\t\t\t\tdateTime[3] = dateTime[3] +86400;\n\t\t\t\t\t\tdateTime[4] = dateTime[4] + DateDiff(end,dateStr[4]);\n\t\t\t\t\t}else if(compareDate(end,dateStr[5])){\n\t\t\t\t\t\tdateTime[1] = dateTime[1] +DateDiff(dateStr[2],start);\n\t\t\t\t\t\tdateTime[2] = dateTime[2] + 86400;\n\t\t\t\t\t\tdateTime[3] = dateTime[3] +86400;\n\t\t\t\t\t\tdateTime[4] = dateTime[4] + 86400;\n\t\t\t\t\t\tdateTime[5] = dateTime[5] + DateDiff(end,dateStr[5]);\n\t\t\t\t\t}else if(compareDate(end,dateStr[6])){\n\t\t\t\t\t\t\n\t\t\t\t\t\tdateTime[1] = dateTime[1] + DateDiff(dateStr[2],start);\n\t\t\t\t\t\tdateTime[2] = dateTime[2] + 86400;\n\t\t\t\t\t\tdateTime[3] = dateTime[3] + 86400;\n\t\t\t\t\t\tdateTime[4] = dateTime[4] + 86400;\n\t\t\t\t\t\tdateTime[5] = dateTime[5] + 86400;\n\t\t\t\t\t\tdateTime[6] = dateTime[6] + DateDiff(end,dateStr[6]);\n\t\t\t\t\t}\n\t\t\t\t}else if(compareDate(this.startime, dateStr[2])){\n\t\t\t\t\tif(compareDate(end,start)){\n\t\t\t\t\t\tdateTime[2] = dateTime[2] + DateDiff(end,start);\n\t\t\t\t\t}else if(compareDate(end,dateStr[3])){\n\t\t\t\t\t\tdateTime[2] = dateTime[2] + DateDiff(dateStr[3],start);\n\t\t\t\t\t\tdateTime[3] = dateTime[3] + DateDiff(end,dateStr[3]);\n\t\t\t\t\t}else if(compareDate(end,dateStr[4])){\n\t\t\t\t\t\tdateTime[2] = dateTime[2] + DateDiff(dateStr[3],start);\n\t\t\t\t\t\tdateTime[3] = dateTime[3] + 86400;\n\t\t\t\t\t\tdateTime[4] = dateTime[4] + DateDiff(end,dateStr[4]);\n\t\t\t\t\t}else if(compareDate(end,dateStr[5])){\n\t\t\t\t\t\tdateTime[2] = dateTime[2] + DateDiff(dateStr[3],start);\n\t\t\t\t\t\tdateTime[3] = dateTime[3] + 86400;\n\t\t\t\t\t\tdateTime[4] = dateTime[4] + 86400;\n\t\t\t\t\t\tdateTime[5] = dateTime[5] + DateDiff(end,dateStr[5]);\n\t\t\t\t\t}else if(compareDate(end,dateStr[6])){\n\t\t\t\t\t\tdateTime[2] = dateTime[2] + DateDiff(dateStr[3],start);\n\t\t\t\t\t\tdateTime[3] = dateTime[3] + 86400;\n\t\t\t\t\t\tdateTime[4] = dateTime[4] + 86400;\n\t\t\t\t\t\tdateTime[5] = dateTime[5] + 86400;\n\t\t\t\t\t\tdateTime[6] = dateTime[6] + DateDiff(end,dateStr[6]);;\n\t\t\t\t\t}\n\t\t\t\t}else if(compareDate(this.startime, dateStr[3])){\n\t\t\t\t\tif(compareDate(end,start)){\n\t\t\t\t\t\tdateTime[3] = dateTime[3] + DateDiff(end,start);\n\t\t\t\t\t}else if(compareDate(end,dateStr[4])){\n\t\t\t\t\t\tdateTime[3] = dateTime[3] + DateDiff(dateStr[4],start);\n\t\t\t\t\t\tdateTime[4] = dateTime[4] + DateDiff(end,dateStr[4]);\n\t\t\t\t\t}else if(compareDate(end,dateStr[5])){\n\t\t\t\t\t\tdateTime[3] = dateTime[3] + DateDiff(dateStr[4],start);\n\t\t\t\t\t\tdateTime[4] = dateTime[4] + 86400;\n\t\t\t\t\t\tdateTime[5] = dateTime[5] + DateDiff(end,dateStr[5]);\n\t\t\t\t\t}else if(compareDate(end,dateStr[6])){\n\t\t\t\t\t\tdateTime[3] = dateTime[3] + DateDiff(dateStr[4],start);\n\t\t\t\t\t\tdateTime[4] = dateTime[4] + 86400;\n\t\t\t\t\t\tdateTime[5] = dateTime[5] + 86400;\n\t\t\t\t\t\tdateTime[6] = dateTime[6] + DateDiff(end,dateStr[6]);\n\t\t\t\t\t}\n\t\t\t\t}else if(compareDate(this.startime, dateStr[4])){\n\t\t\t\t\tif(compareDate(end,start)){\n\t\t\t\t\t\tdateTime[4] = dateTime[4] + DateDiff(end,start);\n\t\t\t\t\t}else if(compareDate(end,dateStr[5])){\n\t\t\t\t\t\tdateTime[4] = dateTime[4] + DateDiff(dateStr[5],start);\n\t\t\t\t\t\tdateTime[5] = dateTime[5] + DateDiff(end,dateStr[5]);\n\t\t\t\t\t}else if(compareDate(end,dateStr[6])){\n\t\t\t\t\t\tdateTime[4] = dateTime[4] + DateDiff(dateStr[5],start);\n\t\t\t\t\t\tdateTime[5] = dateTime[5] + 86400;\n\t\t\t\t\t\tdateTime[6] = dateTime[6] + DateDiff(end,dateStr[6]);\n\t\t\t\t\t}\n\t\t\t\t}else if(compareDate(this.startime, dateStr[5])){\n\t\t\t\t\tif(compareDate(end,start)){\n\t\t\t\t\t\tdateTime[5] = dateTime[5] + DateDiff(end,start);\n\t\t\t\t\t}else if(compareDate(end,dateStr[6])){\n\t\t\t\t\t\tdateTime[5] = dateTime[5] + DateDiff(dateStr[6],start);\n\t\t\t\t\t\tdateTime[6] = dateTime[6] + DateDiff(end,dateStr[6]);\n\t\t\t\t\t}\n\t\t\t\t}else if(compareDate(this.startime, dateStr[6])){\n\t\t\t\t\tif(compareDate(end,start)){\n\t\t\t\t\t\tdateTime[6] = dateTime[6] + DateDiff(end,start);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t});\n\t\t}\n\t\t\n\t\t// ========= 折线图\n\t\tvar myChartThree = echarts.init(document.getElementById('fourth'));\n\n // 指定图表的配置项和数据\n var colors = ['#5793f3', '#d14a61', '#675bba'];\noptionThree = {\n color: colors,\n\n tooltip: {\n trigger: 'none',\n axisPointer: {\n type: 'cross'\n }\n },\n legend: {\n data: ['2016 降水量']\n },\n grid: {\n top: 70,\n bottom: 50\n },\n xAxis: [\n {\n type: 'category',\n axisTick: {\n alignWithLabel: true\n },\n axisLine: {\n onZero: false,\n lineStyle: {\n color: colors[1]\n }\n },\n axisPointer: {\n label: {\n formatter: function (params) {\n return '降水量 ' + params.value\n + (params.seriesData.length ? ':' + params.seriesData[0].data : '');\n }\n }\n },\n data: [dateStr[0],dateStr[1],dateStr[2],dateStr[3],dateStr[4],dateStr[5],dateStr[6]]\n }\n ],\n yAxis: [\n {\n type: 'value'\n }\n ],\n series: [\n {\n name:'2016 降水量',\n type:'line',\n smooth: true,\n data: [dateTime[0]/3600,dateTime[1]/3600 , dateTime[2]/3600, dateTime[3]/3600, dateTime[4]/3600, dateTime[5]/3600, dateTime[6]/3600]\n }\n ]\n};\n\n // 使用刚指定的配置项和数据显示图表。\nmyChartThree.setOption(optionThree);\n\t\t\n\t\t\n\t\t\n\t\t\n\t}, \"json\");\n \n}", "function isFetchNeeded(start, end) {\n\t\t\treturn !rangeStart || // nothing has been fetched yet?\n\t\t\t\tstart < rangeStart || end > rangeEnd; // is part of the new range outside of the old range?\n\t\t}", "getEventsListed(dateObject) {\n const daily_options = {\n method: 'get',\n mode: 'cors',\n cache: 'no-cache',\n credentials: 'same-origin',\n headers: {\n 'Content-Type': 'application/json',\n },\n referrer: 'no-referrer',\n }\n\n // temporary GET request, move as desired, gets object containing all of user's specific events\n // similar request can be made at URL http://localhost:3000/DBInfo/Weekly\n\n const weekly_options = {\n method: 'get',\n mode: 'cors',\n cache: 'no-cache',\n credentials: 'same-origin',\n headers: {\n 'Content-Type': 'application/json',\n },\n referrer: 'no-referrer',\n }\n fetch('http://localhost:3000/DBInfo/Specific/' + this.state.currentDate.replace(/\\//g, '-'), daily_options)\n .then((response) => response.json())\n .then((data) => {\n fetch('http://localhost:3000/DBInfo/Weekly', weekly_options)\n .then((response2) => response2.json())\n .then(async (data2) => {\n //Placing text into main text area\n var dataArray = data2.dataWeekly;\n var importantDates = [];\n\n var tempUserInfo = this.props.currentDate;\n var monthUser = tempUserInfo.substr(0, 2);\n var dayUser = tempUserInfo.substr(3, 2);\n var yearUser = tempUserInfo.substr(6, 4);\n\n var monthNumUser = parseInt(monthUser);\n var dayNumUser = parseInt(dayUser);\n var yearNumUser = parseInt(yearUser);\n\n var userDate = new Date(yearNumUser, monthNumUser - 1, dayNumUser, 0, 0, 0, 0);\n var userdayOfWeek = userDate.getDay();\n for (var obj of dataArray) {\n if (obj.date !== undefined) {\n var tempObj = obj.date;\n var month = tempObj.substr(0, 2);\n var day = tempObj.substr(3, 2);\n var year = tempObj.substr(6, 4);\n\n var monthNum = parseInt(month);\n var dayNum = parseInt(day);\n var yearNum = parseInt(year);\n\n var tempDate = new Date(yearNum, monthNum - 1, dayNum);\n\n var dayOfWeek = tempDate.getDay();\n\n if (userdayOfWeek === dayOfWeek && userDate >= tempDate) {\n importantDates.push(obj);\n }\n }\n }\n\n var keysAndValues = [];\n if (Object.keys(data).length !== 0) {\n var dailyEventArray = [];\n var desiredValue = data;\n var ListOfKeys = Object.keys(desiredValue);\n keysAndValues = ListOfKeys.map((value) => {\n const strTitle = desiredValue[value].title;\n var tempObj = {};\n tempObj = desiredValue[value];\n dailyEventArray.push(tempObj);\n const strDate = \"Date: \" + desiredValue[value].date;\n const fromTime = \"From: \" + desiredValue[value].from;\n const timeTo = \"To: \" + desiredValue[value].to;\n const details = \"Description: \" + desiredValue[value].details;\n return (\n <ul id=\"event_list\" key={value}>\n <div id=\"bold_title\">{strTitle}</div>\n <li>{strDate}</li>\n <li>{fromTime}</li>\n <li>{timeTo}</li>\n <li>{details}</li>\n <br />\n </ul>\n )\n });\n }\n\n\n var tempWeekly = [];\n for (var obj1 of importantDates) {\n const strTitle = obj1.title + \" - Weekly\";\n var tempObjWeekly = {};\n tempObjWeekly = obj1;\n tempWeekly.push(tempObjWeekly);\n const strDate = \"Date: \" + obj1.date;\n const fromTime = \"From: \" + obj1.from;\n const timeTo = \"To: \" + obj1.to;\n const details = \"Description: \" + obj1.details;\n keysAndValues.push(\n <ul id=\"event_list\" key={obj1.title}>\n <div id=\"bold_title\">{strTitle}</div>\n <li>{strDate}</li>\n <li>{fromTime}</li>\n <li>{timeTo}</li>\n <li>{details}</li>\n <br />\n </ul>\n )\n }\n\n\n //Set delete params\n var optionsRender = [];\n var deleteObjects = [];\n var index = 0;\n if (tempWeekly !== undefined) {\n for (var objDelete of tempWeekly) {\n var tempStr = objDelete.date + \" - \" + objDelete.title;\n objDelete.weekly = true;\n deleteObjects.push(objDelete);\n optionsRender.push(<option key={objDelete.title} value={index}>{tempStr}</option>);\n index++\n }\n }\n if (dailyEventArray !== undefined) {\n for (var objDeleteDaily of dailyEventArray) {\n var tempStr2 = objDeleteDaily.date + \" - \" + objDeleteDaily.title;\n objDeleteDaily.weekly = false;\n deleteObjects.push(objDeleteDaily);\n optionsRender.push(<option key={objDeleteDaily.title} value={index}>{tempStr2}</option>);\n index++;\n }\n }\n await this.setState({\n dailyEvents: dailyEventArray,\n weeklyEvents: tempWeekly,\n events: keysAndValues,\n renderDeletes: optionsRender,\n deleteObjects: deleteObjects,\n });\n\n\n });\n })\n //return listElements;\n }", "function cb(start, end) {\n $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));\n }", "set range(range) {\n this.startDate = range.startDate;\n this.endDate = range.endDate;\n this.refresh();\n }", "function filterDataByDate(list) {\n // console.log(list[5]);\n var startdate = $('#startdate').val();\n var enddate = $('#enddate').val();\n // startdate = startdate.replace('/','-');\n // enddate = enddate.replace('/','-');\n // var length = list.length;\n for(var i = 0; i < list.length; i++) {\n var value = list[i];\n var key = i;\n if (value) {\n var dateV = value[indexOfDateColumn];\n var date = moment(dateV,['MM-DD-YY','MM-DD-YY HH:MM:SS HH:mm:ss A']).format('YYYY-MM-DD');\n // console.log('Key: ' + key);\n // console.log('Element: ' + value);\n // console.log(moment(date,'YYYY-MM-DD').isBetween(moment(getDate[0], \"YYYY-MM-DD\"), moment(getDate[1], \"YYYY-MM-DD\")));\n if (! moment(date,'YYYY-MM-DD').isBetween(moment(startdate, \"YYYY-MM-DD\"), moment(enddate, \"YYYY-MM-DD\")) ) {\n var piece = list.splice(key,1);\n // console.log('Element removed: ' + piece);\n i--;\n }\n } else {\n // console.log(value);\n var piece = list.splice(key,1);\n }\n // console.log('i : ' + i);\n }\n\n // console.log('------------');\n // $.each(list, function(key, value) {\n // console.log(value);\n // });\n // console.log(list.length);\n return list;\n }", "fetchClosestEvent(context) {\n return new Promise((resolve, reject) => {\n HTTP.get('events/', {\n headers: {\n 'Authorization': 'Token ' + context.state.token\n }\n })\n .then((response) => {\n // date sorting ( to put in a different function )\n let currentDate = Date.now()\n let eventDate = {index: undefined, difference: undefined}\n\n response.data.forEach((event, index) => {\n let date = new Date(event.exam_date)\n let difference = Math.abs(currentDate - date)\n \n if(eventDate.difference == undefined || difference < eventDate.difference) {\n eventDate.difference = difference\n eventDate.index = index\n if(eventDate.difference == 0) return true\n } \n });\n context.commit('saveCurrentEvent', response.data[eventDate.index])\n resolve(response.data[eventDate.index])\n })\n .catch((error) => {\n console.log(error)\n context.commit('saveErrors', error.message)\n reject(error)\n })\n })\n }", "function getActivityDateRange(params) {\n var beginDate = params.beginDate,\n endDate = params.endDate,\n beginEnd = params.beginEnd,\n date = params.date;\n\n var findParams = {};\n var begin = beginDate ? _moment2.default.utc(beginDate, 'MM-DD-YYYY').startOf('day') : (0, _moment2.default)().subtract(100, 'years');\n var end = endDate ? _moment2.default.utc(endDate, 'MM-DD-YYYY').endOf('day') : (0, _moment2.default)().add(100, 'years');\n if (beginDate && endDate) {\n findParams.created = { $gt: begin.toDate(), $lt: end.toDate() };\n // Begin date only\n } else if (beginEnd === 'begin' && date) {\n findParams.created = { $gt: begin.toDate() };\n }\n if (typeof params.companyId !== 'undefined') {\n findParams.company = params.companyId;\n }\n if (_typeof(params.rejected) && params.rejected === 'true') {\n params.rejected = true;\n }\n // Only sold\n findParams.soldToLiquidation = true;\n\n return findParams;\n}", "setDates(){\n\t\tthis.dates=[];\n\t\tlet min=new Date(this.min);\n\t\twhile(min<=this.max){\n\t\t\tthis.dates.push(new Date(min));\n\t\t\tmin.setDate(min.getDate()+1);\n\t\t}\n\t\tthis.dates.push(new Date(min));\n\t}", "function buildSummaryListData( data, first_day, last_day ){\r\n\r\n var skv_dates = {};\r\n var arr_dates = [];\r\n var count_individual_dates = 0;\r\n\r\n data.forEach( function( skv_event ){\r\n\r\n // don't want to display Highgrove events\r\n // if( skv_event.location \r\n // && skv_event.location.name === 'Highgrove Church' ){\r\n // return false;\r\n // }\r\n\r\n var start_date = moment( skv_event.datetime_start );\r\n var end_date = moment( skv_event.datetime_end );\r\n var start_date_string = moment( start_date ).format( api_date_format );\r\n var event_duration_days = end_date.diff( start_date, 'days' );\r\n // force string concatenation with '' to start\r\n skv_event.event_uid = '' + skv_event.id + start_date_string\r\n\r\n // handle multi day events\r\n if( event_duration_days > 1 ){\r\n\r\n var this_date = moment( start_date );\r\n start_date_string = '';\r\n\r\n for( i = 0; i <= event_duration_days; i++ ){\r\n\r\n start_date_string = moment( this_date ).format( api_date_format );\r\n this_date = moment( this_date ).add( 1, 'days' );\r\n\r\n\r\n if( i === 1 ){\r\n skv_event.datetime_end = moment( this_date ).endOf( 'day' )\r\n .format( \"YYYY-MM-DD HH:mm:ss\" );\r\n }\r\n\r\n if( i > 1 && i < event_duration_days ){\r\n skv_event.datetime_start = moment( this_date ).startOf( 'day' )\r\n .format( \"YYYY-MM-DD HH:mm:ss\" );\r\n skv_event.datetime_end = moment( this_date ).endOf( 'day' )\r\n .format( \"YYYY-MM-DD HH:mm:ss\" );\r\n }\r\n\r\n if( i === event_duration_days ){\r\n skv_event.datetime_start = moment( this_date ).startOf( 'day' )\r\n .format( \"YYYY-MM-DD HH:mm:ss\" );\r\n }\r\n\r\n // force string concatenation with '' to start\r\n skv_event.event_uid = '' + skv_event.id + start_date_string\r\n skv_dates = processSingleEventDay( \r\n start_date_string,\r\n skv_event,\r\n skv_dates\r\n );\r\n }\r\n } else {\r\n skv_dates = processSingleEventDay(\r\n start_date_string,\r\n skv_event,\r\n skv_dates\r\n );\r\n }\r\n\r\n });\r\n\r\n for( var key in skv_dates ){\r\n arr_dates.push( skv_dates[ key ] );\r\n }\r\n\r\n arr_dates.sort(function(a,b){\r\n return (a.order > b.order) \r\n ? 1 \r\n : ((b.order > a.order) ? -1 : 0);\r\n });\r\n\r\n buildSummaryListMarkup( arr_dates, first_day, last_day );\r\n\r\n }", "function splitBusy(day,start,end){\n\n\t\t\t\t\tvar l = busyList.length;\n\n\t\t\t\t\tfor(var i = 0 ; i<l ; i++){\n\n\t\t\t\t\t\tif(busyList[i].start.day() == start.day()){\n\n\t\t\t\t\t\t\tvar toSplit = busyList[i];\n\n\t\t\t\t\t\t\tif(toSplit.start >= start && toSplit.end > end){\n\n\t\t\t\t\t\t\t\t//move begining to the end of end\n\n\t\t\t\t\t\t\t\ttoSplit.start.hour(end.hour());\n\n\t\t\t\t\t\t\t}else if(toSplit.end <= end && toSplit.start < start){\n\n\t\t\t\t\t\t\t\t//move the end to the begining of start\n\n\t\t\t\t\t\t\t\ttoSplit.end.hour(start.hour());\n\n\t\t\t\t\t\t\t}else if(toSplit.start < start && toSplit.end > end){\n\n\t\t\t\t\t\t\t\t//split in two\n\n\t\t\t\t\t\t\t\tbusyList.push({id:busyList.length,\n\n\t\t\t\t\t\t\t\t\ttitle:\"No disponible\",\n\n\t\t\t\t\t\t\t\t\tcolor:\"#000\",\n\n\t\t\t\t\t\t\t\t\tstart: new moment(end),\n\n\t\t\t\t\t\t\t\t\tend: new moment(toSplit.end),\n\n\t\t\t\t\t\t\t\t\teditable:false\n\n\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\ttoSplit.end.hour(start.hour());\n\n\t\t\t\t\t\t\t}else{\n\n\t\t\t\t\t\t\t\tbusyList.splice(i,1);\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}", "async showDatesForEvent(eventId, date_from, date_to ) {\n\t\tconst url = `events/${eventId}/dates`\n\t\tvar params = {date_from: date_from, date_to: date_to}\n\n\t\ttry {\n\t\t\tconst res = await this.axiosClient.get(url, {params})\n\t\t\treturn _.map(res, r => _.pick(r, ['day', 'sold_out']))\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error(err)\n\t\t}\n\t}", "function getData(){\n $http.get(rootUrl+\"?filter[period]=\"+$filter('date')($rootScope.selectedPeriod, \"yyyy-MM\")).then(function(response){\n self.list = response.data.data;\n });\n }", "setStartEnd(moments) {\n let start = new Date(this.props.start)\n let end = new Date(this.props.end)\n\n start.setHours(moments[0].hours())\n start.setMinutes(moments[0].minutes())\n\n if (!this.state.openEnded) {\n if (end.getHours() !== moments[1].hours())\n end.setMinutes(moments[1].minutes())\n end.setHours(moments[1].hours())\n }\n\n // Dates have to be adjusted if workday ends after midnight\n if (start < this.props.start) this.adjustForNextDay(start, 1)\n if (end > this.props.end) this.adjustForNextDay(end, -1)\n if (start >= end) return\n let available = this.isAvailable(start, end)\n if (!available) return\n this.setState({start: start, end: end})\n return true\n }", "function check_sched_conflict(dt,hr,mn,duration){\n //--- assume all is valid\n modelInspection.set(\"isvalid\",true);\n var idx_date = {Jan:\"0\",Feb:\"1\",Mar:\"2\",Apr:\"3\",May:\"4\",Jun:\"5\",Jul:\"6\",Aug:\"7\",Sep:\"8\",Oct:\"9\",Nov:\"10\",Dec:\"11\"};\n var arr = dt.split(\"-\");\n var new_sdate = new Date(arr[2],idx_date[arr[1]],arr[0],hr,mn,0,0);\n var new_edate = new Date(new_sdate.getTime() +duration*60000 );\n \n var cur_Date = new Date();\n if( new_sdate < cur_Date){\n modelInspection.set(\"isvalid\",false);\n return false;\n }\n\n $.each(modelInspection.data_source_inspection.data(), function (field, value) { \n var tmparr = value.date_start.split(\" \");\n var tmpampm = value.start_time.split(\" \");\n var tmptime = tmpampm[0].split(\":\");\n var plushour = tmpampm[1] == \"PM\" && parseInt(tmptime[0]) < 12 ?12:0;\n plushour = tmpampm[1] == \"AM\" && parseInt(tmptime[0]) == 12 ?-12:plushour;\n\n var cur_sdate = new Date(tmparr[2],idx_date[tmparr[1]],tmparr[0],parseInt(tmptime[0])+plushour,tmptime[1],0,0);\n var cur_edate = new Date(cur_sdate.getTime() +value.duration*60000);\n \n\n\n if(new_sdate >= cur_sdate && new_sdate < cur_edate ){\n modelInspection.set(\"isvalid\",false);\n }\n \n if(new_sdate == cur_sdate){\n modelInspection.set(\"isvalid\",false);\n } \n\n if(new_edate > cur_sdate && new_edate <= cur_edate ){\n modelInspection.set(\"isvalid\",false);\n }\n if(new_sdate <= cur_sdate && new_edate >= cur_edate ){\n modelInspection.set(\"isvalid\",false);\n }\n\n });\n\n var startdate = kendo.parseDate(new_sdate);\n var enddate = kendo.parseDate(new_edate);\n return {date_start:kendo.toString(startdate, \"dd MMM yyyy\"),start_time:kendo.toString(startdate, \"hh:mm tt\"),end_time:kendo.toString(enddate, \"hh:mm tt\"),duration:duration};\n \n}", "checkAvabilityScheduleExceptId(id, date, start, end) {\n const schedule = mysql_1.default.raw(`SELECT * FROM schedule WHERE date = \"${date}\" AND \n ((\"${start}\" BETWEEN start_time AND end_time) OR\n (\"${end}\" BETWEEN start_time AND end_time)) AND id <> ${id};`);\n return schedule;\n }", "function getData (startDate, endDate) {\n\n let preds = fetch(predUrl + startDate + '/' + endDate).then( response => {\n return response.json();\n });\n\n let actuals = fetch(trueUrl + startDate + '/' + endDate).then( response => {\n return response.json();\n });\n\n return {'preds':preds, 'actuals':actuals}\n}", "static getCompletedTasks(category='%') {\n // tasks whose end date is farther than current date\n var table_Name = Task.tableName\n category = '\\''+category+'\\''\n const sql = `SELECT * FROM ${table_Name} WHERE category like ${category} AND isCompleted = 1`\n console.log(sql)\n const params = []\n return this.repository.databaseLayer.executeSql(sql, params)\n }", "function getDateArray(start, end) {\n\t\tvar arr = new Array();\n\n\t\twhile (start <= end) {\n\t\t\tarr.push(new Date(start));\n\t\t\tstart.setDate(start.getDate() + 1);\n\t\t}\n\t\t\n\t\treturn arr;\n\t}", "function isFetchNeeded(start, end) {\n\t\treturn !rangeStart || // nothing has been fetched yet?\n\t\t\tstart < rangeStart || end > rangeEnd; // is part of the new range outside of the old range?\n\t}", "function isFetchNeeded(start, end) {\n\t\treturn !rangeStart || // nothing has been fetched yet?\n\t\t\tstart < rangeStart || end > rangeEnd; // is part of the new range outside of the old range?\n\t}", "function isFetchNeeded(start, end) {\n\t\treturn !rangeStart || // nothing has been fetched yet?\n\t\t\tstart < rangeStart || end > rangeEnd; // is part of the new range outside of the old range?\n\t}" ]
[ "0.64892733", "0.64662874", "0.6211523", "0.6206695", "0.6142456", "0.6107244", "0.60717344", "0.60375684", "0.59969956", "0.5981756", "0.5945079", "0.5932486", "0.5901057", "0.59004486", "0.58930755", "0.58885026", "0.5852746", "0.5838475", "0.5776359", "0.5761849", "0.57523644", "0.5729283", "0.5706007", "0.57051605", "0.56993085", "0.569395", "0.5652647", "0.5638923", "0.5622969", "0.5608753", "0.56085306", "0.56053746", "0.5599764", "0.55874026", "0.55766815", "0.5562785", "0.5555136", "0.554991", "0.55476093", "0.5537169", "0.54723173", "0.54678917", "0.54671985", "0.5461719", "0.5458603", "0.54554796", "0.54475117", "0.544565", "0.5441554", "0.54350656", "0.5430534", "0.5430534", "0.5407903", "0.5401568", "0.53955764", "0.53859496", "0.5382059", "0.5367592", "0.5366207", "0.5366207", "0.5352594", "0.53518915", "0.5348297", "0.5343766", "0.53354806", "0.5330789", "0.533034", "0.5329313", "0.5328493", "0.53261715", "0.53139466", "0.5308322", "0.52983403", "0.52898103", "0.5287948", "0.52864414", "0.52862716", "0.5285912", "0.5282971", "0.52757996", "0.52727026", "0.52696013", "0.5262465", "0.5256354", "0.52563244", "0.5244435", "0.5240741", "0.5240538", "0.52198344", "0.521329", "0.5205438", "0.520463", "0.5188527", "0.51852816", "0.5183788", "0.51815695", "0.51796573", "0.517929", "0.51781434", "0.51781434", "0.51781434" ]
0.0
-1
The string returned by the "getNodeValue()" method for an Element Node is null.
function hc_nodeelementnodevalue() { var success; var doc; var elementNode; var elementValue; doc = load("hc_staff"); elementNode = doc.documentElement; elementValue = elementNode.nodeValue; assertNull("elementNodeValue",elementValue); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function eltText(node) {\n return node.textContent || node.innerText || node.nodeValue || \"\";\n }", "function eltText(node) {\n return node.textContent || node.innerText || node.nodeValue || \"\";\n }", "function eltText(node) {\n return node.textContent || node.innerText || node.nodeValue || \"\";\n }", "function eltText(node) {\n return node.textContent || node.innerText || node.nodeValue || \"\";\n }", "function eltText(node) {\n return node.textContent || node.innerText || node.nodeValue || \"\";\n }", "function eltText(node) {\n return node.textContent || node.innerText || node.nodeValue || \"\";\n }", "getNodeValue() {}", "function nodeVal(node) {\n\t node?.normalize();\n\t return (node && node.textContent) || \"\";\n\t}", "function nodeVal(x) {\n if (x) { norm(x); }\n return (x && x.firstChild && x.firstChild.nodeValue) || '';\n }", "function checkEmptyEntry(node){\n\tvar result;\n\t\n\tif(node.firstChild){\n\t\tresult = node.firstChild.nodeValue;\n\t}else{\n\t\tresult = '';\n\t}\n\t\n\treturn result;\n}", "function nodeText(node){\n\t\tvar str = node.textContent || node.innerHTML || node.innerText || '';\n\t\t\n\t\treturn str.trim();\n\t}", "function xmlText(oNode)\r\n{\r\n\tif(oNode==null)return \"\";\r\n\r\n\tif(oNode.text)return oNode.text;\r\n if(typeof(oNode.textContent) != \"undefined\") return oNode.textContent; \r\n\tif(oNode.nodeValue && oNode.nodeValue!=\"\") return oNode.nodeValue;\r\n\tif(oNode.firstChild) \r\n\t{\r\n\t\treturn oNode.firstChild.nodeValue;\r\n\t}\r\n\t\r\n\treturn \"\";\r\n}", "function _getAdjacentBlankNodeName(node, id) {\n return (node.type === 'blank node' && node.value !== id ? node.value : null);\n }", "function nodeVal(x) { if (x) {norm(x);} return x && x.firstChild && x.firstChild.nodeValue; }", "function _nullCoerce() {\n return '';\n}", "function hc_nodedocumentfragmentnodevalue() {\n var success;\n var doc;\n var docFragment;\n var attrList;\n var value;\n doc = load(\"hc_staff\");\n docFragment = doc.createDocumentFragment();\n attrList = docFragment.attributes;\n\n assertNull(\"attributesNull\",attrList);\n value = docFragment.nodeValue;\n\n assertNull(\"initiallyNull\",value);\n \n}", "nodeValue(e){\n var value = e.nodeName == '#text' ? e.data : e.innerHTML,\n value = value||'';\n\n return this.domPreparer.prepareTranslateHTML(value, e).trim();\n }", "function isNull(val) {\n return val || \"\"\n}", "function esNull(valor){\n\tif(valor === \"null\" || valor === undefined || valor === null){\n\t\treturn '';\n\t}\n\treturn valor;\n}", "function _getAdjacentBlankNodeName(node, id) {\n return (node.type === 'blank node' && node.value !== id ? node.value : null);\n}", "function _getAdjacentBlankNodeName(node, id) {\n return (node.type === 'blank node' && node.value !== id ? node.value : null);\n}", "function _isBlankTextNode(node) {\n return node.nodeType === wysihtml5.TEXT_NODE && !wysihtml5.lang.string(node.data).trim();\n }", "function _isBlankTextNode(node) {\n return node.nodeType === wysihtml5.TEXT_NODE && !wysihtml5.lang.string(node.data).trim();\n }", "function xmlNodeValue(domNode) {\n \n if (domNode.nodeType === 1) {\n return xmlInnerText(domNode);\n }\n return domNode.nodeValue;\n}", "function GetInnerText (node)\n{\n return (node.textContent || node.innerText || node.text) ;\n}", "function isEmpty(node) {\n\t\treturn !node || (!node.childElementCount && (typeof node.textContent !== 'string' || node.textContent.trim() === ''));\n\t}", "function getNodeText(nodeElement)\n{\n if(!nodeElement)\n return null;\n if(typeof nodeElement===\"string\" || nodeElement instanceof String\n || typeof nodeElement===\"number\" || nodeElement instanceof Number)\n return nodeElement;\n return nodeElement.$\n}", "function getElementText (parent, localName, ns) {\n var el = _getFirstChildNS(parent, localName, ns);\n if (el === undefined) return undefined;\n return el.textContent;\n }", "function handleNull(value) {\n\tif(value == null) {\n\t\treturn \"\";\n\t}\n\treturn value;\n}", "get value() {\n return this._value !== undefined\n ? this._value\n : this._textElement.textContent.trim();\n }", "function getNodeValue(node, tag) {\nvar returnValue = undefined;\n\t\t\nif (tag !== \".\") {\nvar foundAt = -1;\n\ntry {\nfor (var i = 0; i < node.childNodes.length; i++) {\n\t\t\t\t\tif (node.childNodes[i].nodeName === tag) { \n\t\t\t\t\t\tfoundAt = i;\n\t\t\t\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (err1) {\n\t\t\t}\n\t\t\n\t\t\tif (foundAt === -1) {\n\t\t\t\ttry {\n\t\t\t\t\tif ((node.length !== undefined) && (node.length > 0)) {\n\t\t\t\t\t\tnode = node[0];\n\t\t\t\n\t\t\t\t\t\tfor (var j = 0; j < node.childNodes.length; j++) {\n\t\t\t\t\t\t\tif (node.childNodes[j].nodeName === tag) { \n\t\t\t\t\t\t\t\tfoundAt = j;\n\t\t\t\t\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (err2) {\n\t\t\t\t}\n\t\t\t}\n\t\t\n\t\t\tif (foundAt >= 0) {\n\t\t\t\tvar set = false;\n\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\treturnValue = node.childNodes[foundAt].nodeValue;\n\t\t\t\t\n\t\t\t\t\tif ((returnValue !== \"\") && (returnValue !== null) && (returnValue !== undefined)) {\n\t\t\t\t\t\tset = true;\n\t\t\t\t\t}\n\t\t\t\t} catch (err3) {\n\t\t\t\t}\n\t\t\t\n\t\t\t\tif (! set) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturnValue = node.childNodes[foundAt].textContent;\n\t\t\t\t\n\t\t\t\t\t\tif ((returnValue !== \"\") && (returnValue !== null) && (returnValue !== undefined)) {\n\t\t\t\t\t\t\tset = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (err4) {\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (! set) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (node.childNodes[foundAt].childNodes.length > 0) {\n\t\t\t\t\t\t\treturnValue = node.childNodes[foundAt].childNodes[0].textContent;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tif ((returnValue !== \"\") && (returnValue !== null) && (returnValue !== undefined)) {\n\t\t\t\t\t\t\tset = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (err5) {\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturnValue = node.textContent;\n\t\t}\n\t\t\n\t\tif (returnValue === undefined) {\n\t\t\treturnValue = \"\";\n\t\t}\n\t\t\n\t\treturnValue = returnValue.replace(/&amp;/gi,\"&\");\n\t\t\n\t\treturn returnValue;\n\t}", "StringValue(node) {\n return node.value;\n }", "function isNodeNully(node) {\n if (node == null) {\n return true;\n } else if (node.type === 'Identifier' && node.name === 'undefined') {\n return true;\n } else if (node.type === 'Literal' && node.value === null) {\n return true;\n } else if (node.type === 'UnaryExpression' && node.operator === 'void') {\n return true;\n } else {\n return false;\n }\n }", "function getNodeValue(elem, tag) {\n return elem.getElementsByTagName(tag)[0].firstChild.nodeValue;\n}", "function getNodeAsString()\n\t{\n\t\treturn this.n;\n\t}", "function is_node_empty(node) {\n return (node.nodeType == 3 && /^[\\s\\r\\n]*$/.test(node.nodeValue)) || node.nodeName == \"BR\";\n }", "function isEmpty(node){\n\t\t\t\t// If not for old IE we could check for Element children by node.firstElementChild\n\t\t\t\treturn (/^(p|div|br)$/i.test(node.nodeName) && node.children.length == 0 &&\n\t\t\t\t\t/^[\\s\\xA0]*$/.test(node.textContent || node.innerText || \"\")) ||\n\t\t\t\t\t(node.nodeType === 3/*text*/ && /^[\\s\\xA0]*$/.test(node.nodeValue));\n\t\t\t}", "getText(name = null) {\n if (name == null) {\n return this._text;\n } else {\n const el = this.getElement(name);\n if (! el) return undefined;\n return el._text;\n }\n }", "getNodeName() {}", "function getDomValue() {\n\t\t\t\tvar val = elem.val();\n\t\t\t\tif (val === attrs.placeholder) {\n\t\t\t\t\tval = '';\n\t\t\t\t}\n\t\t\t\treturn val;\n\t\t\t}", "function hc_nodevalue04() {\n var success;\n var doc;\n var newNode;\n var newValue;\n doc = load(\"hc_staff\");\n newNode = doc.doctype;\n\n \tassertTrue(\"docTypeNotNullOrDocIsHTML\",\n \n\t(\n\t(newNode != null)\n || \n\t(builder.contentType == \"text/html\")\n)\n);\n\n\tif(\n\t\n\t(newNode != null)\n\n\t) {\n\tassertNotNull(\"docTypeNotNull\",newNode);\nnewValue = newNode.nodeValue;\n\n assertNull(\"initiallyNull\",newValue);\n newNode.nodeValue = \"This should have no effect\";\n\n newValue = newNode.nodeValue;\n\n assertNull(\"nullAfterAttemptedChange\",newValue);\n \n\t}\n\t\n}", "get nativeElement() {\n return this.nativeNode.nodeType == Node.ELEMENT_NODE ? this.nativeNode : null;\n }", "function SRC_isNull(text)\r\n {\r\n \tvar notSpaceRE = /\\S/\r\n\r\n \tif ((text == null) || (text == \"\"))\r\n \t{\r\n \t\treturn true;\r\n \t}\r\n \treturn text.search(notSpaceRE) == -1;\r\n}", "_isNullOrUndefinedNodes() {\n return isNullOrUndefined(this._left) || isNullOrUndefined(this._right);\n }", "function _null() {\n return exports.PREFIX.null;\n}", "getTrueValue () {\n var val = this.getValue ();\n if (!val) return;\n if (val === NULL_CHARACTER) return null;\n return val;\n }", "function hc_nodeelementnodename() {\n var success;\n var doc;\n var elementNode;\n var elementName;\n doc = load(\"hc_staff\");\n elementNode = doc.documentElement;\n\n elementName = elementNode.nodeName;\n\n \n\tif(\n\t\n\t(builder.contentType == \"image/svg+xml\")\n\n\t) {\n\tassertEquals(\"svgNodeName\",\"svg\",elementName);\n \n\t}\n\t\n\t\telse {\n\t\t\tassertEqualsAutoCase(\"element\", \"nodeName\",\"html\",elementName);\n \n\t\t}\n\t\n}", "function haveNull(pos) {\r\n return pos.value == null;\r\n }", "function removeNull(msg) {\n if (msg) return msg;\n return '';\n}", "get viewValue() {\n // TODO(kara): Add input property alternative for node envs.\n return (this._getHostElement().textContent || '').trim();\n }", "get viewValue() {\n // TODO(kara): Add input property alternative for node envs.\n return (this._getHostElement().textContent || '').trim();\n }", "get viewValue() {\n // TODO(kara): Add input property alternative for node envs.\n return (this._getHostElement().textContent || '').trim();\n }", "function Xml_IsEmptyAttribute(objNode,strAttributeName)\r\n{\r\n var strAttributeValue = Xml_GetAttribute(objNode,strAttributeName,\"\");\r\n return (!strAttributeValue || strAttributeValue==\"\");\r\n}", "asElement() {\n return null;\n }", "function getNodeName(node) {\n var attr = node.attributes['_ktype'];\n if (attr != undefined)\n return attr.nodeValue;\n return '';\n }", "getText() {\n return this._node.__execute(() => this.element.getText());\n }", "function Null$prototype$toString() {\n return 'null';\n }", "function getRootHtmlNode(nodes)\n {\n for (var i = 0; i < nodes.length; i++)\n {\n if (nodes[i].nodeType === 1)\n {\n return nodes[i];\n }\n }\n\n return null;\n }", "function getTextValue(el) {\n\ttry {\n\t\tvar i;\n\t\tvar s;\n\t\t\n\t\t// Find and concatenate the values of all text nodes contained within the element.\n\t\ts = \"\";\n\t\tfor (i = 0; i < el.childNodes.length; i++) \n\t\t\tif (el.childNodes[i].nodeType == 3) \n\t\t\t\ts += el.childNodes[i].nodeValue;\n\t\t\telse \n\t\t\t\tif (el.childNodes[i].nodeType == 1 &&\n\t\t\t\tel.childNodes[i].tagName == \"BR\") \n\t\t\t\t\ts += \" \";\n\t\t\t\telse \n\t\t\t\t\t// Use recursion to get text within sub-elements.\n\t\t\t\t\ts += getTextValue(el.childNodes[i]);\n//\t\talert(\"getTextValue(\"+el+\")...s = \"+ s);\n\t\treturn normalizeString(s);\n\t}\n\tcatch (error){\n\t\tshowErrorMessage(error.message, \"getTextValue(\"+el+\")\");\n\t}\n}", "function HTML_AJAX_Serialize_Null() {}", "get firstChild() {\n return this.childNodes[0] || null;\n }", "function getInnerText(node) {\n if (node==undefined) return \"\";\n var result = '';\n if (Node.TEXT_NODE == node.nodeType)\n\treturn node.nodeValue;\n if (Node.ELEMENT_NODE != node.nodeType)\n\treturn '';\n for (var index = 0; index < node.childNodes.length; ++index)\n\tresult += getInnerText(node.childNodes.item(index));\n return result;\n} // getInnerText", "function node(v) {\n\t\t\t\tif (!v.firstChild ||\n\t\t\t\t\tv.firstChild.nodeName === \"#text\") {\n\t\t\t\t\tv = v.textContent.match(/[^\\n]+/);\n\n\t\t\t\t\treturn v != null ? v[0] : \"\";\n\t\t\t\t}\n\n\t\t\t\treturn node(v.firstChild);\n\t\t\t}", "get value() {\n return (this._inputNode && this._inputNode.value) || this.__value || '';\n }", "get textContent() {\n return this.#el?.textContent ?? this.#textContent;\n }", "function emptyElement(e)\n{\n if (typeof e != 'undefined')\n\tif (e.firstChild)\n\t while (e.firstChild)\n\t\te.removeChild(e.firstChild);\n}", "function isNullorEmpty(strVal) {\n return (strVal == null || strVal == '' || strVal == 'null' || strVal ==\n undefined || strVal == 'undefined' || strVal == '- None -' ||\n strVal ==\n '0');\n }", "get viewValue() {\n // TODO(kara): Add input property alternative for node envs.\n return (this._text?.nativeElement.textContent || '').trim();\n }", "function getTextValueOfChild (node) {\n var str\n visitChildren ( \n node,\n function (x){str=x.nodeValue},\n Node.TEXT_NODE\n )\n if (!str){\n str = \"\" \n }\n str = str.replace(/^\\s+/,\"\") \n return str.replace(/\\s+$/, \"\")\n}", "get value(){\n return this.nodeValue;\n }", "get value(){\n return this.nodeValue;\n }", "function getDataFromElement(element){\n\treturn (element != undefined) ? element : \"\";\n}", "get nodeName() {\n return this.getAsElem(0).getIf(\"nodeName\");\n }", "get nodeName() {\n return this.getAsElem(0).getIf(\"nodeName\");\n }", "function isNullorEmpty(strVal) {\n return (strVal == null || strVal == '' || strVal == 'null' || strVal ==\n undefined || strVal == 'undefined' || strVal == '- None -' ||\n strVal ==\n '0');\n }", "function getText(n) {\n switch (n.nodeType) {\n case 1: /* element */\n var s = \"\";\n for (var c = n.firstChild; c != null; c = c.nextSibling) {\n s += getText(c);\n }\n return s;\n case 2: /* attribute*/\n case 3: /* text */\n case 4: /* cdata */\n return n.nodeValue;\n default:\n return \"\";\n }\n }", "function isBlankNode(term) {\n return !!term && term.termType === 'BlankNode';\n}", "getAttributeValue(key) {\n const attr = this.getAttribute(key);\n if (attr) {\n return attr.value !== null ? attr.value.toString() : null;\n }\n else {\n return null;\n }\n }", "function serializeXmlNode(xmlNode) {\n if (typeof window.XMLSerializer != \"undefined\") {\n return (new window.XMLSerializer()).serializeToString(xmlNode);\n } else if (typeof xmlNode.xml != \"undefined\") {\n return xmlNode.xml;\n }\n return \"\";\n }", "function isNull(val){return(val==null);}", "function attrNull() {\n this.removeAttribute(name);\n }", "function isBlankNode(str) {\n str = str.trim();\n if (str.charAt(0) == \"_\" && str.charAt(1) == \":\") {\n return str;\n } else if (str.charAt(0) == \"[\" && str.charAt(str.length - 1) == \"]\") {\n return str;\n } else {\n return false;\n }\n}", "function getInnerText(elem) {\n\t\treturn (typeof elem.textContent == \"string\") ? elem.textContent : elem.innerText;\n\t}", "validateNone(node) {\n if (classifyNodeText(node) === TextClassification.EMPTY_TEXT) {\n return;\n }\n this.reportError(node, node.meta, `${node.annotatedName} must not have text content`);\n }", "function findNull(el) {\n return el===\"author\";\n }", "function attrNull() {\n this.removeAttribute(name);\n }", "function attrNull() {\n this.removeAttribute(name);\n }", "function replaceNull(value) {\r\n\treturn (value === null || value === \"null\") ? \"\" : value;\r\n}", "function nullIfEmpty(string){\n\t\tif(string === '' || string === null || string === undefined){\n\t\t\treturn null;\n\t\t}\n\t\telse{return string;}\n\t}", "function _getText(node) {\n\n if (node.nodeType === 3) {\n return node.data;\n }\n\n var txt = '';\n\n if (!!(node = node.firstChild)) do {\n txt += _getText(node);\n } while (!!(node = node.nextSibling));\n\n return txt;\n\n }", "'renderEmptyNodeJqo'() {\n\t\treturn [this.renderBeginTagToHtml(), this.renderEndTagToHtml(), this.renderHtmlAppendment()].join('');\n\t}", "function getTitleNode()\r\n{\r\n\tvar nodes = document.evaluate(\"//span[@id='\" + titleNodeId + \"']\", document, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);\r\n\tif(!nodes){\r\n\t\treturn null;\r\n\t}\r\n\r\n\tvar thisNode = nodes.iterateNext(); \r\n\tvar titleNode;\r\n\t// Get the last node\r\n\twhile(thisNode){\r\n\r\n\t\t//GM_log( thisNode.textContent );\r\n\t\ttitleNode = thisNode;\r\n\t\tthisNode = nodes.iterateNext();\r\n\t}\r\n\r\n\t//was (titleValue == null)\r\n\tif (titleNode == null) {\r\n GM_log(\"can't find title node\");\r\n\t\treturn null;\r\n\t}\r\n\telse {\r\n GM_log(\"Found title node: \" + titleNode.textContent);\r\n\t}\r\n\treturn titleNode;\r\n}", "function tf_GetNodeText(n)\r\n/*====================================================\r\n\t- returns text + text of child nodes of a node\r\n=====================================================*/\r\n{\r\n\tvar s = n.textContent || n.innerText || n.innerHTML.replace(/\\<[^<>]+>/g, '');\r\n\ts = s.replace(/^\\s+/, '').replace(/\\s+$/, '')/*.tf_Trim()*/;\r\n\treturn s.tf_Trim();\r\n}", "function getElementTextNS(prefix, local, parentElem, index) {\r\n// alert('entro');\r\n var result = \"\";\r\n if (prefix && isIE) {\r\n // IE/Windows way of handling namespaces\r\n result = parentElem.getElementsByTagName(prefix + \":\" + local)[index];\r\n } else {\r\n // the namespace versions of this method \r\n // (getElementsByTagNameNS()) operate\r\n // differently in Safari and Mozilla, but both\r\n // return value with just local name, provided \r\n // there aren't conflicts with non-namespace element\r\n // names\r\n// alert(' antes de result entro');\r\n result = parentElem.getElementsByTagName(local)[index];\r\n }\r\n if (result) {\r\n // get text, accounting for possible\r\n // whitespace (carriage return) text nodes \r\n if (result.childNodes.length > 1) {\r\n return result.childNodes[1].nodeValue;\r\n } else {\r\n return result.firstChild.nodeValue; \r\n }\r\n } else {\r\n return \"n/a\";\r\n }\r\n}", "function isEmptyInlineElement(node) {\n\t if( node.children.length > 1 ) return false;\n\t if( node.children.length === 1 && node.textContent.trim() !== '' ) return false;\n\t if( node.children.length === 0 ) return node.textContent.trim() === '';\n\t return isEmptyInlineElement(node.children[0]);\n\t }", "function evaluateNullLiteral(_options) {\n return null;\n}", "isNull() {\n assert.equal(resource.change.after_unknown, null);\n }", "function getElemValue(aID, aDefaultValue)\n{\n var rv = aDefaultValue;\n var elem = document.getElementById(aID);\n if (elem)\n {\n switch (elem.tagName)\n {\n case \"checkbox\":\n rv = elem.checked;\n break;\n case \"radio\":\n rv = elem.selected;\n break;\n case \"textbox\":\n case \"menulist\":\n case \"listbox\":\n rv = elem.value;\n break;\n }\n }\n\n if (rv && (\"string\" == (typeof rv)))\n rv = rv.trim();\n\n return rv;\n}", "function checaNullUndefined(arr){\n\treturn ((arr === null || arr === undefined) ? \"\" : arr)\n}", "get innerText() {\n return this.#el?.innerText ?? this.#innerText;\n }" ]
[ "0.6444224", "0.6444224", "0.6444224", "0.6444224", "0.6444224", "0.6444224", "0.6393919", "0.6361848", "0.61373246", "0.6120681", "0.6119781", "0.6024086", "0.5964991", "0.5961994", "0.5906481", "0.5892821", "0.58725256", "0.58251286", "0.5750651", "0.575056", "0.575056", "0.5701874", "0.5701874", "0.56929183", "0.56914693", "0.56528986", "0.56307966", "0.5606922", "0.55362165", "0.5492784", "0.5478606", "0.5464898", "0.54589665", "0.5457511", "0.54355925", "0.5424657", "0.5394896", "0.5386318", "0.5356005", "0.53488445", "0.5323893", "0.53002995", "0.5299849", "0.5287831", "0.52755576", "0.527199", "0.5219411", "0.5216359", "0.52110296", "0.5203562", "0.5203562", "0.5203562", "0.5199185", "0.51738733", "0.5169333", "0.5168908", "0.5162488", "0.5143782", "0.513645", "0.5126043", "0.5121835", "0.51202846", "0.5115606", "0.51088375", "0.5105703", "0.51025754", "0.509684", "0.50797594", "0.5078072", "0.5069737", "0.5069737", "0.50685203", "0.5063419", "0.5063419", "0.5063215", "0.5059062", "0.50524724", "0.50467473", "0.50464374", "0.50325876", "0.50272274", "0.5022087", "0.50144404", "0.4987216", "0.4983961", "0.49774012", "0.49774012", "0.4977258", "0.49733016", "0.49361268", "0.4935695", "0.49328598", "0.4925164", "0.4922491", "0.49193817", "0.491693", "0.49078184", "0.49011233", "0.48978516", "0.48947555" ]
0.6501883
0
populate the drop down list with ids from sample set
function populateDropDown() { // select the panel to put data var dropdown = d3.select('#selDataset'); jsonData.names.forEach((name) => { dropdown.append('option').text(name).property('value', name); }); // set 940 as place holder ID populatedemographics(jsonData.names[0]); visuals(jsonData.names[0]); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function initializeIDPulldown() {\n samples_data.names.forEach((val, index) => {\n let selDataset = d3.select(\"#selDataset\");\n let option = selDataset.append(\"option\");\n option.property(\"text\", val);\n option.property(\"value\", index);\n console.log(samples_data.names);\n })\n}", "function populateDropdowns() {\n}", "function populateDropdown() {\n var dropdown = d3.select(\"#selDataset\")\n d3.json(\"samples.json\").then(data => {\n var patientIDs = data.names;\n patientIDs.forEach(patientID => {\n dropdown.append(\"option\").text(patientID).property(\"value\", patientID)\n })\n })\n}", "populate_dropdown() {\n let dropdown = $(\"#vertex-shader\");\n this.shader_lib.vertex_info.map((x, i) => {\n $('<option>')\n .val(i)\n .html(x.title)\n .appendTo(dropdown);\n });\n }", "function populateBreedsSelect(breeds) {\n $breed_select.empty().append(function() {\n var output = '';\n $.each(breeds, function(key, value) {\n output += '<option id=\"' + value.id + '\">' + value.name + '</option>';\n });\n return output;\n });\n}", "function getdropdown() {\n var dropdownMenu = d3.select(\"#selDataset\");\n\n d3.json(\"samples.json\").then(function (data) {\n let uniqueIds = data.names;\n console.log(uniqueIds);\n uniqueIds.forEach(element => dropdownMenu.append('option').property('value', element).text(element));\n })\n}", "function idList(data) {\n var dropList = d3.select('#selDataset');\n dropList.selectAll('option')\n .data(data)\n .enter()\n .append('option')\n .attr( 'value', d => d )\n .text( d => d );\n }", "function populateSampleList(data) {\n\n data = data.sort();\n\n $.each(data, function(key, value) {\n $('#zz')\n .append($(\"<option></option>\")\n .attr(\"value\", value)\n .on(\"click\", addToList)\n .text(value));\n });\n\n\n\n $(\"#zz\").val('-- select projectRun --').trigger(\"chosen:updated\");\n $(\"#loading\").hide();\n\n}", "function init () {\n d3.json(\"samples.json\").then(data => {\n console.log(data);\n var IDs = d3.select(\"#selDataset\");\n var IDsValues = data.names;\n IDsValues.forEach(id => {\n IDs.append(\"option\").text(id).property(\"value\", id);\n })\n });\n}", "function loadDropDowns(myId, myshortList, myText) {\n // var tbody = d3.select(\"tbody\");\n var inputDate = d3.select(myId) \n \n inputDate.html(\" \");\n \n console.log(myshortList);\n var cell = inputDate.append(\"option\").text(myText);\n \n myshortList.forEach((f) => {\n console.log(f);\n var cell = inputDate.append(\"option\")\n cell.text(f);\n \n });\n }", "function dropDown(sampleData){\n\tsampleData['names'].forEach(name=>{\n\t\tvar newItem = d3.select('#selDataset').append('option');\n\t\tnewItem.text(name);\n\t\tnewItem.property('value', name)\n\t});\n}", "function filterSamples(i) {\n\n // return the id that is equal to the dropdown value option\n return i.id == dName\n }", "function populateGroupDropdown(){\n $.each(grps, function(i,group){\n $('#group').append($('<option>').attr(\"value\",group.id).text(\"\\$\"+group.name+\"\\$\"))\n });\n MathJax.Hub.Queue([\"Typeset\",MathJax.Hub,\"group\"]);\n $('.selectpicker').selectpicker('refresh');\n}", "function getListOfDistrict_reg() {\n loadingDistrictsMaster();\n $.each(district, function(i, resData) {\n var districts = \"<option value=\" + resData.districtID + \">\" + resData.districtName + \"</option>\";\n $(districts).appendTo('#reg_statutory_districtID');\n });\n $('#reg_statutory_districtID').trigger(\"chosen:updated\");\n $(\"#reg_statutory_districtID\").chosen();\n}", "function loadChoices(id)\n{\n var candArr = [];\n $('#select' + id).find('select').each(function() {\n candArr.push($(this).children(':selected').text());\n });\n candArr = $.map(candArr, function(val){\n if(val == \"No Selection\")\n {\n return \"\";\n console.log(val + \"is ns\");\n }\n else\n {\n return \"<li>\" + val + \"</li>\";\n }\n });\n $('#modal'+id+' .cand-list').html(candArr);\n}", "function dropDownMenu(x) {\r\n\r\n x.forEach(id => {\r\n var option = d3.select(\"#selDataset\").append(\"option\");\r\n option.text(id);\r\n\r\n });\r\n}", "function populateSelections(data) {\n var selector = document.getElementById('selector');\n\n data.forEach(function (item) {\n var option = document.createElement('option');\n option.text = item;\n option.value = item;\n selector.appendChild(option);\n });\n}", "function getListOfDistrict() {\n loadingDistrictsMaster();\n $.each(district, function(i, resData) {\n var districts = \"<option value=\" + resData.districtID + \">\" + resData.districtName + \"</option>\";\n $(districts).appendTo('#district_id');\n });\n $('#district_id').trigger(\"chosen:updated\");\n $(\"#district_id\").chosen();\n}", "function init() {\n d3.json(\"samples.json\").then((data) => {\n console.log(\"data\");\n console.log(data);\n\n s_ids = data.names;\n console.log(\"s_ids\");\n console.log(s_ids);\n\n s_ids.map((id) => { //defines the drop down menu\n dropdownMenu\n .append(\"option\")\n .property(\"value\", id)\n .text(id);\n });\n optionChanged(s_ids[0])\n \n });\n}", "function populate_specialization_dropdown_by_query()\n{\n let select = document.getElementById(\"Select Specialization\");\n let arr= Get(\"api/buttonsdynamically/get/specialization\");\n if(select===null)\n alert(\"empty object retrieved from DOM parse\");\n if( select.length>1) {\n //alert(\"Specialization already exist in under the domain button, no need to again add them\");\n return \"\";\n }\n for (let i = 0; i < arr.length; i++) {\n let option = document.createElement(\"OPTION\"), txt = document.createTextNode(arr[i]);\n option.appendChild(txt);\n option.setAttribute(\"value\", arr[i]);\n select.insertBefore(option, select.lastChild);\n }\n}", "function getListOfDistrict() {\n loadingDistrictsMaster();\n $.each(district, function(i, resData) {\n var districts = \"<option value=\" + resData.districtID + \">\" + resData.districtName + \"</option>\";\n $(districts).appendTo('#statutory_districtID');\n });\n $('#statutory_districtID').trigger(\"chosen:updated\");\n $(\"#statutory_districtID\").chosen();\n}", "function createDropDown(ids) {\n // select dropdown by id\n var dropdown = d3.select(\"#selDataset\");\n ids.forEach(function (item, index) {\n addDropdownOption(item, item);\n });\n\n}", "function populate_user_specialization_dropdown_by_query()\n{\n let select = document.getElementById(\"Select User Course Specialization\");\n let arr= Get(\"api/buttonsdynamically/get/specialization\");\n if(select===null)\n alert(\"empty object retrieved from DOM parse\");\n if( select.length>1) {\n //alert(\"Specialization already exist in under the domain button, no need to again add them\");\n return \"\";\n }\n for (let i = 0; i < arr.length; i++) {\n let option = document.createElement(\"OPTION\"), txt = document.createTextNode(arr[i]);\n option.appendChild(txt);\n option.setAttribute(\"value\", arr[i]);\n select.insertBefore(option, select.lastChild);\n }\n \n}", "function populate(id, array) {\n let $dropdown = $(id);\n $.each(array, function() {\n $dropdown.append($(\"<option>\").val(this).text(this)).trigger('change');\n });\n}", "function initializeIDPulldown() {\n let selPeriod = d3.select(PULLDOWNID);\n let option;\n \n option = selPeriod.append(\"option\");\n option.property(\"text\", \"Spring 2018\");\n option.property(\"value\", S2018);\n\n option = selPeriod.append(\"option\");\n option.property(\"text\", \"Fall 2018\");\n option.property(\"value\", F2018);\n\n option = selPeriod.append(\"option\");\n option.property(\"text\", \"Spring 2019\");\n option.property(\"value\", S2019);\n\n option = selPeriod.append(\"option\");\n option.property(\"text\", \"Fall 2019\");\n option.property(\"value\", F2019);\n}", "function lists(ev)\r\n{\r\n list = JSON.parse(httd.responseText);\r\n size = list.length;\r\n var sel;\r\n if(start ==1)\r\n {\r\n sel = document.getElementById(\"uni0\");\r\n start--;\r\n }\r\n else \r\n {\r\n var c = num;\r\n sel = document.getElementById(\"uni\"+ --c);\r\n }\r\n for(var i = 0; i<size; i++)\r\n {\r\n var opt = document.createElement(\"Option\");\r\n opt.innerText= list[i].University_name;\r\n sel.appendChild(opt);\r\n }\r\n}", "function update_ids_list(){\r\n\t// clean first\r\n\t$('select#div-id').empty();\r\n\t$('select#config-id-selected').empty();\r\n\t\r\n\t// add from id_class object\r\n\tfor(let key in css_ids){\r\n\t\tlet tmp = $('<option></option').attr('value',key).text(key);// create node\r\n\t\t$('select#div-id').append(tmp);// append node\r\n\r\n\t\ttmp = $('<option></option').attr('value',key).text(key);// create node\r\n\t\t$('select#config-id-selected').append(tmp);// append node\r\n\t}\r\n\t\r\n\t// deselect id\r\n\t$('select#div-id').val('');\r\n}", "function getListOfDistrict_scene() {\n $(\"#districs_id\").empty();\n $(\"#districs_id_reg\").empty();\n\n loadingDistrictsMaster();\n var selectfirst = \"<option value='0'>Select District</option>\";\n $('#districs_id').append(selectfirst);\n $('#districs_id_reg').append(selectfirst);\n $.each(district, function (i, resData) {\n var districts = \"<option value=\" + resData.districtID + \">\" + resData.districtName + \"</option>\";\n $(districts).appendTo('#districs_id');\n $(districts).appendTo('#districs_id_reg');\n\n });\n $('#districs_id').trigger(\"chosen:updated\");\n $('#districs_id_reg').trigger(\"chosen:updated\");\n $('#districs_id').chosen();\n $('#districs_id_reg').chosen();\n}", "function putItemsInSelect(){\n\tfor(var i = 0; i < patient_items.length; i++){\n\t\t$(\"#patient-list\").append(\"<option value='\" + patient_items[i] + \"'>\" + patient_items[i] + \"</options>\");\n\t}\n\tfor(var i = 0; i < test_type_items.length; i++){\n\t\t$(\"#test-type-list\").append(\"<option value='\" + test_type_items[i] + \"'>\" + test_type_items[i] + \"</options>\");\n\t}\n\tfor(var i = 0; i < date_items.length; i++){\n\t\t$(\"#date-list\").append(\"<option value='\" + date_items[i] + \"'>\" + date_items[i] + \"</options>\");\n\t}\n}", "function populateMonths() {\n let template = $('#ddlViewBy').find('option:selected').val();\n\n // update dropdown\n $(\"#monthID\").empty();\n for (i in availableMonths[template]) {\n let month = availableMonths[template][i];\n if (months.indexOf(month) < 0) {\n $(\"#monthID\").append($('<option></option>').val(month).html(month));\n }\n }\n }", "function dropDown() {\n // Use list of sample names to render the select options\n Plotly.d3.json(\"/names\", function (error, response) {\n if (error) return console.warn(error);\n\n let selection = document.getElementById(\"select-dataset\");\n for (let i = 0; i < response.length; i++) {\n let selectedOption = document.createElement(\"option\");\n selectedOption.text = response[i];\n selectedOption.value = response[i];\n selection.appendChild(selectedOption);\n }\n getData(response[0], createCharts);\n });\n}", "function populateOptions(select, list, uidToSet) {\n var str = list.reduce(function(acc, val) {\n var opt = '<option value=\"' + val.uid + '\"';\n if(uidToSet && uidToSet === val.uid) {\n opt += ' selected';\n }\n opt += '>' + val.codice + ' - ' + val.descrizione + '</option>';\n return acc + opt;\n }, '<option></option>');\n select.append(str);\n }", "function populateNames(data){\n var result = _.uniq(data);\n for (var x = 0; x < result.length; x++){\n var $opt = $('<option>');\n $opt.text(result[x]);\n $('#names').append($opt);\n }\n }", "function populate(arr, cntrl) {\n\tvar i;\n\t$(cntrl).html(\"\");\n\tfor(i = 0; i < arr.length; i++) {\n\t\t//original using terms\n\t\t// $(cntrl).append(\"<option value='\"+ arr[i].vocabterm.value +\"'>\"+arr[i].vocabterm.value+\" (\"+ arr[i].occurence.value+\")</option>\"); \n\t\t//redesign using encoded uris\n\t\t$(cntrl).append(\"<option value='\"+ arr[i].vocabterm.value + \"#\" + arr[i].classification.value +\"'>\"+arr[i].vocabterm.value+\" (\"+ arr[i].occurence.value+\")</option>\"); \n\t}\n\t$(cntrl).multiselect({title: \"Select Term\"});\n\t\n\t\n}", "function init(){\r\n\tgenDropDownList();\r\n}", "function init() {\n resetData();\n d3.json(\"data/samples.json\").then((data => {\n data.names.forEach((name => {\n var option = idSelect.append(\"option\");\n option.text(name);\n }));\n var initId = idSelect.property(\"value\")\n plotCharts(initId);\n })); \n}", "function populateDropdown(selection, masterGenres) {\n for (var i = 0; i < masterGenres.length; i++) {\n var opt = masterGenres[i];\n var el = document.createElement(\"option\");\n el.textContent = opt;\n el.value = opt;\n selection.appendChild(el);\n }\n}", "function handleRenderOptions() {\n let url = 'https://api.napster.com/v2.2/genres?apikey=OTI0NjE5NWEtNWVjOC00ZTJjLTliMDgtOTdkMTg5NjEwYmU0';\n\n fetch(url)\n .then(function (response) {\n return response.json();\n })\n .then(function (data) {\n //console.log(data.genres);\n for (var i = 0; i < data.genres.length; i++) {\n let options = data.genres[i].name;\n let genreId = data.genres[i].id;\n genreArray = data.genres\n //console.log(options, genreId);\n let userOptions = document.createElement('option');\n userOptions.innerHTML = options;\n userOptions.value = genreId;\n select$.append(userOptions);\n select$.formSelect();\n }\n })\n }", "function fillAttributeDropdown(selectElement, idPrefix) {\n for (var a=0; a<attributeTrainingOptions.length; a++) {\n var id = null;\n if (idPrefix!=null) {\n id = idPrefix+attributeTrainingOptions[a];\n }\n addElement('option', id, selectElement, {\n\t\t\tvalue : attributeTrainingOptions[a],\n\t\t\tinnerHTML: attributeTrainingOptions[a]\n });\n }\n}", "function defenders_dropdown(){ \n // Adapted from: https://www.encodedna.com/javascript/populate-select-dropdown-list-with-json-data-using-javascript.htm\n var ele = document.getElementById('sel_defenders');\n var defenderschoice = Object.keys(defendersInTheBox)\n for (var i = 0; i < defenderschoice.length; i++) {\n ele.innerHTML = ele.innerHTML + '<option value=\"' + defenderschoice[i] + '\">' + defenderschoice[i] + '</option>';\n };\n\n}", "function init() {\n var selector = d3.select(\"#selDataset\")\n d3.json(\"samples.json\").then((data) => {\n // console.log(importedData);\n // var data = importedData.samples;\n\n // Select the dropdown element\n var subjectIds = data.names;\n subjectIds.forEach((id) => {\n selector\n .append(\"option\")\n .text(id)\n .property(\"value\", id);\n });\n var firstSample = subjectIds[0];\n buildCharts(firstSample);\n buildMetadata(firstSample);\n });\n }", "function populateDatasetDropdownCurate(datasetDropdown, datasetlist) {\n removeOptions(datasetDropdown);\n\n /// making the first option: \"Select\" disabled\n addOption(datasetDropdown, \"Select dataset\", \"Select dataset\");\n var options = datasetDropdown.getElementsByTagName(\"option\");\n options[0].disabled = true;\n\n for (var myitem of datasetlist) {\n var myitemselect = myitem.name;\n var option = document.createElement(\"option\");\n option.textContent = myitemselect;\n option.value = myitemselect;\n datasetDropdown.appendChild(option);\n }\n}", "function renderMenu(){\n $.get(\"/api/masterPlants/\", function(mData){\n for (var i=0; i<mData.length; i++){\n var newOption = $(\"<option>\").text(mData[i].common_name).addClass(\"drop-down\");\n newOption.attr({\"value\":mData[i].id});\n $(\"#drop-down\").append(newOption);\n } \n })\n }", "function populateStrategicValues() {\n var listitems;\n listitems = '<option value=\"0\">--None--</option>';\n var selectStrategicId = $('#selOtherSrc2');\n selectStrategicId.empty();\n $.ajax({\n url: 'api/data/GetStrategicValues'\n }).done(function (data) {\n $.each(data, function (key, value) {\n listitems += '<option value=' + key + '>' + value + '</option>';\n });\n selectStrategicId.append(listitems);\n }).fail(function () {\n alert('fail');\n });\n}", "function getCohort() {\n let xhttp = new XMLHttpRequest();\n xhttp.onreadystatechange = function () {\n if (xhttp.readyState === 4 && xhttp.status === 200) {\n let arrayCohorts = JSON.parse(xhttp.responseText);\n // console.log(arrayCohorts);\n let select = document.getElementById(\"cboCohorts\");\n for (let i in arrayCohorts) {\n let option = document.createElement(\"option\");\n select.options.add(option, 0);\n select.options[0].value = arrayCohorts[i].id;\n select.options[0].innerText = arrayCohorts[i].id;\n }\n }\n };\n \n xhttp.open(\"GET\", \"../data/cohorts.json\", true);\n xhttp.send();\n }", "function initialLoad() {\n var selectYear = document.getElementById(\"year\");\n for (cnt in year) {\n // console.log(\"year:\"+year[cnt]);\n var optionYear = document.createElement(\"option\");\n optionYear.text = year[cnt];\n optionYear.value = year[cnt];\n selectYear.add(optionYear);\n }\n //document.getElementById(\"year\").multiple = true; // to enable multi-select\n\n var selectDistrict = document.getElementById(\"district\");\n for (cnt in district) {\n var optionDistrict = document.createElement(\"option\");\n optionDistrict.text = district[cnt];\n optionDistrict.value = ++cnt;\n selectDistrict.add(optionDistrict);\n }\n\n var selectCounty = document.getElementById(\"county\");\n for (cnt in countyName) {\n var optionCounty = document.createElement(\"option\");\n optionCounty.text = countyName[cnt];\n optionCounty.value = ++cnt;\n selectCounty.add(optionCounty);\n }\n}", "populateNumberBases(elSelector, numberBaseArray) {\n let selectElement = document.getElementById(elSelector);\n\n numberBaseArray.forEach((numberBase) => {\n let optionElement = document.createElement('option');\n optionElement.textContent = numberBase;\n optionElement.value = numberBase;\n selectElement.appendChild(optionElement);\n });\n }", "function populateStates(states) {\n let stateDropdown = document.getElementById(\"stateDropdown\");\n stateDropdown.innerHTML = ''; // Delete Children\n console.log(states);\n\n for (let i = 0; i < states.length; i++) {\n let s = document.createElement('option');\n s.innerHTML = states[i].business_state;\n s.value = states[i].business_state;\n stateDropdown.appendChild(s);\n }\n document.getElementById(\"stateDropdown\").selectedIndex = -1; // Default state is set to empty\n}", "function init(){\n d3.json(\"/api/race_stats\").then((race_stats) => { \n // divisionArray = race_stats.Division;\n var ddlItems = document.getElementById(\"selDataset\")\n var uniqueDivisionArray=[];\n var opt;\n for (var i = 0; i < race_stats.length; i++) {\n opt = race_stats[i].Division;\n if(!uniqueDivisionArray.includes(opt)){\n console.log(\"Unique division name found: \" + opt);\n uniqueDivisionArray.push(opt);\n var element = document.createElement(\"option\");\n element.textContent = opt;\n element.value = opt;\n ddlItems.appendChild(element);\n } \n }\n }) \n}", "function init () {\n var dropdownMenu = d3.select(\"#selDataset\");\n d3.json(\"samples.json\").then((data) => {\n var names = data.names;\n names.forEach(function(id) { //exercise 14.1\n dropdownMenu.append(\"option\").text(id).property(\"value\",id); \n });\n updatecharts(data.samples[0]);\n getDemoInfo(data.names[0]);\n });\n\n}", "function populateList(response) {\n console.log(response);\n var libraries = JSON.parse(response);\n var librarySelect = document.getElementById(\"librarySelect\");\n var currentLibrary;\n\n for (var i = 0; i < libraries.length; i++) {\n currentLibrary = libraries[i].library;\n librarySelect.innerHTML += \"<option value='\"+currentLibrary+\"'>\"+currentLibrary+\" Library</option>\";\n }\n}", "function populateSelect() {\r\n//\tIn base al numero di diversi tipi di icone presenti nell'array\r\n//\tPopola la <select> nell'HTML\t\r\n\tvar types = getUniqueTypes(iconsAll);\r\n\tselect.innerHTML = `<option value=\"all\">Mostra Tutto</option>`;\r\n\tfor(let i = 0; i < types.length; i++) {\r\n\t\tselect.innerHTML += `<option value=\"${types[i]}\">Mostra \"${types[i]}\"</option>`;\r\n\t}\r\n}", "function fillSelect() {\n let select = $('#selectRFC').get(0);\n while (select.firstChild) select.removeChild(select.firstChild);\n for (let i = 0; i < response.length; i++) {\n let opt = document.createElement('option');\n opt.value = i;\n opt.innerHTML = response[i].client_rfc;\n select.appendChild(opt);\n }\n}", "function populateSAttackSelect(sAttack){\n\n\tvar saSelect = document.querySelector(\"#saSelect\");\n\n\tfor(var index = 0; index < sAttack.length; index++){\n\n\t\tvar cSA = sAttack[index];\n\n\t\tvar nOpt = document.createElement(\"option\");\n\n\t\tnOpt.id = \"sa_\"+index;\n\t\tnOpt.innerHTML = cSA.name;\n\t\tnOpt.value = index;\n\n\t\tvar cSAStats = Object.keys(cSA);\n\n\t\tfor(var indexS = 0; indexS < cSAStats.length; indexS++){\n\n\t\t\tnOpt.dataset[cSAStats[indexS]] = cSA[cSAStats[indexS]];\n\t\t}\n\n\t\tsaSelect.appendChild(nOpt);\n\t}\n\n\t$('#saSelect').material_select();\n\t$('#saSelect').on('change', socialAttackSelectEvt);\n}", "function baseLocation_reg(listOfDistrict) {\n\t $(\"#basloc_id_reg\").empty();\n loadingBaseLocationMaster(listOfDistrict);\n var selectfirst = \"<option value='0'>Select Base Location</option>\";\n $('#basloc_id_reg').append(selectfirst);\n $.each(baselocations, function (i, resData) {\n var baselocation = \"<option value=\" + resData.baselocationID + \">\" + resData.baselocationName + \"</option>\";\n $(baselocation).appendTo('#basloc_id_reg');\n });\n $('#basloc_id_reg').trigger(\"chosen:updated\");\n $(\"#basloc_id_reg\").chosen();\n\n}", "function init(){\n\n d3.json(\"static/data/year.json\").then(function(raw) { \n console.log(\"raw data from first pull down selection\")\n console.log(raw)\n\n \n // Identifies unique years to populate pull down menu\n var teamList = raw.map(raw => raw.team);\n teamList = uniqueArray4(teamList); \n console.log(teamList);\n\n\n // populates pull down list with team names/// IT WORKS!!!! YES!!!!!!!!!\n teamList.forEach(i =>\n d3.select(\"select\")\n .append(\"option\")\n .text(i)\n .property(\"value\", i)\n );\n \n // Use the first sample from the list to build the initial plots\n var firstSample = \"ARI\";\n drawChart(firstSample);\n\n\n });\n\n\n}", "function getInterventions() {\n $http.get('/Administrator/GetInterventions').\n then(function (results) {\n var interventions = results.data;\n $scope.interventions = interventions;\n var select = document.getElementById(\"interventionSelect\");\n for (var i = 0; i < interventions.length; i++) {\n // $('#interventionSelect').append(\"<option value='\" + interventions[i].Id + \"'>Id:\" + interventions[i].Id + \" Name:\" + interventions[i].Name + \"</option>\");\n }\n \n }, function (error) {\n });\n }", "function wasteList(){\n getItemList().then(function(body){\n\n for (let i = 0; i < body.length; i++){\n console.log(body[i].itemName);\n console.log(body[i]._id)\n console.log(\"getting the items\");\n let dropWaste = document.getElementById(\"wasteDrop\");\n //let wasteOptions = document.createElement('option');\n \n dropWaste.innerHTML += `<option value = \"${body[i]._id}\" data-name = \"${body[i].itemName}\" data-id=\"${body[i]._id}\">${body[i].itemName}</option>`\n \n }\n }).catch(function(err){\n console.log(err);\n });\n }", "function addOptions(all_data) {\n let sample_names = all_data[\"names\"]\n let select_element = d3.select(\"#selDataset\")\n\n // console.log(sample_names)\n\n for (let i = 0; i < sample_names.length; i++) {\n select_element.append(\"option\").property(\"value\", sample_names[i]).text(sample_names[i])\n }\n console.log(all_data)\n}", "function setCategories(categories) {\n var output = '<select name=\"categoryId\" id=\"entity_categoryId\" class=\"form-control\">';\n for (var category in categories) {\n output += '<option value=\"' + categories[category].id + '\">' + categories[category].name + '</option>';\n }\n output += '</select>';\n document.getElementById(\"categories\").innerHTML = output;\n}", "function genreListDisplay() {\n var genreList = ['Genre', 'Romance', 'Thriller', 'Paranormal', 'Fantasy', 'Young Adult', 'Mystery', 'Dark', 'Contemporary', 'Comedy'];\n let selects = document.getElementsByClassName(\"custom-select\");\n for(let i=0; i<selects.length; i++) {\n selects[i].innerHTML = '';\n genreList.map((text, id) => {\n let temp = '<option value=\"'+text+'\">'+text+'</option>';\n selects[i].innerHTML += temp;\n });\n }\n}", "function createDropdowns() {\n //region\n region_options = '';\n for (var i in region_info){\n region_options += '<option value=\"' + region_info[i] + '\">'+ region_info[i] + '</option>'\n }\n $('#id_region').append($.parseHTML(region_options));\n //habitat\n habitat_options = '';\n for (var i in habitat_info){\n habitat_options += '<option value=\"' + habitat_info[i] + '\">'+ habitat_info[i] + '</option>'\n }\n $('#id_habitat').append($.parseHTML(habitat_options));\n //status\n status_options = '';\n for (var i in status_info){\n status_options += '<option value=\"' + status_info[i] + '\">'+ status_info[i] + '</option>'\n }\n $('#id_status').append($.parseHTML(status_options));\n //family\n family_options = '';\n for (var i in family_info){\n family_options += '<option value=\"' + family_info[i] + '\">'+ family_info[i] + '</option>'\n }\n $('#id_family').append($.parseHTML(family_options));\n\n\n }", "function populateDropdown(elementarr, dataset, selected) {\n elementarr.forEach(function(entry) {\n //console.log(entry)\n dropdownelement = document.getElementById(entry);\n dropdownelement.innerHTML = \"\";\n Object.keys(dataset).forEach(function(key) {\n //debug\n //console.log(key, countries[key].Name);\n //console.log(key)\n //console.log(countries[key].Name)\n //create an options\n newOption = document.createElement(\"option\");\n //add the name \n newOption.text = dataset[key].Name;\n //ad the value\n newOption.value = dataset[key].Code;\n //check if the code matches the selected and if so set it to the selected item\n if (dataset[key].Code == selected) newOption.selected = true;\n //add the element\n dropdownelement.appendChild(newOption);\n });\n });\n }", "function populate_dropdown(entries) {\r\n entries = entries.slice(0, _settings.limit);\r\n\r\n var list = $('<ul></ul>').addClass('list-group');\r\n entries.forEach(function(entry) {\r\n list.append($('<li></li>').text(entry).data('id', entry).addClass('list-group-item'));\r\n });\r\n\r\n $dropdown.html(list).show(_settings.fade_time, function() {\r\n // Reset dropdown selected index\r\n $dropdown.data('selected_index', 0);\r\n var options = $dropdown.find('li');\r\n options.removeAttr('selected');\r\n options.eq(0).attr('selected', 'selected');\r\n });\r\n }", "function baseLocation_reg(listOfDistrict) {\n\t $(\"#basloc_id_reg\").empty();\n loadingBaseLocationMaster(listOfDistrict);\n var selectfirst = \"<option value='0'>Select BaseLocation</option>\";\n $('#basloc_id_reg').append(selectfirst);\n $.each(baselocations, function (i, resData) {\n var baselocation = \"<option value=\" + resData.baselocationID + \">\" + resData.baselocationName + \"</option>\";\n $(baselocation).appendTo('#basloc_id_reg');\n });\n $('#basloc_id_reg').trigger(\"chosen:updated\");\n $(\"#basloc_id_reg\").chosen();\n\n}", "function optionArrays(arr, eachId){\n arr.forEach(eachItem => {\n //console.log(eachId, eachItem.name);\n // eachItem.name.split(' ')[0] --> split by space between words, and take the first word.\n // populate inside the <selec> --> the options inside\n // we use += to add inside <select> the options <option> , not only equals to replace, but + to add it\n eachId.innerHTML += `<option value=\"${eachItem.name}\">${eachItem.name}</option>`\n //console.log(content);\n });\n }", "function gender_load(){\n var genders = [{value: \"gender\", text: \"Gender\"},\n {value: \"Female\", text: \"Female\"},\n {value: \"Male\", text: \"Male\"}]\n \n var elm = document.getElementById('gender'); // get the select\n for(i=0; i< genders.length; i++){ \n var option = document.createElement('option'); // create the option element\n option.value = genders[i].value; // set the value property\n option.appendChild(document.createTextNode(genders[i].text)); // set the textContent in a safe way.\n if(elm != null){\n elm.append(option);\n } \n } \n }", "function populateForm() {\n const selectElement = document.getElementById('items');\n for (let i in Product.allProducts) {\n let option = document.createElement('option');\n option.textContent = Product.allProducts[i].name;\n option.id = i; \n selectElement.appendChild(option);\n } \n}", "function selectBookOptions() {\n display()\n result = \"\";\n AvailableBooks.forEach(element => {\n result += `\n <option class=\"btnSelectBy\" value=\"${element.id}\">${element.name}</option>`\n });\n avalabalLiterature.innerHTML = result;\n}", "function init() {\n // Use D3 to select the dropdown menu\n \n var dropdownMenu = d3.select(\"#selDataset\");\n\n // Use d3 to get the data from URL.\n d3.json(url).then (function (data){\n console.log(data);\n\n // Create a variable for Name which has subject ID\n var sampleData = data.names;\n console.log(sampleData);\n \n // Append to the dropdown menu using for loop\n for (var i=0; i < 156; i++) {\n toption = dropdownMenu.append(\"option\");\n toption.text(sampleData[i])\n toption.property(\"value\", sampleData[i]);\n };\n \n });\n}", "function filterSamples(i) {\n\n // return the id that is equal to the dropdown value option\n return i.id == dName\n }", "function init() {\n var selector = d3.select(\"#selDataset\");\n d3.json(\"samples.json\").then((data) => {\n var Samp_ID = data.names;\n Samp_ID.forEach((sample) => {\n selector.append(\"option\").text(sample).property(\"value\");\n });\n\n var original = Samp_ID[0];\n charts(original);\n metadata(original);\n \n });\n}", "function populate_select(select, values)\r\n{\r\n\tvar x;\r\n\tfor(x = 0; x < values.length; x++)\r\n\t{\r\n\t\tvar choice = document.createElement('option');\r\n\t\tchoice.value = 'option1';\r\n\t\tchoice.appendChild(document.createTextNode(values[x]));\r\n\t\tselect.appendChild(choice);\r\n\t}\r\n}", "function init() {\n \n var selector = d3.select(\"#selDataset\");\n d3.json(\"samples.json\").then(function(data){\n var IDNames = data.names;\n IDNames.forEach(function(userchoice){\n selector\n .append(\"option\")\n .text(userchoice)\n .property(\"value\", userchoice);\n });\n var beginning = IDNames[0];\n ChartInfo(beginning);\n AllData(beginning);\n });\n }", "function init() {\n var dropDownMenu = d3.select(\"#selDataset\");\n\n d3.json(\"samples.json\").then((data) => {\n \n var idNames = data.names;\n idNames.forEach((sample) => {\n dropDownMenu\n .append(\"option\")\n .text(sample)\n .property(\"value\", sample); \n });\n\n\n const firstName = idNames[0];\n horizontalBarChart(firstName);\n bubbleChart(firstName);\n getMetadata(firstName);\n });\n}", "function populateScores(dropdowndata, id) {\n\tvar displayDrop = \"\";\n\tfor (i = 0; i < dropdowndata.length; i++) {\n\t\tdisplayDrop += \"<option>\" + dropdowndata[i] + \"</option>\";\n\t}\n\tdocument.getElementById(id).innerHTML = displayDrop;\n}", "function init(){\n var dropDown = d3.select(\"#selDataset\");\n d3.json(\"data/samples.json\").then(data =>{\n var names = data.names;\n // console.log(names)\n names.forEach(sample => {\n dropDown.append(\"option\")\n .text(sample)\n .property(\"value\",sample);\n });\n var firstSample = names[0];\n console.log(firstSample);\n buildTable(firstSample);\n buildCharts(firstSample);\n });\n}", "function populateSelections(vals){\n let i = 0;\n let opt;\n let txt;\n for(let v in vals){\n opt = document.createElement(\"option\");\n txt = document.createTextNode(v);\n opt.appendChild(txt);\n opt.setAttribute(\"value\", v);\n document.getElementById('sourceCurrencySrc').appendChild(opt);\n\n opt = document.createElement(\"option\");\n txt = document.createTextNode(v);\n opt.appendChild(txt);\n opt.setAttribute(\"value\", v);\n document.getElementById('sourceCurrencyTar').appendChild(opt);\n\n opt = document.createElement(\"option\");\n txt = document.createTextNode(v);\n opt.appendChild(txt);\n opt.setAttribute(\"value\", i);\n document.getElementById('targetCurrencySrc').appendChild(opt);\n\n opt = document.createElement(\"option\");\n txt = document.createTextNode(v);\n opt.appendChild(txt);\n opt.setAttribute(\"value\", i);\n document.getElementById('targetCurrencyTar').appendChild(opt);\n i++;\n }\n }", "function populatetireDimensions() {\n let manufactureDropdown = document.getElementsByName('tireManufacture')[0];\n let modelDropdown = document.getElementsByName('tireModel')[0];\n let dimensionsDropdown = document.getElementsByName('tireDimensions')[0];\n\n modelDropdown.addEventListener('click', function() {\n\n // Empty dropdown\n dimensionsDropdown.innerHTML = '';\n\n jsonRequest('jr_tires.php', function(payload) {\n let selectedModel = modelDropdown.options[modelDropdown.selectedIndex];\n let selectedManufacture = manufactureDropdown.options[manufactureDropdown.selectedIndex];\n\n let dimensions = [];\n\n for (var i = 0; i < payload.length; i++) {\n if(selectedModel.value === payload[i].tireModel && selectedManufacture.value === payload[i].tireManufacture) {\n dimensions.push(payload[i].tireDimensions);\n }\n }\n\n // Get unique dimensions\n dimensions = Array.from(new Set(dimensions));\n console.log(dimensions);\n\n for (var j = 0; j < dimensions.length; j++) {\n let option = document.createElement('option');\n option.innerHTML = dimensions[j];\n option.value = dimensions[j];\n dimensionsDropdown.appendChild(option);\n }\n });\n });\n}", "function loadAssetDropDownFromArray() {\n assetDropDown = $('#asset-id-dropdown');\n assetDropDown.empty();\n assetDropDown.append('<option value=\"\" disabled selected hidden>Please Select</option>');\n for (var i = 0,len=assetList.length;i<len;i++) {\n currentAsset = assetList[i];\n var newOptionItem = $('<option>');\n // console.log(newOptionItem);\n newOptionItem.attr('data-index',i);\n newOptionItem.val(currentAsset.AssetID);\n newOptionItem.text(currentAsset.AssetID+' '+currentAsset.ItemDescription[0]);\n assetDropDown.append(newOptionItem);\n }\n} // function loadAssetDropDownFromArray", "function populate_year_dropdown_by_query()\n{\n let select = document.getElementById(\"Select Academic Year\");\n let arr= Get(\"api/buttonsdynamically/get/years\");\n if(select===null)\n alert(\"empty object retrieved from DOM parse\");\n if( select.length>1) {\n //alert(\"year already exist in under the domain button, no need to again add them\");\n return \"\";\n }\n\n for (let i = 0; i < arr.length; i++) {\n let option = document.createElement(\"OPTION\"), txt = document.createTextNode(arr[i]);\n option.appendChild(txt);\n option.setAttribute(\"value\", arr[i]);\n select.insertBefore(option, select.lastChild);\n }\n}", "function fetchGenreList() {\n // const params=new URLSearchParams()\n // params.set('userID',)\n fetch('./api/genre')\n .then(response => response.json())\n .then(genres => {\n populateDropdown(selection1, genres);\n populateDropdown(selection2, genres);\n populateDropdown(selection3, genres);\n })\n}", "function populateDropdown(id, data) {\n let select = document.getElementById(id)\n data.forEach(alt => {\n if (alt.commits.items.length == 0) return\n var opt = document.createElement(\"option\")\n opt.appendChild(document.createTextNode(alt.name))\n opt.value = alt.commits.items[0].referencedObject\n select.appendChild(opt)\n })\n isDropdownLoaded = true\n}", "function populateGroupDropDown(userGroupMap) {\r\n\tdocument.getElementById(\"userGroupInptId\").innerHTML = \"\";\t\r\n\tvar userGroupSelect = document.getElementById(\"userGroupInptId\");\r\n\tvar defaultOpn = document.createElement(\"option\");\r\n\tdefaultOpn.text = \"None\";\r\n\tdefaultOpn.value = \"2!None\";\r\n\tdefaultOpn.className = \"form-control-general\";\r\n\tuserGroupSelect.add(defaultOpn, null);\r\n\t\r\n\t//var userGroupSelect = document.getElementById(\"userGroupInptId\");\r\n\tfor (var key in userGroupMap) {\t\t\t\t\r\n\t\tvar option = document.createElement(\"option\");\r\n\t\toption.text = userGroupMap[key];\r\n\t option.value = key+\"!\"+userGroupMap[key];\r\n\t option.className = \"form-control-general\";\r\n\t try {\r\n\t \tuserGroupSelect.add(option, null); //Standard \r\n\t }catch(error) {\r\n\t \t//regionSelect.add(option); // IE only\r\n\t }\r\n\t}\r\n}", "function populateCountrySelect() {\n\n let countriesInfo = countriesInfoFunctions.returnCountriesInfo();\n\n let features = countriesInfo['countryBorders']['features'];\n\n // Setup alphabetized countries array\n const countryNames = [];\n\n features.forEach(feature => {\n\n const countryName = feature['properties']['name'];\n\n countryNames.push(countryName);\n\n });\n\n countryNames.sort();\n\n // populate coutriesList string with all countries from countryBorders as options, then update datalist once with countriesList string \n let countriesList = \"\";\n\n const homeCountryName = countriesInfo['home']['countryBorder']['properties']['name'];\n\n countryNames.forEach(countryName => {\n\n if (countryName == homeCountryName) {\n\n countriesList += `<option value=\"${countryName}\" selected>${countryName}</option>`; \n\n } else {\n\n countriesList += `<option value=\"${countryName}\">${countryName}</option>`;\n\n }\n\n });\n\n $countriesSelect = $('#countries');\n $countriesSelect.html(countriesList);\n\n}", "function setNodeIdList(selectList, params, nodes){\n if(params.style !== undefined){\n selectList.setAttribute('style', params.style);\n }\n selectList.style.display = 'inline';\n \n option = document.createElement(\"option\");\n option.value = \"\";\n if(params.main === undefined){\n option.text = \"Select by id\";\n } else {\n option.text = params.main;\n }\n \n selectList.appendChild(option);\n \n // have to set for all nodes ?\n if(params.values === undefined){\n var info_node_list = nodes.get({\n fields: ['id', 'label'],\n returnType :'Array'\n });\n for (var i = 0; i < info_node_list.length; i++) {\n option = document.createElement(\"option\");\n option.value = info_node_list[i].id;\n if(info_node_list[i].label && params.useLabels){\n option.text = info_node_list[i].label;\n }else{\n option.text = info_node_list[i].id;\n }\n selectList.appendChild(option);\n }\n } else {\n var tmp_node;\n for(var tmp_id = 0 ; tmp_id < params.values.length; tmp_id++){\n tmp_node = nodes.get({\n fields: ['id', 'label'],\n filter: function (item) {\n return (item.id === params.values[tmp_id]) ;\n },\n returnType :'Array'\n });\n if(tmp_node !== undefined){\n option = document.createElement(\"option\");\n option.value = tmp_node[0].id;\n if(tmp_node[0].label && params.useLabels){\n option.text = tmp_node[0].label;\n }else{\n option.text = tmp_node[0].id;\n }\n selectList.appendChild(option);\n }\n }\n }\n}", "function dropdownData(){\n // Select the Dropdown element\n var dropdown = d3.select(\"#selDataset\");\n\n // Initialize empty array with PatientID\n //var dataID = [];\n\n // Extract dropdown data from the Samples.json Name field\n d3.json(\"data/samples.json\").then((data) => {\n var dataName = data.names;\n \n //console.log(dataName)\n\n dataName.forEach(patientID =>\n dropdown.append('option').text(`${patientID}`).property(\"value\",patientID))\n \n \n //optionChanged(dataID)\n })\n}", "function populateDropdownControls(target, values) {\n const selectCtrl = document.getElementById(target)\n selectCtrl.innerHTML = ''\n for (let value in values) {\n for (let opt of selectCtrl.options) {\n if (opt.value === values[value]) {\n selectCtrl.removeChild(opt)\n }\n }\n var opt = document.createElement('option')\n opt.value = opt.text = values[value]\n selectCtrl.appendChild(opt)\n }\n}", "function init(){\r\n \r\n buildplot(940);\r\n var testId = d3.select(\"#selDataset\");\r\n d3.json(\"js/samples.json\").then((importedData)=>{\r\n console.log(importedData);\r\n var data = importedData;\r\n var names = data.names;\r\n console.log(names);\r\n names.forEach(name=>{\r\n testId.append(\"option\").property(\"value\",name).text(name);\r\n \r\n })\r\n \r\n }); \r\n \r\n }", "function LoadDropdown(result, id) {\n $(id).get(0).options.length = 0;\n if (id.attr('id') == 'ddlItemHead') {\n itmList = [];\n itmList = result;\n }\n var content = '<option value=\"-1\">-- Select --</option>';\n if (result != null) {\n $.each(result, function (i, obj) {\n content += '<option value=\"' + obj.Value + '\" >' + obj.DisplayName + '</option>';\n });\n }\n $(id).append(content);\n\n if (id.attr('class') == 'span12 SupplierID') {\n if (manId != '0') {\n $(id).val(manId).trigger('change');\n }\n }\n $(id).select2();\n}", "function setSelections(json, target, value){\n\t var len = json.length;\n\t if (len == 0){\n\t \t$('#' + target).hide();\n\t } else {\n\t\t$('#' + target).show();\n\t }\n\t $('#' + target).empty();//.append('<option value=\"-1\">-</option>');\n\t for(var j = 0; j < len; j++) {\n\t var op = $('<option/>');\n\t op.attr('value', json[j].id); // fixed typo \n\t if (value != undefined && value == json[j].id){\n\t op.attr('selected', 'selected');\n\t }\n\t op.append(json[j].name);\n\t $('#' + target).append(op);\n\t }\n\t}", "function initialize() {\n var dropdown = d3.select(\"#selDataset\"); \n d3.json(\"samples.json\").then((data) => {\n var sampleList = data.names; \n sampleList.forEach((sample) => {\n dropdown.append(\"option\").text(sample).property(\"value\", sample); \n \n });\n //capture sample metadata from the list\n var firstSample = sampleList[0];\n chartBuilder(firstSample); \n metadataBuilder(firstSample);\n \n }); \n }", "function populateDropDown(dropDownName, arrOfVals){\n arrOfVals.forEach(function(item) {\n $(dropDownName).append(\n \"<option value='\" + item + \"'>\" + item + \"</option>\"\n );\n });\n }", "function setUpDropdownMenu() {\n\tvar dropdown = document.getElementById(\"dictionary-title\");\n\n\tfor (var columnKey in Object.keys(dictionaries_in_dropdown_data)) {\n\t\t// Get column data from large column object\n\t\tvar column_data = dictionaries_in_dropdown_data[columnKey];\n\n\t\t// Create the option element for the dropdown\n\t\tvar option = document.createElement('option');\n\t\toption.text = column_data[\"title\"]; // set the text to be the title\n\t\toption.value = columnKey; \t\t\t// set the value to be the index\n\t\tdropdown.appendChild(option);\n\t}\n}", "function create_gun_selection(){\n var select_gun = $('#select_gun');\n for (var i = 0; i < DEFAULT_GUNS.length; i++) {\n var el = document.createElement('option');\n el.text = DEFAULT_GUNS[i].name;\n el.value = JSON.stringify(DEFAULT_GUNS[i]);\n select_gun.append(el);\n }\n}", "function getTests() {\n const lab = $('#lab').val()\n $.post('/get-lab', { lab: lab })\n .done(function(data) {\n $(\"#myTests option[value]\").remove();\n $.each(data, function(index, value){\n $(\"#myTests\").append($(\"<option>\",{\n value: value.id,\n text: value.tests\n }))\n })\n })\n}", "function createDropdownCountries() {\n let dropdown = document.getElementById(\"dropdownCountries\");\n dropdown.length = 0;\n let option;\n\n // Set default option to global stats\n let defaultOption = document.createElement(\"option\");\n defaultOption.text = \"Global\";\n defaultOption.value = 0;\n dropdown.add(defaultOption);\n $(\".selectpicker\").selectpicker(\"refresh\");\n dropdown.selectedIndex = 0;\n updateUI(defaultOption.value);\n\n // Populate the dropdown\n countryList.forEach((entry) => {\n option = document.createElement(\"option\");\n option.text = entry.country;\n option.value = entry.countryInfo._id;\n dropdown.add(option);\n });\n $(\".selectpicker\").selectpicker(\"refresh\");\n }", "function populateSelect(array, elementId, name){\n var select = $('#'+elementId+' select[name='+name+']');\n var options = '';\n for(var i=0; i<array.length; i++){\n options += '<option value=\"'+array[i].id+'\">'+array[i].name+'</option>';\n }\n\n // first empty select, then populate it with the options\n $(select).html('');\n $(select).append(options);\n}", "function CreateStudentOptions(selectid) {\r\n let select = document.getElementById(selectid);\r\n for (let i = 0; i < students.length; i++) {\r\n let opt = document.createElement(\"option\");\r\n opt.innerHTML = students[i][\"No\"] + \". \" + students[i][\"FirstName\"] + \" \" + students[i][\"LastName\"];\r\n select.appendChild(opt);\r\n }\r\n}", "function populateDataSelect () {\n const options = dataVariables\n\n for (let i = 0; i < options.length; i++) {\n let opt = options[i].table + '/' + options[i].column\n let el = document.createElement('option')\n el.textContent = opt\n el.value = opt\n dataSelect.appendChild(el)\n }\n}" ]
[ "0.72692955", "0.66110945", "0.6570161", "0.6537719", "0.6521654", "0.64871025", "0.6406948", "0.6396835", "0.6368716", "0.6303995", "0.6301479", "0.6278536", "0.6274078", "0.62712055", "0.6250328", "0.62456286", "0.6237694", "0.6230388", "0.6219206", "0.62164885", "0.620469", "0.6203414", "0.6174703", "0.61691093", "0.6161452", "0.6157632", "0.6153328", "0.61523867", "0.61149436", "0.6113565", "0.61094654", "0.61020964", "0.60875845", "0.6085999", "0.6067461", "0.6061908", "0.6057633", "0.60544044", "0.6045879", "0.6045254", "0.60421425", "0.6038263", "0.60259247", "0.6012534", "0.6006514", "0.6004729", "0.6004647", "0.5998633", "0.5991687", "0.59915555", "0.59629405", "0.595714", "0.59554714", "0.59482586", "0.5946014", "0.59385324", "0.5937999", "0.59375405", "0.5934796", "0.5932899", "0.593157", "0.5927893", "0.5926536", "0.5926105", "0.59164107", "0.5902446", "0.59012055", "0.58981", "0.5886151", "0.58852184", "0.58713347", "0.58635676", "0.5861227", "0.5855266", "0.58531535", "0.58497053", "0.58473825", "0.584595", "0.5838658", "0.58325803", "0.58291763", "0.5825141", "0.5824927", "0.58202684", "0.5819588", "0.58169097", "0.58124167", "0.580649", "0.5801655", "0.58010024", "0.57932276", "0.5788801", "0.5788462", "0.57872766", "0.5786311", "0.5770126", "0.5769996", "0.5768932", "0.5767434", "0.5762251" ]
0.59408414
55
set a function for working with demgraphic info panel
function populatedemographics(id) { //filter data with id, select the demographic info with appropriate id var filterMetaData= jsonData.metadata.filter(meta => meta.id.toString() === id)[0]; // select the panel to put data var demographicInfo = d3.select("#sample-metadata"); // empty the demographic info panel each time before getting new id info demographicInfo.html(""); // grab the necessary demographic data data for the id and append the info to the panel Object.entries(filterMetaData).forEach((key) => { demographicInfo.append("h5").text(key[0].toUpperCase() + ": " + key[1] + "\n"); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function disp_info(d) {\n //console.log(d);\n materialInfo.html(getMaterialInfo(d))\n .attr(\"class\", \"panel_on\");\n }", "function drawExtraDecalsFn() {\n }", "function drawExtraDecalsFn() {\n }", "function InfoBox() {\n}", "function getPlotFunction() {\n\t// route the data to the appropriate func depending on the current display setting\t\n\tif (c_display_option == \"location\") {\n\t\treturn plotMapMarkerZip;\n\t}\n\telse if (c_display_option == \"total_number\") {\n\t\treturn plotMapCircleZip;\n\t}\n\telse if (c_display_option == \"weight_ratio\") {\n\t\treturn plotMapWeightZip;\n\t}\n\telse if (c_display_option == \"heatmap\") {\n\t\treturn null;\n\t}\n\telse { \n\t\talert(\"Something went wrong!\");\n\t\treturn null;\n\t}\n}", "function PanelHelper() {\n\t}", "static displayInfoPanel(panel, data) {\n // Updatte and display panel\n LibrariesMap.updatePanel(panel, data);\n panel.style(\"display\", \"block\");\n // Update pie charts\n LibrariesMap.updatePieCharts(panel, data);\n }", "function showDatasetDetailDescription( datasetid , goto_description, select_point, center_point)\n/**\n * Shows Dataset Detail Description and adjusts the scroll so that detail panel is visible\n * @param {[string]} datasetid\n * @param {[bool]} goto_description - scroll to the current description in the right panel if True\n * @param {[bool]} select_point - selects corresponding feature (point) on the map\n * @param {[bool]} center_point - center corresponding feature (point) on the map\n */\n{\n\n // trick to set parameter by default\n if ( goto_description == undefined)\n {\n goto_description = true;\n }\n if ( select_point == undefined)\n {\n select_point = true;\n }\n if ( center_point == undefined)\n {\n center_point = true;\n }\n // collapse other detail panels\n jQuery('#dataset_desc').find('.collapse').each(function() {\n if (jQuery(this).attr('id') != datasetid) {\n jQuery(this).collapse('hide');\n }\n });\n // load details panel\n callDatasetDetailDescription(datasetid);\n // scroll up to this panel\n if (goto_description) {\n jQuery(\"#\"+datasetid).on(\"shown.bs.collapse\", function() {\n let topPos = jQuery('#dataset_desc').scrollTop() + jQuery(\"#\"+datasetid).position().top;\n jQuery('#dataset_desc').animate({scrollTop:topPos}, 500);\n });\n }\n if (select_point) {\n selectFeatureOnMap(datasetid);\n }\n if (center_point) {\n centerFeatureOnMap(datasetid);\n }\n}", "function SetInfoZoomHandler()\n{ \n var media = GetState(\"media\");\n var type = GetState(\"type\");\n var id = $(this).attr(\"class\").match(/\\d+(_\\d+)?/g);\n \n ShowInfoZoomMedia(media, type, id);\n}", "function ZoomableView() { }", "function add_man() {\n\t\t\t\t$(\"#p4_panel\").append(\"<h3><u> Manual : </u></h3><h5>Functionalities :</h5>\" +\n\t\t\t\t\"<ul><li>Grid Size</li><li>Number of point in grid</li><li>Players Color</li></ul>\" +\n\t\t\t\t\"\");\n\t\t\t}", "function showInfo(layer) {\n if (layer.id == \"info_pipe\"){\n //For default layer pipeline\n document.getElementById(\"inf_title\").innerHTML = \"tuberia\";\n document.getElementById(\"inf_id\").innerHTML = \"Layer ID: tfm:tuebria\";\n document.getElementById(\"inf_abs\").innerHTML = \"Abstract: Red de aguas\";\n document.getElementById(\"inf_cp\").innerHTML = \"Contact Person: Claudius Ptolomaeus\";\n document.getElementById(\"inf_org\").innerHTML = \"Organization: The ancient geographes INC\";\n document.getElementById(\"inf_email\").innerHTML = \"Email: [email protected]\";\n document.getElementById(\"inf_phone\").innerHTML = \"Telephone: \";\n document.getElementById(\"inf_ac\").innerHTML = \"Access Constraints: NONE\";\n document.getElementById(\"inf_wms\").innerHTML = \"WMS: http://localhost:8080/geoserver/wms?service=wms&version=1.3.0&request=GetCapabilities\";\n document.getElementById(\"inf_legend\").innerHTML = \"Legend:<br><img src='http://localhost:8080/geoserver/tfm/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&WIDTH=20&HEIGHT=20&STRICT=false&style=Diametros'>\";\n return;\n }\n if (layer.id == \"info_comm\"){\n //For default layer comments\n document.getElementById(\"inf_title\").innerHTML = \"comments\";\n document.getElementById(\"inf_id\").innerHTML = \"Layer ID: tfm:comments\";\n document.getElementById(\"inf_abs\").innerHTML = \"Abstract: Comments of the interest points\";\n document.getElementById(\"inf_cp\").innerHTML = \"Contact Person: Claudius Ptolomaeus\";\n document.getElementById(\"inf_org\").innerHTML = \"Organization: The ancient geographes INC\";\n document.getElementById(\"inf_email\").innerHTML = \"Email: [email protected]\";\n document.getElementById(\"inf_phone\").innerHTML = \"Telephone: \";\n document.getElementById(\"inf_ac\").innerHTML = \"Access Constraints: NONE\";\n document.getElementById(\"inf_wms\").innerHTML = \"WMS: http://localhost:8080/geoserver/wms?service=wms&version=1.3.0&request=GetCapabilities\";\n document.getElementById(\"inf_legend\").innerHTML = \"Legend:<br><img src='http://localhost:8080/geoserver/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&WIDTH=20&HEIGHT=20&LAYER=tfm:comments'> Comment\";\n return;\n }\n //The position in the array info, is the same of the layer id,\n //because is ordered it is only necessary fill the data\n document.getElementById(\"inf_title\").innerHTML = info[layer.id][0];\n document.getElementById(\"inf_id\").innerHTML = \"Layer ID: \"+info[layer.id][1];\n document.getElementById(\"inf_abs\").innerHTML = \"Abstract: \"+info[layer.id][2];\n document.getElementById(\"inf_cp\").innerHTML = \"Contact Person: \"+info[layer.id][3];\n document.getElementById(\"inf_org\").innerHTML = \"Organization: \"+info[layer.id][4];\n document.getElementById(\"inf_email\").innerHTML = \"Email: \"+info[layer.id][5];\n document.getElementById(\"inf_phone\").innerHTML = \"Telephone: \"+info[layer.id][6];\n document.getElementById(\"inf_ac\").innerHTML = \"Access Constraints: \"+info[layer.id][7];\n document.getElementById(\"inf_wms\").innerHTML = \"WMS: \"+info[layer.id][8];\n document.getElementById(\"inf_legend\").innerHTML = \"Legend:<br><img style='max-width:100%' src='\"+info[layer.id][9]+\"'>\";\n}", "addHighlighTooltip () {\n }", "function formSkyline() {\n\n}", "function fm(){}", "function Details() {\r\n}", "plot() {\n return \"Cute alien takes over the earth\";\n }", "function optionChanged(id) {\n display_data(id);\n dyna_demos(id);\n}", "function gd(){}", "function createNewFunctionView() {\n // json set\n var dataSet = pluto.loadedDataSet[pluto.selectedPlutoName];\n \n // gets the pluto\n var layer = pluto.loadedPluto[pluto.selectedPlutoName];\n // create layer.\n layer.loadFillLayer(thr, pluto.selectedFunctionName, dataSet);\n }", "function plot() {\n\n}", "function optionChanged (sample) {\ndemographic_panel(sample);\ncreate_charts(sample);\n}", "function show_additional_panel(tool){\n var new_panel = '';\n switch(tool){\n case 'polyline':\n case 'line':\n case 'path':\n case 'multipath':\n new_panel = 'open_shape_style';\n break;\n case 'polygon':\n case 'rect':\n case 'circle':\n new_panel = 'closed_shape_style';\n break;\n case 'image':\n new_panel = 'image_style';\n break;\n }\n if(g['additional_panel'] != new_panel){\n if(g['additional_panel'] != '')\n // Hide old panel\n getById(g['additional_panel']).className = 'hidden';\n if(new_panel != ''){\n var panel = getById(new_panel);\n // Show the new panel\n panel.className = 'new_panel';\n }\n // Save changes\n g['additional_panel'] = new_panel;\n }\n}", "function showDatosFacturacion() {\n fillSelect();\n showInfoClient();\n}", "function salesHeatmap() {}", "function D(e,t){switch(e){case E$3.LINE:return n$e.line;case E$3.TEXT:return n$e.text;case E$3.LABEL:return n$e.label;case E$3.FILL:return t===S.DOT_DENSITY?n$e.dotDensity:n$e.fill;case E$3.MARKER:switch(t){case S.HEATMAP:return n$e.heatmap;case S.PIE_CHART:return n$e.pieChart;default:return n$e.marker}}}", "function InfoBarWindow(){}", "function mydoc_on(gal_type)\n{\n if(document.getElementById('map').style.display=='none')\n hide('uc_image');\n else\n hide('map');\n\n hide('chart_gallery_id');\n hide('gallery_id');\n hide('weather_gallery_id');\n\n if(gal_type=='chart')\n show('chart_gallery_id');\n if(gal_type=='place')\n show('gallery_id');\n if(gal_type=='weather')\n show('weather_gallery_id');\n\n //for hide show details window\n hide('more_info');\n\n}", "function ShowAbstract(key, px, py) {\n\tvar ol = \"#\".concat(key).concat(\"overlay\");\n\tvar dl = \"#\".concat(key).concat(\"dialog\");\n\t$(ol).show();\n\tif((px != 0) && (py !=0 )) {\n\t\t$(dl).css({left:px, top:py }).fadeIn(300);\n\t}else {\n\t\t$(dl).fadeIn(300);\n\t}\n\t\n}", "function getDesempenho(){\n init(1200, 500,\"#infos2\");\n executa(dados_atuais, 0,10,4);\n showLegendasRepetencia(false);\n showLegendasDesempenho(true);\n showLegendasAgrupamento(false);\n}", "function CustomInfosetExtensionHandler() {\n\n\t$.level = 1; // Debugging level\n\t/**\n\t The context in which this sample can run.\n\t @type String\n\t*/\n\tthis.requiredContext = \"\\tNeed to be running in context of Bridge\\n\";\n\n\t/**\n\t The image for the button icon\n @type String\n\t*/\n\tthis.buttonIcon = new File($.fileName).parent.fsName + \"/resources/editIcon.png\";\n\t\t\n}", "function TextualZoomControl() {\n }", "function sel_panel(id) {}", "function showDetails(d) {\r\n\t// Get the ID of the feature.\r\n\t// var id = getIdOfFeature(f);\r\n\t// Use the ID to get the data entry.\r\n\t// var d = dataById[id];\r\n\t// Render the Mustache template with the data object and put the\r\n\t// resulting HTML output in the details container.\r\n\t// var detailsHtml = Mustache.render(template, d);\r\n\t// Hide the initial container.\r\n\t// d3.select('#initial').classed(\"hidden\", true);\r\n\t// Put the HTML output in the details container and show (unhide) it.\r\n\t// d3.select('#details').html(detailsHtml);\r\n\t// d3.select('#details').classed(\"hidden\", false);\r\n}", "function regTooltipWhite(id) {\n\n $(id).tooltipster('show', function () {\n\n $(document).on('click', function () {\n $(id).tooltipster('hide', function () {\n });\n });\n });\n}", "_initDisplay(value) {}", "function TcPermDetailsPanel() {}", "function callMarker() {\n displayInfo(markerNum); \n}", "createInfoPanel() {\n var panel = d3.select(\"#panel\");\n\n // Close panel button\n panel.append(\"button\")\n .text(\"X\")\n .on(\"click\", function () {\n panel.style(\"display\", \"none\");\n LibrariesMap.libCirclesGroup.selectAll(\"circle\").classed(\"circle-selected\", false);\n });\n\n // Create the pie charts svg\n this.pieSvg = panel.append(\"svg\")\n .attr(\"id\", \"pie-svg\")\n .attr(\"width\", \"100%\")\n .attr(\"height\", \"50%\")\n\n // Language Pie chart\n this.pieSvg.append(\"g\")\n .attr(\"id\", \"pieLg-group\")\n .attr(\"transform\", \"translate(\" + pieChartDim.left + \",\" + pieChartDim.top + \")\");\n // Public Pie chart\n this.pieSvg.append(\"g\")\n .attr(\"id\", \"piePub-group\")\n .attr(\"transform\", \"translate(\" + pieChartDim.left1 + \",\" + pieChartDim.top + \")\");\n // Format Pie chart\n this.pieSvg.append(\"g\")\n .attr(\"id\", \"pieForm-group\")\n .attr(\"transform\", \"translate(\" + pieChartDim.left2 + \",\" + pieChartDim.top + \")\");\n \n // Legend\n this.createLegend(8, LibrariesMap.pieLgColorScale, pieLgInfo.legendTexts);\n this.createLegend(pieChartDim.left1*0.75, LibrariesMap.piePubColorScale, piePubInfo.legendTexts);\n this.createLegend(pieChartDim.left2*0.8, LibrariesMap.pieFormColorScale, pieFormInfo.legendTexts);\n\n return panel;\n }", "function changeDisplay(){\n}", "function fuctionPanier(){\n\n}", "function tema4(){\n\n}", "function showPosition() {\n}", "function setInfobox(props){\r\n \r\n var infoValue, i = infoValue = 0;\r\n do {\r\n var infoValue = parseFloat(props[expressed]).toFixed(i);\r\n i++;\r\n }\r\n while (infoValue <= 0);\r\n \r\n if (isNaN(infoValue)) {\r\n var infoValue, infoAcres = infoValue = 0;\r\n } else {\r\n var infoValue = comma(parseFloat(props[expressed]).toFixed(i));\r\n var infoAcres = comma(props[displayed]);\r\n }\r\n\r\n var infoDesc2 = \"Acreage \" + drop2Choice;\r\n var infoDesc1 = \"Total Acreage of \" + drop1Choice;\r\n \r\n //label content\r\n var infoAttribute1 = '<h2><span id=\"inf\">' + infoDesc1 + ': </span> ' + infoAcres + '</h2>';\r\n var infoAttribute2 = '<h2><span id=\"inf\">' + infoDesc2 + ': </span> ' + infoValue + '</h2>';\r\n var stateName = '<h2>' + props.geo_name + '</h2>';\r\n \r\n //create info label div\r\n var infolabel = d3.select(\"body\")\r\n .append(\"div\")\r\n .attr(\"class\", \"infolabel\")\r\n .attr(\"id\", props.geo_id + \"_label\")\r\n .html(stateName);\r\n\r\n var stateName = infolabel.append(\"div\")\r\n .attr(\"class\", \"infogoo\")\r\n .html(infoAttribute1);\r\n var stateName = infolabel.append(\"div\")\r\n .attr(\"class\", \"infogoo\")\r\n .html(infoAttribute2);\r\n }", "function functionDelegator() {\n colorCalc();\n showColors();\n displayHex();\n displayRGB();\n displayHSL();\n}", "function SVGDeviationChart() {\r\n }", "function getgeoinfoFoss (event){\n\t\t //console.log(\"getgeoinfoUSGS\");\n\t\t// console.log(event.graphic.attributes);\n\t\t var attr = event.graphic.attributes;\n\t\t var lon=event.mapPoint.x;\n\t\t var lat=event.mapPoint.y;\t\t\n\t\t map.infoWindow.setTitle(\"Fossil Information \");\n\t\t map.infoWindow.setContent( \"<b>Formation:</b>\"+attr.Formation+\"<br/><b>Collection Name:</b>\"+attr.nam+\"<br/><b>Early interval:</b>\"+attr.oei);\n\n\t\t map.infoWindow.show(event.mapPoint, map.getInfoWindowAnchor(event.screenPoint));\n }", "function optionChanged(id) {\n doplot(id);\n getInfo(id);\n}", "function viewMapInfo(mapId) {\r\n\tif (mapId != \"-1\"){\r\n\t\tmapDwrAction.getMap(mapId, \r\n \t\tfunction(sysMap){\r\n \t\t\tif (sysMap != null) {\r\n \t\t\t\t$(\"mapInfoImg\").src=\"../images/icons/info-02.gif\";\r\n \t\t\t\t$(\"mapInfoTable\").style.display=\"\";\r\n \t\t\t\t$(\"sysCatalogInfo\").style.display=\"none\";\r\n \t\t\t\t$(\"onMapDiv\").style.display=\"none\";\r\n\t \t\t\tvar mapTitle = $(\"mapTitleDiv\");\r\n\t \t\t\tvar mapSign = $(\"mapSignDiv\");\r\n\t \t\t\tvar mapDescn = $(\"mapDescnDiv\");\r\n\t \t\t\tmapTitle.innerHTML=\"<font color='red'>\" + sysMap.mapTitle + \"</font>\";\r\n\t \t\t\tmapSign.innerHTML=sysMap.mapSign;\r\n\t \t\t\tmapDescn.innerHTML=sysMap.mapDescn;\r\n \t\t\t} else {\r\n \t\t\t\tviewSimpleDlg(noMap);\r\n \t\t\t\tsetMapId_NodeId(\"\", \"\");\r\n \t\t\t\t$(\"mapInfoImg\").src=\"../images/icons/error.gif\";\r\n \t\t\t\t$(\"onMapDiv\").style.display=\"\";\r\n \t\t\t\t$(\"mapInfoTable\").style.display=\"none\";\r\n \t\t\t\t$(\"sysCatalogInfo\").style.display=\"none\";\r\n \t\t\t}\r\n\t\t\t}\t);\r\n\t} else {\r\n\t\t\t$(\"mapInfoImg\").src=\"../images/icons/info-02.gif\";\r\n\t\t\t$(\"sysCatalogInfo\").style.display=\"\";\r\n\t\t\t$(\"mapInfoTable\").style.display=\"none\";\r\n\t\t\t$(\"onMapDiv\").style.display=\"none\";\r\n\t\t\t\r\n\t}\r\n}", "function plot() {\n \n }", "function optionChanged(id){\n metadatainfo(id);\n draw(id);\n}", "addLegend () {\n \n }", "function showFeature(feature, evt) {\n roeMapCarbon.graphics.clear(); //Clear graphics on the map\n\n //set graphic symbol\n var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 2), new dojo.Color([255, 255, 255, 0]));\n feature.setSymbol(symbol);\n\n function toTitleCase(str) {\n return str.replace(/\\w\\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });\n }\n\n // Build text and layout for the popup\n var attr = feature.attributes;\n //alert(attr.Biomass_sm.toFixed(3));\n var st = attr.ST_NAME;\n var county = attr.NAME;\n var title = county + \", \" + st;//attr.NAMELSAD + \", \" + toTitleCase(attr.StateName);\n var content = \"\";\n var percentChnge = \"\"; //attr.PerentCh_1 ? parseFloat(attr.PerentCh_1).toFixed(2) + \"%\" : null;\n var perChnge = attr.PercentChg;\n\n if (perChnge === 0) {\n percentChnge = attr.PercentChg + \"%\";\n } else {\n percentChnge = attr.PercentChg ? parseFloat(attr.PercentChg).toFixed(2) + \"%\" : null;\n }\n\n //alert(perChnge + \" \" + percentChnge);\n if (percentChnge != null) {\n if (perChnge === 0) {\n content += \"<div>+\" + percentChnge + \"</div>\";\n } else if (percentChnge.substr(0, 1) != \"-\") {\n content += \"<div>+\" + percentChnge + \"</div>\";\n } else {\n content += \"<div>\" + percentChnge + \"</div>\";\n }\n } else {\n content += \"<div>No forest or no data</div>\";\n }\n\n //Add graphics\n roeMapCarbon.graphics.add(feature);\n //Set title and content for the popup window\n roeMapCarbon.infoWindow.setTitle(title);\n roeMapCarbon.infoWindow.setContent(content);\n\n (evt) ? roeMapCarbon.infoWindow.show(evt.screenPoint, roeMapCarbon.getInfoWindowAnchor(evt.screenPoint)) : null;\n roeMapCarbon.infoWindow.resize(300, 120);\n }", "function functionToPanel(panel, func){\n\t\t\tif(Atm.inProcess){\n\t\t\t\tfunctionButton[panel].style.background = functionPanel[func].color;\n\t\t\t\tfunctionButton[panel].innerHTML = functionPanel[func].status;\n\t\t\t\tfunctionButton[panel].onclick = functionPanel[func].func;\n\t\t\t}\n\t\t}", "function FunctionPlotter(options) {\n let axisTickCounts,\n functions,\n gridBoolean,\n group,\n hasTransitioned,\n plotArea,\n plotter,\n range,\n width,\n where,\n x,\n y;\n\n plotter = this;\n\n init(options);\n\n return plotter;\n\n /* INITIALIZE */\n function init(options) {\n let curtain;\n\n _required(options);\n _defaults(options);\n\n\n curtain = addCurtain();\n plotter.scales = defineScales();\n plotter.axisTitles = {};\n group = addGroup();\n plotArea = addPlotArea();\n plotter.layers = addLayers();\n plotter.grid = addGrid();\n plotter.axes = addAxes();\n plotter.lines = addLines(functions);\n plotter.hotspot = addHotspot();\n\n plotter.hasTransitioned = false;\n\n // valueCircle = false;\n\n\n }\n\n /* PRIVATE METHODS */\n function _defaults(options) {\n\n axisTickCounts = options.axisTicks ? options.axisTicks : {\"x\":1,\"y\":1};\n functions = options.functions ? options.functions : [];\n plotter.height = options.height ? options.height : 400;\n plotter.width = options.width ? options.width : 800;\n plotter.domain = options.domain ? options.domain : [0,10];\n plotter.range = options.range ? options.range : [0,10];\n plotter.margins = options.margins ? options.margins : defaultMargins();\n //TODO: THIS IS SLOPPY. GRID SHOULD BE CLEARER\n gridBoolean = options.hideGrid ? false : true;\n x = options.x ? options.x : 0;\n y = options.y ? options.y : 0;\n plotter.coordinates = options.coordinates ? options.coordinates : {\"x\":x,\"y\":y};\n plotter.fontFamily = options.fontFamily ? options.fontFamily : \"\";\n\n }\n\n function _required(options) {\n\n hasTransitioned = false;\n where = options.where;\n\n }\n\n\n /* PRIVATE METHODS */\n function addAxes() {\n let axes;\n\n axes = {};\n\n axes.x = addXAxis();\n axes.y = addYAxis();\n\n return axes;\n }\n\n function addCurtain() {\n let clipPath,\n rect;\n\n clipPath = where\n .select(\"defs\")\n .append(\"clipPath\")\n .attr(\"id\",\"plotterClipPath\");\n\n rect = clipPath\n .append(\"rect\")\n .attr(\"x\",-1)\n .attr(\"y\",-1)\n .attr(\"width\",width - plotter.margins.left - plotter.margins.right + 1)\n .attr(\"height\",plotter.height - plotter.margins.top - plotter.margins.bottom + 1);\n\n return clipPath;\n }\n\n function addGroup() {\n let group;\n\n group = explorableGroup({\"where\":options.where})\n .attr(\"transform\",\"translate(\"+plotter.coordinates.x+\",\"+plotter.coordinates.y+\")\");\n\n return group;\n }\n\n function addGrid() {\n let grid;\n\n if(gridBoolean) {\n grid = new FunctionPlotterGrid({\n \"axisTickCounts\":axisTickCounts,\n \"domain\":plotter.domain,\n \"range\":range,\n \"scales\":plotter.scales,\n \"where\":plotter.layers.grid,\n \"tickEvery\":1\n });\n }\n\n return grid;\n }\n\n function addHotspot() {\n let hotspot;\n\n hotspot = group\n .append(\"rect\")\n .attr(\"x\",plotter.margins.left)\n .attr(\"y\",plotter.margins.top)\n .attr(\"width\",plotter.width - plotter.margins.left - plotter.margins.right)\n .attr(\"height\",plotter.height - plotter.margins.top - plotter.margins.bottom)\n .attr(\"fill\",\"rgba(0,0,0,0)\");\n\n return hotspot;\n }\n\n function addPlotArea() {\n let plotGroup;\n\n plotGroup = explorableGroup({\n \"where\":group\n })\n .attr(\"transform\",\"translate(\"+plotter.margins.left+\",\"+plotter.margins.top+\")\");\n\n return plotGroup;\n }\n\n function addLayers() {\n let layers;\n\n layers = {};\n layers.plot = explorableGroup({\"where\":group})\n .attr(\"transform\",\"translate(\"+plotter.margins.left+\",\"+plotter.margins.top+\")\");\n\n layers.grid = explorableGroup({\"where\":layers.plot})\n .attr(\"clip-path\",\"url(#plotterClipPath)\");\n\n layers.axes = explorableGroup({\"where\":layers.plot});\n layers.lines = explorableGroup({\"where\":layers.plot});\n\n\n layers.indicators = explorableGroup({\"where\":group});\n layers.tooltip = explorableGroup({\"where\":group});\n\n return layers;\n }\n\n\n function addLines(functions) {\n let lines;\n\n if(functions.length == 0) {\n lines = [];\n\n return lines;\n }\n\n functions.forEach((aFunction) => {\n let line = new FunctionPlotterLine({\n \"function\":aFunction,\n \"where\":plotter.layers.lines,\n \"domain\":plotter.domain,\n \"scales\":plotter.scales,\n });\n\n lines.push(line);\n });\n\n return lines;\n }\n\n function addXAxis() {\n let axis;\n\n axis = new FunctionPlotterAxis({\n \"axisType\":\"bottom\",\n \"scales\":plotter.scales,\n \"tickCount\":axisTickCounts.x,\n \"where\":plotter.layers.axes\n });\n\n return axis;\n }\n\n function addYAxis() {\n let axis;\n\n axis = new FunctionPlotterAxis({\n \"axisType\":\"left\",\n \"scales\":plotter.scales,\n \"tickCount\":axisTickCounts.y,\n \"where\":plotter.layers.axes\n });\n\n return axis;\n }\n\n function defaultMargins() {\n return {\n \"left\":100,\n \"right\":10,\n \"top\":30,\n \"bottom\":50\n };\n }\n\n function defineScale(inputDomain,outputRange) {\n let scale;\n\n scale = d3.scaleLinear()\n .domain(inputDomain)\n .range(outputRange);\n\n return scale;\n }\n\n function defineScales() {\n let scales;\n\n scales = {};\n scales.x = defineScale(plotter.domain,[0,plotter.width - plotter.margins.right - plotter.margins.left]);\n scales.y = defineScale(plotter.range,[plotter.height - plotter.margins.bottom - plotter.margins.top,0]);\n\n return scales;\n }\n\n\n}", "function SVGPieChart() {\r\n }", "function miFuncion (){}", "function show_info(txt)\r\n{\r\n\t//alert(txt);\r\n $('info_div').show();// = 'shown';\r\n //var info_style = \r\n $('info_div').setStyle({left:mouseX+\"px\",top:mouseY+\"px\"});\r\n //info_style.left = mouseX+\"px\";\r\n //info_style.top = mouseY+\"px\";\r\n $('info_div').update(txt);\r\n}", "function popupD (feature,layer){\n layer.bindPopup(\n \"</p>Nombre: \"+feature.properties.Nombre+ \n \"</p>Casos cada cien mil (100.000) habitantes, mes de abril:\"+feature.properties.abr+\"</p>\"\n);\n layer.on('mouseover', function () { this.openPopup(); })\n}", "init() {\n const bar = d3.select(this.element);\n // Called when the application knows all needed information to create plots.\n document.addEventListener('setupFinished', (e) => {\n bar.style('opacity', '1');\n });\n // Create PlotTool menu tile\n const plotTileID = 'plotTile';\n const plotTileElement = bar.append('div').attr('id', plotTileID).node();\n const zoomTile = new PlotToolsTile(plotTileElement, '#'+plotTileID, {});\n }", "function infoHide(onClk)\r\n{ \r\ntry\r\n{\r\n\tvar label = GM_getValue(\"infoHide\",\"-\");\r\n\t\r\n\tif ((label==\"-\" && onClk==true) || (label==\"+\" && onClk==false)) \t//Hide\r\n\t{\r\n\t\tdocument.getElementById('infoButton').innerHTML = \"<img src='skin/layout/down-arrow.gif' alt='+' height='10' width='10'>\";\r\n\t\tGM_addStyle('#hideText {display:none;}');\r\n\t\tGM_setValue(\"infoHide\",\"+\");\r\n\t}\r\n\tif ((label==\"+\" && onClk==true) || (label==\"-\" && onClk==false))\t//Show \r\n\t{\r\n\t\tdocument.getElementById('infoButton').innerHTML = \"<img src='skin/layout/up-arrow.gif' alt='-' height='10' width='10'>\";\r\n\t\tGM_addStyle('#hideText {display:table-row;}');\r\n\t\tGM_setValue(\"infoHide\",\"-\");\r\n\t}\r\n}\r\ncatch(er) \t\t\t\t\r\n\t{infoError(\"function infoHide \",er)}\r\n}", "function showTooltip_onMouseOver(){\n//----------------------------------------------------------------------------------------------------------------------------\t\n\n\n this.dispalyTooltips = function(toolz){ //args(tooplips array)\n // request mousemove events\n $(\"#graph\").mousemove(function (e) {\n\t\t var onMouseOver_file = new onMouseOver();//uses other module in this very file\n onMouseOver_file.handleMouseMoveAction(e, toolz); //args(mouse event, tooplips array)\n });\n\n } \n}", "function ShowOutageDetails(mapPoint, attributes, title, height, width) {\n // alert(title);\n map.infoWindow.hide();\n if (!isMobileDevice) {\n dojo.byId('divCreateRequestContainer').style.display = \"none\";\n dojo.byId('divServiceRequestContent').style.display = \"none\";\n }\n selectedMapPoint = mapPoint;\n // for (var i in attributes) {\n // if (!attributes[i]) {\n // attributes[i] = \"\";\n // }\n // }\n\n //selectedRequestStatus = attributes.STATUS;\n //map.getLayer(tempGraphicsLayerId).clear();\n map.infoWindow.resize(width, height);\n //var screenPoint;\n //(isMobileDevice) ? map.centerAt(mapPoint) : map.setExtent(GetBrowserMapExtent(mapPoint));\n\n setTimeout(function () {\n screenPoint = map.toScreen(mapPoint);\n screenPoint.y = map.height - screenPoint.y;\n // if (isMobileDevice)\n // screenPoint = map.toScreen(mapPoint);\n // else {\n // screenPoint = map.toScreen(mapPoint);\n // screenPoint.y = map.height - screenPoint.y;\n // }\n map.infoWindow.show(screenPoint);\n //alert(title + \" new\");\n map.infoWindow.setTitle(title);\n dojo.connect(map.infoWindow.imgDetailsInstance(), \"onclick\", function () {\n map.infoWindow.hide();\n // if (isMobileDevice) {\n // selectedMapPoint = null;\n // map.infoWindow.hide();\n // ShowServiceRequestContainer();\n // }\n // else {\n // map.infoWindow.resize(300, 300);\n // screenPoint = map.toScreen(mapPoint);\n // screenPoint.y = map.height - screenPoint.y;\n // map.infoWindow.reSetLocation(screenPoint);\n // dojo.byId('divServiceRequestContent').style.display = \"block\";\n // }\n // ServiceRequestDetails(attributes);\n });\n\n // map.infoWindow.resize(225, 120);\n // dojo.byId('divServiceRequestContent').style.display = \"block\";\n //ServiceRequestDetails(attributes);\n map.infoWindow.setContent(attributes);\n }, 0);\n}", "function tempShowFeature(feature, evt) {\n\n roeMapTemp.graphics.clear(); //Clear graphics on the map\n\n //set graphic symbol\n var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 2), new dojo.Color([255, 255, 255, 0]));\n feature.setSymbol(symbol);\n\n // Build text and layout for the popup\n var attr = feature.attributes;\n var title = \"\"; //attr.NAME + \" watershed\"; //\", \" + toTitleCase(attr.StateName);\n var content = attr.DegFperCen;\n\n if (parseFloat(attr.DegFperCen) > 0) {\n content = \"+\" + attr.DegFperCen.toFixed(2) + \"&degF per century\";\n } else {\n content = attr.DegFperCen.toFixed(2) + \"&degF per century\";\n }\n\n //Add graphics\n roeMapTemp.graphics.add(feature);\n //Set title and content for the popup window\n roeMapTemp.infoWindow.setTitle(title);\n roeMapTemp.infoWindow.setContent(content);\n\n (evt) ? roeMapTemp.infoWindow.show(evt.screenPoint, roeMapTemp.getInfoWindowAnchor(evt.screenPoint)) : null;\n roeMapTemp.infoWindow.resize(170, 120);\n }", "function setBasicContentsAdGraphicsPanel() {\n var htmlStr = \"\";\n //make the dropdown disappear and put the cursor at the right text box...?\n /*\n htmlStr += \"<span><a href='javascript:setAdGraphicsFields(false, -1, \\\"\\\" , \\\"\\\", \\\"\\\")'>Add a new creative.</a></span><hr><p>\";\n htmlStr += \"<span>Hint: Type words to search (by name) your existing creatives.</span><hr>\";\n */\n htmlStr += '<span>' + hseLabelInt['creatives'] + ':</span><br>';\n\n for (var gid in graphicObjs){\n var obj = graphicObjs[gid];\n\n htmlStr += \"<a href='javascript:populateCreativesTab(false, \" + gid +\n \", \\\"\" + escape(obj.hse_gname) + \"\\\", \\\"\" + obj.image_url + \"\\\", \\\"\" +\n obj.target_url +\n \"\\\")'><img height=\\\"52\\\" width=\\\"90\\\" src=\\\"\";\n htmlStr += obj.image_url + \"\\\" class=\\\"hastip tiny_adgraphics_img\\\" title=\\\"\";\n htmlStr += obj.target_url + \",\" + obj.hse_gname;\n htmlStr += \"\\\"/></a>\";\n }\n var contents = $(htmlStr);\n var dest = $(\"#hse_graphicsPanel\");\n dest.empty();\n contents.appendTo(dest);\n $( \".hastip\").tooltip({show: {effect:\"none\", delay:0}});\n}", "function showFeature(feature, evt) {\n roeMapBio.graphics.clear(); //Clear graphics on the map\n \n //set graphic symbol\n var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 2), new dojo.Color([255, 255, 255, 0]));\n feature.setSymbol(symbol);\n\n function toTitleCase(str) {\n return str.replace(/\\w\\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });\n }\n \n // Build text and layout for the popup\n var attr = feature.attributes;\n \n //alert(attr.Biomass_sm.toFixed(3));\n var st = attr.ST_NAME; //attr.STATENAME;\n var county = attr.NAME; //attr.CountyName;\n var title = county + \", \" + st;//attr.NAMELSAD + \", \" + toTitleCase(attr.StateName);\n var content = \"\";\n\n if (attr.Biomass_pe != null){\n content += \"<div>\" + attr.Biomass_pe.toFixed(3) + \" million metric tons of forest carbon per square mile of land </div>\";\n } else{\n content += \"<div>No forest or no data</div>\";\n }\n \n //Add graphics\n roeMapBio.graphics.add(feature);\n //Set title and content for the popup window\n roeMapBio.infoWindow.setTitle(title);\n roeMapBio.infoWindow.setContent(content);\n\n (evt) ? roeMapBio.infoWindow.show(evt.screenPoint, roeMapBio.getInfoWindowAnchor(evt.screenPoint)) : null;\n roeMapBio.infoWindow.resize(300, 120);\n }", "function informationHandler(event)\n\t\t{\n\t\t\tg.informe();\n\t\t\thideButtons(this);\n\t\t}", "function showMarvelData(data) {\n marvelData(data);\n}", "function mostrar() {}", "function mostrar() {}", "function setgriddisplaycallback(callback) {\n\n setgriddisplay = callback;\n\n }", "function popupM(feature,layer){\n layer.bindPopup(\n \"</p>Nombre: \"+feature.properties.Nombre+ \n \"</p>Casos cada cien mil (100.000) habitantes, mes de diciembre:\"+feature.properties.dic+\"</p>\"\n);\n layer.on('mouseover', function () { this.openPopup(); })\n}", "function earthnc_chartdsp(){\n //close_menus();\n\n show(\"chart_dsp\");\n hide(\"link_char_open\");\n show(\"link_char_close\");\n\n\n}", "function butterscotchPie(){\n \n}", "function activateMeasure(){\n mapImplementation.ActivateMeasure();\n }", "function addPopupInfo(feature, layer) {\n\n // If this feature has properties named 'mag', 'place' and 'time', add a Tool Tip.\n if (feature.properties && feature.properties.mag &&\n feature.properties.place && feature.properties.time) {\n layer.bindTooltip('<div align=\"center\"><div>Magnitude: ' + feature.properties.mag +\n '</div><div>Place: ' + feature.properties.place +\n '</div><div>Date: ' + new Date(+feature.properties.time).toDateString() +\n '</div><div>(Click circle for USGS link)</div></div>');\n }\n\n}", "function view_function_extensible_dispersion (clv, str_b, number_saturation){\n str = '';\n str_normal = str_b;\n str_bold = '';\n \n v_a = copy_val_asoc[number_saturation];\n \n dif = 8 - v_a;\n str_normal = str_b.substring(0, dif);\n str_bold = str_b.substring(dif, 8);\n \n tag = \"<h4 id='funcion_animacion'>F(\"+clv+\") = \"+str_normal+\"<b>\"+str_bold+\"</b></h4>\";\n str = str + \"<div id='panel-funcion'>\";\n str = str + tag;\n str = str + \"</div>\";\n $(\"#panel-funcion\").replaceWith(str);\n}", "function init() {\n setUpToolTip();\n}", "function onEachFeature(feature, layer) {\r\n layer.on({\r\n\t\t'mouseover': function (e) {\r\n\t\t\thighlight(e.target);\r\n\t\t },\r\n\t\t 'mouseout': function (e) {\r\n\t\t\tdehighlight(e.target);\r\n\t\t }, \r\n\t\t'click': function(e)\r\n\t\t\t{\r\n\t\t\t\t// enlever les interaction avec la carte sur une div \r\n\t\t\t\t$('#mySidepanel.sidepanel').mousedown( function() {\r\n\t\t\t\t\tmap2.dragging.disable();\r\n\t\t\t\t });\r\n\t\t\t\t $('html').mouseup( function() {\r\n\t\t\t\t\tmap2.dragging.enable();\r\n\t\t\t\t});\r\n\t\t\t\t// ouverture du panel \r\n\t\t\topenNav(e.target),\r\n\t\t\t// affichage des graphiques \r\n\t\t\tdocument.getElementById(\"myChart\").style.display='block';\r\n\t\t\tdocument.getElementById(\"myChart3\").style.display='none';\r\n\t\t\t// fermeture de la comparaison \r\n\t\t\t// selection des toits \r\n\t\t\tselect(e.target), \r\n\t\t\t// information dans le panel sur le toit sélectionné \r\n\t\t\tdocument.getElementById(\"5\").innerHTML = \"<strong>Adresse : </strong>\" + feature.properties.addr_numer + feature.properties.addr_nom_1 + \"<br>\" + \"<strong>Type : </strong>\" + feature.properties.prop + \"<br>\" + \"<strong>Usage : </strong>\" + feature.properties.usage1 + \"<br>\" + \"<strong>Pluviométrie : </strong>\" + feature.properties.pluvio_max.toFixed(2) + \" mm/an\"+\"<br>\" + \"<strong>Surface : </strong>\" + feature.properties.shape_area.toFixed(2) + \" m²\" + \"<br>\" + \"<strong>Ensoleillement : </strong>\" + feature.properties.sr_mwh.toFixed(2) + \" KWh/m²\" + \"<hr>\"\r\n// graphique sur l'influence des critères dans le roofpotentiel \r\n\t\t\tvar ctx1 = document.getElementById('myChart2').getContext('2d');\r\nvar chart1 = new Chart(ctx1, { \r\n // The type of chart we want to create\r\n type: 'horizontalBar',\r\n\r\n // The data for our dataset\r\n data: {\r\n labels: ['Pluviométrie', 'Surface', 'Ensoleillement', 'Solidité'],\r\n datasets: [{\r\n\t\t\tbackgroundColor: ['rgb(26, 196, 179)', \r\n\t\t\t'rgb(26, 196, 179)', \r\n\t\t\t'rgb(26, 196, 179)', 'rgb(26, 196, 179)'], \r\n borderColor: 'rgb(255, 99, 132)',\r\n data: [e.target.feature.properties.pluviok, e.target.feature.properties.surfacek, e.target.feature.properties.expok, e.target.feature.properties.solidek]\r\n }]\r\n },\r\n\r\n // Configuration options go here\r\n\toptions: {\r\n\t\t// animation: {\r\n // duration: 0 // general animation time\r\n // },\r\n\t\tevents: [], \r\n\t\tlegend: {\r\n\t\t\tdisplay: false}, \r\n\t\t\tscales: {\r\n\t\t\t\txAxes: [{\r\n\t\t\t\t\tticks: {\r\n\t\t\t\t\t\tmax: 5,\r\n\t\t\t\t\t\tmin: 0,\r\n\t\t\t\t\t\tstepSize: 1, \r\n\t\t\t\t\t\tdisplay: false\r\n\t\t\t\t\t}\r\n\t\t\t\t}]\r\n\t\t\t}\r\n\t}\r\n}); \r\n// graphique du roofpotentiel \r\nvar ctx2 = document.getElementById('myChart').getContext('2d');\r\n$('#PluvioInputId').val(1)\r\n$('#PluvioOutputId').val(1)\r\n$('#SurfaceInputId').val(1)\r\n$('#SurfaceOutputId').val(1)\r\n$('#ExpoInputId').val(1)\r\n$('#ExpoOutputId').val(1)\r\n$('#SoliInputId').val(1)\r\n$('#SoliOutputId').val(1)\r\n\tvar chart2 =new Chart(ctx2, {\r\n\t\t// The type of chart we want to create\r\n\t\ttype: 'horizontalBar',\r\n\t\r\n\t\t// The data for our dataset\r\n\t\tdata: {\r\n\t\t\tdatasets: [{\r\n\t\t\t\tbackgroundColor: function(feature){\r\n\t\r\n\t\t\t\t\tvar score = e.target.feature.properties.scoring;\r\n\t\t\t\t\tif (score > 90) {\r\n\t\t\t\t\t\treturn '#008080'; \r\n\t\t\t\t\t } \r\n\t\t\t\t\t else if (score > 80) {\r\n\t\t\t\t\t\treturn '#6EC6BA';\r\n\t\t\t\t\t } \r\n\t\t\t\t\t else if (score > 75) {\r\n\t\t\t\t\t\treturn '#A8E1CE';\r\n\t\t\t\t\t }\r\n\t\t\t\t\t else if (score > 70) {\r\n\t\t\t\t\t\treturn ' #CCF1D2';\r\n\t\t\t\t\t }\r\n\t\t\t\t\t else if (score >= 0) {\r\n\t\t\t\t\t\treturn '#EBF9ED';\r\n\t\t\t\t\t };\r\n\r\n\t\t\t\t},\r\n\t\t\t\tdata: [e.target.feature.properties.scoring],\r\n\t\t\t\tbarThickness: 2,\r\n\t\t\t}]\r\n\t\t},\r\n\t\t// Configuration options go here\r\n\t\toptions: {\r\n\t\t\tevents: [], \r\n\t\t\tlegend: {\r\n\t\t\t\tdisplay: false}, \r\n\t\t\t\tscales: {\r\n\t\t\t\t\txAxes: [{\r\n\t\t\t\t\t\tticks: {\r\n\t\t\t\t\t\t\tmax: 100,\r\n\t\t\t\t\t\t\tmin: 0,\r\n\t\t\t\t\t\t\tstepSize: 20\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}]\r\n\t\t\t\t}\r\n\t\t}\r\n\t});\r\n\r\n//Fonction pour faire varier le poids des critéres et calculer à nouveau le scoring\r\n$('#valideform').click(function(event) {\r\n\tdocument.getElementById(\"myChart3\").style.display='block';\r\n\tdocument.getElementById(\"myChart\").style.display='none';\r\n\tvar ctx3 = document.getElementById('myChart3').getContext('2d');\r\n\tdocument.getElementById('mySidepanel').scroll({top:0,behavior:'smooth'});\r\n\tvar pluvio = $('#PluvioInputId').val()\r\n\tvar surface = $('#SurfaceInputId').val()\r\n\tvar ensoleillement = $('#ExpoInputId').val()\r\n\tvar solidite = $('#SoliInputId').val()\r\n\tvar somme = (100/((5*pluvio)+(5*surface)+(5*ensoleillement)+(5*solidite)))*(e.target.feature.properties.pluviok * pluvio + e.target.feature.properties.expok * ensoleillement + e.target.feature.properties.surfacek * surface + e.target.feature.properties.solidek * solidite)\r\n\t\tvar chart3 =new Chart(ctx3, {\r\n\t\t\t// The type of chart we want to create\r\n\t\t\ttype: 'horizontalBar',\r\n\t\t\r\n\t\t\t// The data for our dataset\r\n\t\t\tdata: {\r\n\t\t\t\tdatasets: [{\r\n\t\t\t\t\tbackgroundColor: function(feature){\r\n\t\t\r\n\t\t\t\t\t\tvar score = somme;\r\n\t\t\t\t\t\tif (score > 90) {\r\n\t\t\t\t\t\t\treturn '#008080'; \r\n\t\t\t\t\t\t } \r\n\t\t\t\t\t\t else if (score > 80) {\r\n\t\t\t\t\t\t\treturn '#6EC6BA';\r\n\t\t\t\t\t\t } \r\n\t\t\t\t\t\t else if (score > 75) {\r\n\t\t\t\t\t\t\treturn '#A8E1CE';\r\n\t\t\t\t\t\t }\r\n\t\t\t\t\t\t else if (score > 70) {\r\n\t\t\t\t\t\t\treturn ' #CCF1D2';\r\n\t\t\t\t\t\t }\r\n\t\t\t\t\t\t else if (score >= 0) {\r\n\t\t\t\t\t\t\treturn '#EBF9ED';\r\n\t\t\t\t\t\t };\r\n\t\t\t\t\t},\r\n\t\t\t\t\tdata: [somme],\r\n\t\t\t\t\tbarThickness: 2,\r\n\t\t\t\t}]\r\n\t\t\t},\r\n\t\t\r\n\t\t\r\n\t\t\t// Configuration options go here\r\n\t\t\toptions: {\r\n\t\t\t\tevents: [], \r\n\t\t\t\tlegend: {\r\n\t\t\t\t\tdisplay: false}, \r\n\t\t\t\t\tscales: {\r\n\t\t\t\t\t\txAxes: [{\r\n\t\t\t\t\t\t\tticks: {\r\n\t\t\t\t\t\t\t\tmax: 100,\r\n\t\t\t\t\t\t\t\tmin: 0,\r\n\t\t\t\t\t\t\t\tstepSize: 20\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}]\r\n\t\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n});\r\n\r\n//Fonction pour réinitialiser les critères par un bouton \r\n$('#renitform').click(function(event) {\r\n\tdocument.getElementById(\"myChart3\").style.display='none';\r\n\tdocument.getElementById(\"myChart\").style.display='block';\r\n\tdocument.getElementById('mySidepanel').scroll({top:0,behavior:'smooth'});\r\n\t$('#PluvioInputId').val(1)\t//replace le slider sur la valeur 1\r\n\t$('#PluvioOutputId').val(1)\r\n\t$('#SurfaceInputId').val(1)\r\n\t$('#SurfaceOutputId').val(1)\r\n\t$('#ExpoInputId').val(1)\r\n\t$('#ExpoOutputId').val(1)\r\n\t$('#SoliInputId').val(1)\r\n\t$('#SoliOutputId').val(1)\r\n})\r\n\r\n\r\n//Fonction pour ouvrir les fiches en fonction du scoring \r\nfunction showButton(){\r\n\tvar type = e.target.feature.properties.scoring\r\n\t if (type >= 90) {\r\n\t\treturn document.getElementById(\"fiche1\").style.display='block',\r\n\t\tdocument.getElementById(\"fiche1body\").innerHTML = \"<strong>Adresse : </strong>\" + feature.properties.addr_numer + feature.properties.addr_nom_1 + \"<br>\" + \"<strong>Type : </strong>\" + feature.properties.prop + \"<br>\" + \"<strong>Usage : </strong>\" + feature.properties.usage1 + \"<br>\" + \"<strong>Pluviométrie : </strong>\" + feature.properties.pluvio_max.toFixed(2) + \" mm/an\"+\"<br>\" + \"<strong>Surface : </strong>\" + feature.properties.shape_area.toFixed(2) + \" m²\" + \"<br>\" + \"<strong>Ensoleillement : </strong>\" + feature.properties.sr_mwh.toFixed(2) + \" KWh/m²\", \r\n\t\tdocument.getElementById(\"fiche2\").style.display='none', \r\n\t\tdocument.getElementById(\"fiche3\").style.display='none',\r\n\t\tdocument.getElementById(\"nbpersonne1\").innerHTML = ((feature.properties.shape_area)*3.5/127).toFixed(0); \r\n\t } \r\n\t else if (type >= 70) {\r\n\t\treturn document.getElementById(\"fiche2\").style.display='block',\r\n\t\tdocument.getElementById(\"fiche2body\").innerHTML = \"<strong>Adresse : </strong>\" + feature.properties.addr_numer + feature.properties.addr_nom_1 + \"<br>\" + \"<strong>Type : </strong>\" + feature.properties.prop + \"<br>\" + \"<strong>Usage : </strong>\" + feature.properties.usage1 + \"<br>\" + \"<strong>Pluviométrie : </strong>\" + feature.properties.pluvio_max.toFixed(2) + \" mm/an\"+\"<br>\" + \"<strong>Surface : </strong>\" + feature.properties.shape_area.toFixed(2) + \" m²\" + \"<br>\" + \"<strong>Ensoleillement : </strong>\" + feature.properties.sr_mwh.toFixed(2) + \" KWh/m²\", \r\n\t\tdocument.getElementById(\"fiche1\").style.display='none', \r\n\t\tdocument.getElementById(\"fiche3\").style.display='none',\r\n\t\tdocument.getElementById(\"nbpersonne2\").innerHTML = ((feature.properties.shape_area)*2.5/127).toFixed(0); \r\n\t } \r\n\t else {\r\n\t\treturn document.getElementById(\"fiche3\").style.display='block',\r\n\t\tdocument.getElementById(\"fiche3body\").innerHTML = \"<strong>Adresse : </strong>\" + feature.properties.addr_numer + feature.properties.addr_nom_1 + \"<br>\" + \"<strong>Type : </strong>\" + feature.properties.prop + \"<br>\" + \"<strong>Usage : </strong>\" + feature.properties.usage1 + \"<br>\" + \"<strong>Pluviométrie : </strong>\" + feature.properties.pluvio_max.toFixed(2) + \" mm/an\"+\"<br>\" + \"<strong>Surface : </strong>\" + feature.properties.shape_area.toFixed(2) + \" m²\" + \"<br>\" + \"<strong>Ensoleillement : </strong>\" + feature.properties.sr_mwh.toFixed(2) + \" KWh/m²\", \r\n\t\tdocument.getElementById(\"fiche1\").style.display='none', \r\n\t\tdocument.getElementById(\"fiche2\").style.display='none',\r\n\t\tdocument.getElementById(\"nbpersonne3\").innerHTML = ((feature.properties.shape_area)*1.5/127).toFixed(0); \r\n\t }\r\n }; \r\nshowButton(e.target); \r\n\r\n// destruction des graphiques a la fermeture du panel \r\n(function() { // self calling function replaces document.ready()\r\n\t//adding event listenr to button\r\ndocument.querySelector('#closesidepanel').addEventListener('click',function(){\r\n\t\tchart1.destroy();\r\n\t\tchart2.destroy(); \r\n\t\t});\r\n\t})();\r\n}\r\n})\r\n}", "function revealFact2(idElement) {\n d3.select(\"#f\" + idElement + \"_line\").style(\"opacity\", 1);\n d3.select(\"#f\" + idElement + \"_head\").style(\"opacity\", 1);\n document.getElementById(\"f\" + idElement.toString()).innerHTML =\n \"<a href='#' onclick=\" +\n \"resetFact(\" +\n idElement +\n \");\" +\n \">Being a girl or a boy does not bring any protection from getting bullied. The largest difference between proportion of girls and boys being bullied is only 1.6% in 2014. </a>\";\n}", "function aa_info_p(d) {\n\tif(d.data.type==\"AA\"||d.data.type==\"Base\"){\n\t\t//information collapsed indicator\n\t\td3.select('a#aa_infor_head').selectAll(\"img\").remove();\n\t\tif(d3.select('div#collapseOne').attr(\"class\")==\"accordion-body collapse\")\n\t\t{\n\t\t\td3.select('a#aa_infor_head').append(\"img\").attr(\"src\", \"img/on.gif\").attr(\"align\", \"right\");\n\t\t}\n\t\td3.select('a#aa_infor_head').on(\"click\", function(){\n\t\t\td3.select('a#aa_infor_head').select(\"img\").remove();\n\t\t});\n\t\t\n\t\td3.select('a#rscu_head').selectAll(\"img\").remove();\n\t\tif(d3.select('div#collapseTwo').attr(\"class\")==\"accordion-body collapse\"){\n\t\t\td3.select('a#rscu_head').append(\"img\").attr(\"src\", \"img/on.gif\").attr(\"align\", \"right\");\n\t\t}\n\t\td3.select('a#rscu_head').on(\"click\", function(){\n\t\t\td3.select('a#rscu_head').select(\"img\").remove();\n\t\t});\n\t\t\n\t\tvar current_name = d.data.name.split(\"/\");\n\t\tvar type = d.data.type;\n\t\td3.text(\"genetic_code/\"+ncbi_genetic_code_a_talbes[gp_genetic_code_no-1], function(d) {\n\t\tvar codon2aa = {};\n\t\tvar genetic_code_line4 = d;\t\t\n\t\tvar lines = genetic_code_line4.split(\"\\n\");\n\t\tvar aa_line = lines[0].replace(/\\s+/g, \"\").split(\"=\");\n\t\tvar aa = aa_line[1].split(\"\");\n\t\tvar base1_line = lines[2].replace(/\\s+/g, \"\").split(\"=\");var base1 = base1_line[1].split(\"\");\n\t\tvar base2_line = lines[3].replace(/\\s+/g, \"\").split(\"=\");var base2 = base2_line[1].split(\"\");\n\t\tvar base3_line = lines[4].replace(/\\s+/g, \"\").split(\"=\");var base3 = base3_line[1].split(\"\");\n\t\tfor(var a = 0; a<aa.length; a++){codon2aa[base1[a]+base2[a]+base3[a]] = aa[a];}\n//###################################\n\t\td3.selectAll(\"div.aa_infor text, div.aa_infor img, div.aa_infor br, div.aa_infor a, div.rscu text, div.rscu br\").remove();\n\t\td3.selectAll(\"div.rscu text, div.rscu div, div.rscu br, div.rscu a\").remove();\n\t\tcurrent_name.forEach(function(cell_class){\n\t\tif(type==\"Base\")\n\t\t{\n\t\t\tcell_class = codon2aa[cell_class];\n\t\t}\n\t\t\t\n\t\t\td3.selectAll(\"div.aa_infor\").append(\"a\").style(\"font-size\", \"14px\").text(amino_acids[cell_class].full+\" (\"+cell_class+\")\").attr(\"href\", \"http://en.wikipedia.org/wiki/\"+amino_acids[cell_class].full);\n\t\t\td3.selectAll(\"div.aa_infor\").append(\"br\");\n\t\t\tif(cell_class==\"*\"){\n\t\t\t\td3.selectAll(\"div.aa_infor text\").text(\"\");\n\t\t\t}\n\t\t\telse{\n\t\t\t\td3.select(\"div.aa_infor\").append(\"text\").text(\"Structure: \");\n\t\t\t\td3.select(\"div.aa_infor\").append(\"img\").attr(\"src\", \"aa_infor_img/\"+amino_acids[cell_class].full+\".png\").attr(\"width\", 150).attr(\"height\", 150);\n\t\t\t\td3.selectAll(\"div.aa_infor\").append(\"br\");\n\t\t\t\td3.select(\"div.aa_infor\").append(\"text\").text(\"Side_chain Polarity: \"+amino_acids[cell_class].polarity);\n\t\t\t\td3.selectAll(\"div.aa_infor\").append(\"br\");\n\t\t\t\td3.select(\"div.aa_infor\").append(\"text\")\n\t\t\t\t\t\t.text(\"Atomic Mass: \"+amino_acids[cell_class].atomic_mass+\" g mol\")\n\t\t\t\t\t\t.append(\"tspan\").text(\"-1\").attr({\"baseline-shift\":\"super\"});\n\t\t\t\td3.selectAll(\"div.aa_infor\").append(\"br\");\n\t\t\t}\n\t\t\td3.selectAll(\"div.aa_infor\").append(\"br\");\n\n\t\t\td3.selectAll(\"div.rscu\").append(\"a\").style(\"font-size\", \"14px\").text(amino_acids[cell_class].full+\" (\"+cell_class+\")\").attr(\"href\", \"http://en.wikipedia.org/wiki/\"+amino_acids[cell_class].full);\n\t\t\td3.select(\"div.rscu\").append(\"br\");\n\t\t\tif(cell_class==\"*\"){\n\t\t\t\td3.selectAll(\"div.rscu text\").text(\"\");\n\t\t\t}\n\t\t\telse{\n\t\t\t\td3.select(\"div.rscu\").append(\"div\").attr(\"class\",cell_class);\n\t\t\t\tvar canvas = \"div.rscu div.\"+cell_class;\n\t\t\t\tvar rec_name = gp_files[gp_rec_no];\n\t\t\t\tvar aa_name = cell_class;\n//\t\t\t\tconsole.log(\"canvas:\" ,canvas ,\"ec_name:\",rec_name,\"aa_name:\" ,aa_name );\n\t\t\t\trscu_aa_figure(canvas, aa_name);\n\t\t\t\td3.selectAll(\"div.rscu\").append(\"br\");\n\t\t\t}\n\t\t});\n\t\t});\n\n\t}\n\telse\n\t{\n//###################################\n\t\td3.selectAll(\"div.aa_infor text, div.aa_infor img, div.aa_infor br, div.aa_infor a\").remove();\n\t\td3.selectAll(\"div.rscu text, div.rscu div, div.rscu br, div.rscu a\").remove();\n\t\td3.select(\"div.aa_infor\").append(\"text\").style(\"color\", \"red\").text(\"Please select Amino Acids.\");\n\t\td3.select(\"div.rscu\").append(\"text\").style(\"color\", \"red\").text(\"Please select Amino Acids.\");\n\t}\n}", "function selectfloodpumpMap() {\r\n\r\n\t//select on pump sta map\r\n\tpumpstationlayer.setStyle(function (feature){\r\n\t\r\n\t//highlight pump station on the map\r\n\tif (clickchartpump === feature.properties.Borough_BN ){\r\n\tfeature.properties.selected = true;\r\n\t\r\n\t\treturn {\r\n\t\t\t\tradius: 5,\r\n\t\t\t\tfillColor: \"#0000ff\",\r\n\t\t\t\tcolor: \"#000000\",\r\n\t\t\t\tweight: 1,\r\n\t\t\t\topacity: 1,\r\n\t\t\t\tfillOpacity: 1\t\t\t\t\r\n\t\t} \r\n\t\t\r\n\t}else { \r\n\t\tfeature.properties.selected = false;\r\n\t\t return pumpstaStyle;\r\n\t\t}\r\n\t});\r\n\t\r\n\t\t//select on map\r\n\tfloodrisklayer.setStyle(function (feature){\r\n\tvar i;\r\n\t\tif (clickchartpump === feature.properties.NAME ){\r\n\t\tfeature.properties.selected = true;\r\n\t\t\tif (feature.properties.selected){\r\n\t\treturn {\r\n\t\t\t\tweight: 5,\r\n\t\t\t\tfillColor: '#666',\r\n\t\t\t\tcolor: '#666',\r\n\t\t\t\tdashArray: '',\r\n\t\t\t\tfillOpacity: 0.7\r\n\t\t\t\t\r\n\t\t\t} }\r\n\t\t\r\n\t}else {\r\n\t\tfeature.properties.selected = false;\r\n\t\treturn FloodRiskstyle(feature);\t\r\n\t\t}\r\n\t});\r\n\t\r\n\t//change detail chart\r\n\tvar i;\r\n\tfor (i = 0; i < floodriskper.length; i++) { \r\n\tif (clickchartpump === floodriskper[i][0]){\r\n\t\tfloodriskvalue = floodriskper[i][1];\r\n\t}\r\n\t}\r\n\tlayoutTable.getCell(0, 1).content(Detaillinegauge());\r\n\r\n\r\n}", "setTooltip_() {\n this.tooltip = $('arc-event-band-tooltip');\n this.svg.onmouseover = this.showToolTip_.bind(this);\n this.svg.onmouseout = this.hideToolTip_.bind(this);\n this.svg.onmousemove = this.updateToolTip_.bind(this);\n this.svg.onclick = (event) => {\n showDetailedInfoForBand(this, event);\n };\n }", "function open_infobox(point_id) {\n var point_bullet = $(window.point_list[point_id]);\n $('.infobox h1').text(point_bullet.find('h3').text());\n $('.infobox__insertedhtml').html(point_bullet.find('.point_data__content').html());\n $('.infobox').fadeIn(\"fast\", function () {\n $(this).addClass('show');\n });\n}", "function showTooltipEdition(d, color) {\n\t\t\n\t//Find location of mouse on page\n\tvar xpos = d3.event.pageX - 10;\n\tvar ypos = d3.event.pageY + 80;\n\n\t//Set the title and discipline\n\td3.select(\"#tooltip-edition-wrapper #tooltip-edition-edition\").text(d.edition);\n\t\n\t//Set city and continent\n\tvar city, continent, contColor = \"\";\n\tif (d.city === \"none\") {\n\t\tcity = \"No Olympics - WW II\";\n\t\tcontinent = \"-\";\n\t\tcontColor = \"#d2d2d2\";\n\t} else {\n\t\tcity = d.city;\n\t\tcontinent = d.cityContinent;\n\t\tcontColor = color(continent);\n\t}\n\n\td3.select(\"#tooltip-edition-wrapper #tooltip-edition-city\").text(city);\n\td3.select(\"#tooltip-edition-wrapper #tooltip-edition-continent\")\n\t\t.style(\"color\", contColor)\n\t\t.text(continent);\n\n\t//Set the tooltip in the right location and display it\n\td3.select(\"#tooltip-edition-wrapper\")\n\t\t.style(\"top\", ypos + \"px\")\n\t\t.style(\"left\", xpos + \"px\")\n\t\t.transition().duration(0)\n\t\t.style(\"opacity\", 1);\n}//showTooltipEdition", "function optionChanged(id){\n showPlots(id);\n infoCard(id);\n}", "tooltipClicked() {}", "function draw(){\n\t\t// Needed to comply with Tool Delegate design pattern\n\t}", "function precipShowFeature(feature, evt) {\n\n roeMapPrecip.graphics.clear(); //Clear graphics on the map\n\n //set graphic symbol\n var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 2), new dojo.Color([255, 255, 255, 0]));\n feature.setSymbol(symbol);\n\n // Build text and layout for the popup\n var attr = feature.attributes;\n var title = \"\"; //attr.NAME + \" watershed\"; //\", \" + toTitleCase(attr.StateName);\n var content = \"\";\n var pct = attr.PercentChn * 100;\n if (parseFloat(attr.PercentChn) > 0) {\n content = \"+\" + pct.toFixed(1) + \"&#37\";\n } else {\n content = pct.toFixed(1) + \"&#37\";\n }\n\n //Add graphics\n roeMapPrecip.graphics.add(feature);\n //Set title and content for the popup window\n roeMapPrecip.infoWindow.setTitle(title);\n roeMapPrecip.infoWindow.setContent(content);\n\n (evt) ? roeMapPrecip.infoWindow.show(evt.screenPoint, roeMapPrecip.getInfoWindowAnchor(evt.screenPoint)) : null;\n roeMapPrecip.infoWindow.resize(170, 120);\n }", "function showInfoWindow(event) {\n\tvar $elementFired = $( event.data.elementPlotter );\n\t\n\tif (exists($elementFired)) {\n\t\tvar id = $elementFired.attr('item-id');\n\t\t\n\t\tif (id) {\n\t\t\tfor (var indexInfoMarks = 0; indexInfoMarks < markers.length; indexInfoMarks++) {\n\t\t\t\tvar infoMark = markers[indexInfoMarks];\n\t\t\t\t\n\t\t\t\tif (infoMark.id == id) {\n\t\t\t\t\tnew google.maps.event.trigger( infoMark.googleOBJ , 'click' );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "function showTooltip(content, refIndic,event) {\n tt.style('opacity', 1.0)\n .html(content);\n\n updatelineChart(refIndic)\n updatePosition(event);\n }", "function fnhideInformation()\r\n\t\t{\r\n\t\t\tmblnOnInfoWindow = false;\r\n\t\t}", "function hideShowInfoDetails() {\n linkId = this.valueOf();\n highlightSelectedMeasure(null);\n hideShowRequest({\n requestingMethod: \"LearningCurve.hideShowInfoDetails\",\n datasetId: dataset,\n linkId: linkId,\n hideShow: $(linkId).up().visible() ? \"hide\" : \"show\"\n });\n}", "function setup_showInfo() {\n\tdocument.getElementById(\"basic\").style.display = \"none\";\n\tdocument.getElementById(\"create\").style.display = \"none\";\n\tdocument.getElementById(\"source\").style.display = \"none\";\n\tdocument.getElementById(\"info\").style.display = \"block\";\n}", "function demoInfo(id) {\r\n d3.json(\"data/cardata.json\").then((data)=> {\r\n //call in metadata to demographic panel//\r\n var car_data = data.cars;\r\n var result = car_data.filter(car => car.index_col.toString() === id)[0]\r\n\r\n console.log(`test ${result}`)\r\n\r\n //select demographic panel from html//\r\n var features = d3.select(\"#cardata-cars\");\r\n //empty the demographic panel for new data//\r\n features.html(\"\");\r\n Object.entries(result).forEach((key) => {\r\n features.append(\"h5\").text(key[0]+ \": \" + key[1]);\r\n });\r\n });\r\n}", "function dataLoaded() {\r\n if (width>700) {\r\n document.getElementById(\"more-info\").innerHTML =\r\n \"Hover over one of the animal's text in the legend to see which U.S. national parks have them.\";\r\n }\r\n else {\r\n document.getElementById(\"more-info\").innerHTML =\r\n \"Click on one of the animal's text in the legend to see which U.S. national parks have them.\";\r\n }\r\n}", "function details_off(d) {\n\n\tvar sp_dot = document.getElementById(\"sp\"+d.Team);\n\tvar tm_node = document.getElementById(\"tm\"+d.Team);\n\n switch(zoom_level) {\n\t // Conference - make everyone visible\n\t case 0: \n\t\t\tteams.forEach(function(team) {\n\t\t\t\tdocument.getElementById(\"sp\"+team).setAttribute(\"opacity\", 1);\n\t\t\t});\n\t\t\tbreak;\n\t\t\t\n\t // Division - make division's teams visible\n\t case 1: \n\t\t\tteams.forEach(function(team) {\n\t\t\t\tif(division_map[team] == current_division) \n\t\t\t\t\tdocument.getElementById(\"sp\"+team).setAttribute(\"opacity\", 1);\n\t\t\t});\n\t\t\tbreak;\n\t\t\t\n\t // Team - make focused team visible\n\t case 2:\n\t\t\tteams.forEach(function(team) {\n\t\t\t\tdocument.getElementById(\"sp\"+team).setAttribute(\"opacity\", .1);\n\t\t\t});\n\t\t\tdocument.getElementById(\"sp\"+current_team).setAttribute(\"opacity\", 1);\n\t\t\tbreak;\n\t}\n\t\n\t// Reset dot\n\tsp_dot.setAttribute(\"r\", old_dot);\n sp_dot.setAttribute(\"opacity\", old_opacity);\n\t\n\t// Reset node\n\ttm_node.style.opacity = \"1\";\n\t\n\t//Disappear tooltip\n\ttooltip.transition()\n\t\t.duration(100)\n\t\t.style(\"opacity\", 0); \n}", "_initPanelAdapter() {\n }", "setPopup(department, layer) {\n if (department.properties && department.properties.nom && department.properties.metrics) {\n let content = `<h6>${department.properties.nom} (${department.properties.code})</h6>\\\n <table class=\"table table-borderless table-hover\">\n <thead>\n <tr>\n <th scope=\"col\">#</th>\n <th scope=\"col\">1e dose</th>\n <th scope=\"col\">Vaccinés</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th scope=\"row\">0-24 ans</th>\n <td>${department.properties.metrics[24].n_tot_dose1.toLocaleString()} (${department.properties.metrics[24].rate_dose1} %)</td>\n <td>${department.properties.metrics[24].n_tot_complet.toLocaleString()} (${department.properties.metrics[24].rate_complet} %)</td>\n </tr>\n <tr>\n <th scope=\"row\">25-29 ans</th>\n <td>${department.properties.metrics[29].n_tot_dose1.toLocaleString()} (${department.properties.metrics[29].rate_dose1} %)</td>\n <td>${department.properties.metrics[29].n_tot_complet.toLocaleString()} (${department.properties.metrics[29].rate_complet} %)</td>\n </tr>\n <tr>\n <th scope=\"row\">30-39 ans</th>\n <td>${department.properties.metrics[39].n_tot_dose1.toLocaleString()} (${department.properties.metrics[39].rate_dose1} %)</td>\n <td>${department.properties.metrics[39].n_tot_complet.toLocaleString()} (${department.properties.metrics[39].rate_complet} %)</td>\n </tr>\n <tr>\n <th scope=\"row\">40-49 ans</th>\n <td>${department.properties.metrics[49].n_tot_dose1.toLocaleString()} (${department.properties.metrics[49].rate_dose1} %)</td>\n <td>${department.properties.metrics[49].n_tot_complet.toLocaleString()} (${department.properties.metrics[49].rate_complet} %)</td>\n </tr>\n <tr>\n <th scope=\"row\">50-59 ans</th>\n <td>${department.properties.metrics[59].n_tot_dose1.toLocaleString()} (${department.properties.metrics[59].rate_dose1} %)</td>\n <td>${department.properties.metrics[59].n_tot_complet.toLocaleString()} (${department.properties.metrics[59].rate_complet} %)</td>\n </tr>\n <tr>\n <th scope=\"row\">60-64 ans</th>\n <td>${department.properties.metrics[64].n_tot_dose1.toLocaleString()} (${department.properties.metrics[64].rate_dose1} %)</td>\n <td>${department.properties.metrics[64].n_tot_complet.toLocaleString()} (${department.properties.metrics[64].rate_complet} %)</td>\n </tr>\n <tr>\n <th scope=\"row\">65-69 ans</th>\n <td>${department.properties.metrics[69].n_tot_dose1.toLocaleString()} (${department.properties.metrics[69].rate_dose1} %)</td>\n <td>${department.properties.metrics[69].n_tot_complet.toLocaleString()} (${department.properties.metrics[69].rate_complet} %)</td>\n </tr>\n <tr>\n <th scope=\"row\">70-74 ans</th>\n <td>${department.properties.metrics[74].n_tot_dose1.toLocaleString()} (${department.properties.metrics[74].rate_dose1} %)</td>\n <td>${department.properties.metrics[74].n_tot_complet.toLocaleString()} (${department.properties.metrics[74].rate_complet} %)</td>\n </tr>\n <tr>\n <th scope=\"row\">75-79 ans</th>\n <td>${department.properties.metrics[79].n_tot_dose1.toLocaleString()} (${department.properties.metrics[79].rate_dose1} %)</td>\n <td>${department.properties.metrics[79].n_tot_complet.toLocaleString()} (${department.properties.metrics[79].rate_complet} %)</td>\n </tr>\n <tr>\n <th scope=\"row\">80 ans et +</th>\n <td>${department.properties.metrics[80].n_tot_dose1.toLocaleString()} (${department.properties.metrics[80].rate_dose1} %)</td>\n <td>${department.properties.metrics[80].n_tot_complet.toLocaleString()} (${department.properties.metrics[80].rate_complet} %)</td>\n </tr>\n <tr>\n <th scope=\"row\">Total</th>\n <td>${department.properties.metrics[0].n_tot_dose1.toLocaleString()} (${department.properties.metrics[0].rate_dose1} %)</td>\n <td>${department.properties.metrics[0].n_tot_complet.toLocaleString()} (${department.properties.metrics[0].rate_complet} %)</td>\n </tr>\n </tbody>\n </table>`;\n layer.bindPopup(content);\n }\n }", "function Expt() {\r\n}" ]
[ "0.6486069", "0.63386065", "0.63386065", "0.60748994", "0.6049459", "0.5824524", "0.57694054", "0.5757857", "0.5685926", "0.56495374", "0.56013", "0.55910856", "0.55881536", "0.55745596", "0.5559892", "0.5559312", "0.5532589", "0.5532413", "0.5529554", "0.5506044", "0.55054885", "0.5501966", "0.54840004", "0.5479654", "0.5472894", "0.54511535", "0.54378885", "0.5436509", "0.5420941", "0.5420499", "0.5414712", "0.5410647", "0.5409588", "0.5395223", "0.53845894", "0.53841704", "0.538373", "0.53789395", "0.5378482", "0.5377828", "0.53745383", "0.5371837", "0.5356263", "0.5347875", "0.53477603", "0.53469855", "0.5340252", "0.5324648", "0.532214", "0.5319579", "0.53157777", "0.5298551", "0.5298229", "0.5291171", "0.52868533", "0.527673", "0.52722156", "0.52645427", "0.5262859", "0.52586406", "0.5258377", "0.5257426", "0.525588", "0.52504873", "0.5244043", "0.52358097", "0.5233554", "0.52319616", "0.5229325", "0.5229325", "0.5227931", "0.52274376", "0.52232975", "0.5215746", "0.521381", "0.5209066", "0.52089804", "0.5203433", "0.520133", "0.52008605", "0.520025", "0.519926", "0.51876265", "0.51875436", "0.5187275", "0.5182856", "0.518007", "0.51786023", "0.51770145", "0.5173027", "0.51727384", "0.517147", "0.5170431", "0.5168551", "0.5166343", "0.516568", "0.5164775", "0.51637125", "0.51620877", "0.5158432" ]
0.52752507
56
Checks to see if player has revealed all of the letters in the active phrase
checkForWin() { const shown = document.getElementsByClassName('letter'); const shownArr = [...shown]; for (let show of shownArr) { if (show.classList.contains('hide')) { return false; } } return true; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "checkForWin() {\r\n return this.activePhrase.phrase.split(\"\")\r\n // if any letter in the phrase hasn't been guessed, allLettersGuessed\r\n // will be false from that point on, and false will be returned.\r\n // if all letters of the phrase have been guessed, they'll all be in\r\n // this.guessedLetters, and truth will be maintained;\r\n .reduce((allLettersGuessed,currentLetter) => {\r\n return (this.guessedLetters[currentLetter] || false) && allLettersGuessed\r\n },true);\r\n }", "checkForWin(){\n let unguessedLetters = 0; \n for(let c = 0; c < this.activePhrase.phrase.length; c++){\n if(phraseSection.firstElementChild.children[c].classList.contains('hide')){\n unguessedLetters ++;\n } \n } \n if(unguessedLetters === 0){\n return true;\n } \n }", "checkForWin() {\n const noSpacesArray = game.activePhrase.phraseArray.filter(\n (character) => character !== \" \"\n );\n return matchedLetterList.length === noSpacesArray.length;\n }", "checkForWin(){\r\n revealedLetters = document.querySelectorAll('.show')\r\n let phraseNoSpaces = splitPhraseArray.filter( char => char !== ' ')\r\n if(revealedLetters.length === phraseNoSpaces.length){\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n}", "checkForWin() {\n let unsolvedLetters = 0;\n\n for (let i = 0; i < phraseLetters.length; i++) {\n phraseLetters[i].className == `hide letter ${ phraseLetters[i].textContent }` ? \n unsolvedLetters++ : unsolvedLetters = unsolvedLetters;\n }\n\n return unsolvedLetters === 0;\n }", "checkLetter(guessedletter) {\r\n let activePhr = game.activePhrase.toLowerCase();\r\n const phraseLetterArray = activePhr.split(\"\").filter(i => i != \" \");\r\n let letterWasCheacked = phraseLetterArray.includes(guessedletter);\r\n return letterWasCheacked;\r\n }", "checkLetter(keyClicked) {\r\n if (this.phrase.includes(keyClicked)) {\r\n console.log('Yeah bitch');\r\n return true;\r\n } else {\r\n console.log('No Bitch');\r\n return false;\r\n }\r\n }", "checkForWin() {\r\n const activeLetters = this.activePhrase.phrase.split('');\r\n const selectedLetter = document.querySelectorAll(`li.show.letter`);\r\n\r\n for (let i = 0; i < activeLetters.length; i++) {\r\n if (activeLetters[i] === ' ') {\r\n activeLetters.pop(activeLetters[i]);\r\n }\r\n }\r\n\r\n for (let i = 0; i < activeLetters.length; i++) {\r\n if (selectedLetter.length === activeLetters.length) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }\r\n }", "function testWin() {\n var hasLetters = false;\n\n for (var i = 0; i < guitarist.length; i++) {\n\n if (goodGuess.includes(guitarist.toLowerCase().charAt(i)) || (guitarist.charAt(i) === \" \")) {\n hasLetters = true;\n } else {\n hasLetters = false;\n }\n\n if (hasLetters === false) {\n if (numGuess === 0) {\n displayMessage('You lose, click \"Start\" to try again :(');\n document.querySelector(\"#wordLetters\").innerHTML = guitarist;\n return true;\n }\n return false;\n } \n\n }\n \n if (hasLetters === true) {\n displayMessage('You win!, click \"Start\" to play again :)');\n return true;\n }\n\n\n}", "function checkGuessedLetters() {\n //This is checking that if users guess is in alailableLetters\n if(availableLetters.indexOf(this.event.key) > -1) {\n //Looping through guessed letters for the length of word\n for(var i = 0; i < word.length; i++) {\n //If the users guess has already been guessed then we will set guessed to true\n if(this.event.key === guessedLetters[i]) {\n guessed = true;\n }\n }\n }\n}", "function isRepeat() {\n var i = 0;\n for (i = 0; i < lettersUsed.length; i++) {\n if (userGuess.toUpperCase() === lettersUsed[i].toUpperCase()) {\n feedBackText.textContent = \"This letter was already used. Please make another selection.\";\n return true;\n }\n }\n return false;\n }", "lldisplayAllVowels() {\r\n if (this.checkIfVowelsAllRevealed()) {\r\n console.log(\"\\nAll vowels have been revealed already!\");\r\n }\r\n else {\r\n for (let i = 0; i < this.text.length; i++) {\r\n if (this.lettersToGuess.includes(this.text.charAt(i)) && Utilities.vowels.includes(this.text.charAt(i))) {\r\n this.performGuessSuccess(this.text.charAt(i));\r\n }\r\n }\r\n this.displayLetters();\r\n }\r\n }", "gameOver() {\n const {matchedKeys, letter, error} = this.state;\n let goodLetters = 0;\n letter.forEach((element) => {\n if (matchedKeys.includes(element)) goodLetters++;\n });\n if (goodLetters === letter.length) return 'won';\n if (error >= 10) return 'loose';\n else return 'playing';\n }", "checkLetter(letter) {\n let hasMatch = false;\n //loop through each phrase letter\n for (let i = 0; i < this.phrase.length; i++){\n if (this.phrase[i] === letter) {\n this.showMatchedLetter(letter);\n hasMatch = true;\n }\n }\n return hasMatch;\n }", "checkForWin() {\n const hiddenLetters = document.getElementsByClassName(\"hide letter\"); //Total hidden litters which are set by Phrase class\n if (hiddenLetters.length > 0) {\n //if more than zero, not winning yet if 0 return true and player won\n return false;\n } else {\n return true;\n }\n }", "checkLetter(letter) { //Checks to see if the letter selected by the player matches a letter in the phrase.\r\n console.log('in checkLetter method'); \r\n console.log(letter);\r\n console.log(\"in the phrase.checkLetter method\");\r\n let phraseCharactersArray = this.phrase.split(''); //converts phrase to array\r\n console.log(phraseCharactersArray);\r\n return phraseCharactersArray.includes(letter);\r\n \r\n // phraseCharactersArray.forEach(character => {\r\n // if (character === letter) {\r\n // return true;\r\n // } else {\r\n // return false;\r\n // }\r\n // });\r\n }", "checkForWin(){\r\n if(show.length === letters.length){\r\n return true;\r\n }\r\n }", "checkLetter(letter) {\n let compareLetter = chosenWord.includes(letter)\n console.log('Chosen letter: ' + letter)\n if (compareLetter === true) {\n var numCorrectLetters = $('.spaceLetter[data-letter=\"' + letter + '\"]')\n .length\n this.correctLetters += numCorrectLetters\n\n if (this.correctLetters === chosenWord.length) {\n setTimeout(function() {\n alert('You won!')\n }, 300)\n setTimeout(function() {\n location.reload()\n }, 2000)\n }\n $('*[data-letter=\"' + letter + '\"]').removeClass('hidden')\n } else {\n this.turnsRemaining -= 1\n console.log('Turns Remaining:' + this.turnsRemaining)\n this.drawBodyPart()\n }\n }", "checkLetter(target){\n if (this.phrase.includes(target)) {\n return true;\n } else {\n return false;\n }\n }", "checkIfVowelsAllRevealed() {\r\n let allVowelsRevealed = true;\r\n for (let letterToGuess of this.lettersToGuess) {\r\n if (Utilities.vowels.includes(letterToGuess)) {\r\n allVowelsRevealed = false;\r\n break;\r\n }\r\n }\r\n return allVowelsRevealed;\r\n }", "function checkSolved(selection) {\n notGuessed=0;\n selection.letters.forEach(function(element) {\n \n if(element.guessed===false) {\n notGuessed++\n }\n\n })\n}", "checkLetter(letter) {\r\r // Loop through the phrase text and if the letter matches\r // the phrase text at index j, return true\r for (let j = 0; j < this.phrase.length; j++){\r\r\n if (this.phrase[j] == letter)\r\n return true;\r\n }\r\r // No match, return false\r return false;\r }", "checkLetter(letter) {\r\n // console.log(`in checkLetter()`);\r\n // console.log(`letter clicked: ${letter.textContent}`);\r\n // console.log(`phrase is: ${this.phrase}`);\r\n const selectedPhrase = this.phrase;\r\n // console.log(`selected phrase is: ${selectedPhrase}`);\r\n let selectedLetter = letter.textContent;\r\n // console.log(`letteris: ${selectedLetter}`);\r\n\r\n //check to see if letter is included in the phrase\r\n // console.log(`checkLetter: ${selectedPhrase.includes(selectedLetter)}`);\r\n return selectedPhrase.includes(selectedLetter);\r\n }", "checkLetter(e) {\n\t\tthis.letterGuess = e.toLowerCase();\n\t\tthis.regexText = /[A-Za-z]/.test(this.letterGuess);\n\t\tif (this.regexText) {\n\t \t\tlet thisPhrase = this.phrase.toString();\n\n\t\t\t//Append letters to Letter CheckArray\n\t\t\tif (this.letterGuesses.includes(this.letterGuess)) {\n\t\t\t\talert(\"You've already used that letter!\")\n\t\t\t} else {\n\t\t\tthis.letterGuesses.push(this.letterGuess);\n\t\t\t}\n\n\t\t\tif (this.phrase.includes(this.letterGuess)) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else {\n\t\t\talert(\"Please only use letters!\");\n\n\t\t}\n\t}", "function checkLetter() {\n if (validKeys.indexOf(currentGuess) > -1) {\n if ((secretPhrase.indexOf(currentGuess) > -1)) {\n for (var i = 0; i < secretPhrase.length; i++) {\n if (phraseArray[i] === currentGuess) {\n blankArray[i] = currentGuess;\n spanSecretRandom.innerHTML = blankArray.join(\" \");\n }\n }\n } else {\n lettersGuessed.push(currentGuess);\n spanLettersGuessed.innerHTML = lettersGuessed.join(\" \");\n numGuesses--;\n numGuesses <= 0 ? spanNumGuesses.innerHTML = 0 : spanNumGuesses.innerHTML = numGuesses;\n }\n } else {\n alert(\"Please guess a valid letter\");\n }\n}", "function checkLetter(letter)\n{\n\tvar isInWord;\n\tfor (i = 0; i < targetWordArray.length; i++)\n\t{\n\t\tif(letter == targetWordArray[i])\n\t\t{\n\t\t\tisInWord = true;\n\t\t\treplaceLetter(letter);\n\t\t\tcorrectLetters.push(letter);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tisInWord = false;\n\t\t}\n\t}\n\tif(isInWord === false)\n\t{\n\t\twrongLetters.push(letter);\n\t\tremainingGuesses = remainingGuesses - 1;\n\t}\n\telse\n\t{\t\n\t}\n\tdocument.getElementById(\"array-box\").innerHTML = displayWord.join(\"\");\n}", "checkForWin() {\n //console.log('The phrases property: ', this.phrases);\n //const arrayActivePhrase = this.phrases.map(item => item.phrase);\n\n //select all the letters in the activePhrase with a class name 'hide'\n const phraseLetterDomNodes = document.querySelectorAll(\"div#phrase ul li\");\n\n const hiddenPhraseLettersDomNodes = [...phraseLetterDomNodes].filter(item => item.classList.contains(\"hide\"));\n\n const hiddenPhraseLetters = hiddenPhraseLettersDomNodes.map(hiddenNode => hiddenNode.textContent);\n \n // //selects all the letters in the activePhrase with a class name 'show'\n // const shownPhraseLettersDomNodes = [...phraseLetterDomNodes].filter(item => item.classList.contains(\"show\"));\n // const shownPhraseLetters = shownPhraseLettersDomNodes.map(hiddenNode => hiddenNode.textContent);\n\n\n console.log(\"The hidden list items: \", hiddenPhraseLettersDomNodes, hiddenPhraseLetters)\n //console.log(\"The shown list items: \", shownPhraseLettersDomNodes, shownPhraseLetters)\n //if the hidden letters length equals to the activePhrase letters length\n if (hiddenPhraseLetters.length > 0) {\n //keep the game going\n return false;\n //if the shown letters length equals to the activePhrase letters lenght\n } else {\n //stop the game, the usr has won\n return true;\n }\n }", "checkLetter(e){\n const phraseJoin = this.phrase.join('');\n return phraseJoin.includes(e.toLowerCase()) ? true : false;\n }", "function checkLetters() {\n //If no - add letter to guessed letters array\n if ((remainingGuesses - lettersGuessed.length) > 0 && (lettersGuessed.indexOf(playerGuess) == -1)) {\n lettersGuessed.push(\" \" + playerGuess);\n document.getElementById(\"lettersGuessed\").innerHTML = lettersGuessed.join(\" \");\n\n //Check to see if letter is in word\n //If yes - replace dash with letter in the appropriate position\n for (k = 0; k < currentWord.length; k++) {\n if (currentWord[k] == playerGuess) {\n guessingWord[k] = \" \" + playerGuess + \" \";\n document.getElementById(\"currentWord\").textContent = guessingWord.join(\"\");\n }\n //If no - decrement Number of Guesses by 1\n else {\n document.getElementById(\"remainingGuesses\").innerHTML = remainingGuesses - lettersGuessed.length;\n }\n };\n };\n }", "function reveal(guess) {\n for (var z = 0; z < word.length; z++) {\n if (word[z] == guess) {\n context.fillText(word[z], (100 + (z * 20)), 490);\n lettersRemaining--;\n console.log(\"reveal: \" + lettersRemaining);\n }\n }\n }", "checkLetter(letter) {\n\n let letterContained = false;\n\n for (let i = 0; i < this.phrase.length; i++) {\n if (this.phrase[i] === letter) {\n letterContained = true;\n }\n }\n\n return letterContained;\n }", "function answerCheck() {\n\tgameWordDisplay = \"\"; \n\n//loops through the game word \nfor (var i = 0; i < gameWord.length; i++) {\n\n\t//check the letters guessed by the user agains each position of the game word\n\tif (guessedLetters.includes(gameWord.charAt(i))) {\n\n\t\t//if the letter is there, displays it at the position\n\t\tgameWordDisplay += gameWord.charAt(i);\n\t\t//if not, replaces the display with _ _ _\n\t} else {\n\t\tgameWordDisplay += \"_\";\n\n\t}\n}\n}", "function checkStatus() {\n if (guessesLeft === 0) {\n gameStart = false;\n loss++;\n failure.textContent = loss;\n guessedLetters.textContent = \"Sorry, the mighty sea got you this time. Try again\"\n\n\n } else if (word.toLowerCase() === chosenWordArray.join(\"\").toLowerCase()) {\n gameStart = false;\n win++;\n victory.textContent = win;\n guessedLetters.textContent = \"You are victorious! Your place in Valhalla is all but insured.\"\n }\n}", "function checkforMatch(f) {\n if (inputWord.length === 0) {\n let modalText = document.querySelector(\".modal__text\");\n modalBox.style.display = \"flex\";\n modalText.innerText = `Pick a word first!`;\n }\n if (inputWord.indexOf(f) === -1) {\n console.log(\"incorrect\");\n gunshot.play();\n wrongLetters.push(f);\n counter++;\n guessesLeft--;\n guessCounter.innerText = `Guesses Left: ${guessesLeft}`;\n imageLoop.setAttribute(\"src\", imagesArr[counter]);\n document\n .querySelector(\"[data-letter=\" + f + \"]\")\n .classList.add(\"letter_no\");\n if (counter === 8) {\n let modalText = document.querySelector(\".modal__text\");\n let fullWord = inputWord.join(\"\");\n modalBox.style.display = \"flex\";\n modalText.innerText = `You Lost! The correct word was ${fullWord}`;\n }\n return;\n }\n console.log(\"correct letter\");\n document.querySelector(\"[data-letter=\" + f + \"]\").classList.add(\"letter_yes\");\n addLetters(f);\n}", "function checkLetter() {\n document.onkeyup = function (event) {\n guess = event.key.toLowerCase();\n var found = false;\n for (i = 0; i < word.length; i++) {\n if (guess === word[i]) {\n letters[i] = guess;\n document.getElementById(\"answer\").innerHTML = letters.join(\" \");\n found = true;\n }\n }\n //wrong letters put in wrongLetters array and are shown on screen\n if (found) return;\n if (wrongLetters.indexOf(guess) < 0) {\n wrongLetters.push(guess);\n document.getElementById(\"wrongGuesses\").innerHTML = wrongLetters.join(\" \");\n //every wrong guess -1 from the counter\n counter--;\n console.log(counter);\n document.getElementById(\"counter\").innerHTML = counter;\n \n //+1 to the wins if player guesses correrct\n if (counter > 0 && letters.join(\" \") == word) {\n document.getElementById(\"wins\").innerHTML = wins + 1;\n console.log(wins);\n confirm(\"YOU WIN! Would You Like To Play Again?\");\n wins++;\n counter = 10;\n letters= i ;\n wrongLetters = [];\n start();\n };\n\n //when counter reaches 0 it's Game Over\n if (counter === 0) {\n document.getElementById(\"losses\").innerHTML = losses + 1;\n console.log(losses);\n confirm(\"YOU LOSE! Would You Like to Playe again Play again?\"); {\n losses++;\n counter = 10;\n letters = i;\n wrongLetters = [];\n start();\n }\n\n }\n }\n }\n}", "function checkLetter()\n { \n //verify if the letter was an incorrect guess \n if (movie.indexOf(letter) === -1) {\n letter = event.key.toUpperCase();\n wrongGuesses.push(letter); \n //if incorrect guess join letter to wrongGuesses array \n document.getElementById('lettersWronglyGuessed').innerHTML = wrongGuesses.join(' ');\n //display number of guesses remaining and decrement allottedGuesses counter\n document.getElementById('guessesRemaining').innerHTML = allottedGuesses--\n } else {\n //if not incorrect check to see if it is a correct letter \n for (i = 0; i <movie.length; i++) {\n if (movie[i] === letter) {\n answerArray[i] = letter; \n }\n //if correct join the movie to the currentMovie span and display the letter\n document.getElementById(\"currentmovie\").innerHTML = answerArray.join(' ');\n } \n\n }\n //go to checkIfWon function to check if the player has won \n checkIfWon(); \n}", "function whenUserGuesses () {\n if (currentWord.alreadyPressedLetters.includes(userKey) && userWon === false && userLost === false) {\n $(\".already-pressed\").empty().append('You already guessed \"' + userKey + '\"').fadeIn(\"slow\").fadeOut(\"slow\");\n } else if (keyCode > 64 && keyCode < 91 && remainingGuesses > 0 && userWon === false) {\n $(\".guessed-letters\").append(userKey + \" \"); \n remainingGuesses -= 1;\n $(\".remaining-guesses\").empty().append(remainingGuesses);\n currentWord.alreadyPressedLetters.push(userKey);\n } \n}", "checkForWin() {\n // Get all the elements that have the class \"show\"\n const lettersShown = document.querySelectorAll('.show').length;\n // Count how many letters there are in total\n const lettersTotal = this.chosenPhrase.phrase.length;\n // Check if the total numbers of letters is the same as the total number of letters shown\n if (lettersTotal === lettersShown) {\n // Call the gameOver method with the winning message\n this.gameOver('You won! Keep on rockin!');\n }\n }", "function checkLetter(keyLetter) {\n let list = document.querySelectorAll('.letter');\n let correctLetter = false;\n \n for (let i = 0; i < list.length; i++) {\n \n let listLetter = list[i].textContent;\n \n if (listLetter === keyLetter) {\n correctLetter = true;\n list[i].classList.add('show');\n // CSS transistion added for exceed expectations\n list[i].style.transition = 'all 2s';\n } \n }\n \n if (correctLetter === false) {\n missed += 1;\n } if (missed == 1) {\n life[0].style.display = 'none';\n } if (missed == 2) {\n life[1].style.display = 'none';\n } if (missed == 3) {\n life[2].style.display = 'none';\n } if (missed == 4) {\n life[3].style.display = 'none';\n } if (missed == 5) {\n life[4].style.display = 'none';\n }\n \n return correctLetter;\n}", "function checkLetter(guess) {\n\tmatch = null;\n\tlet letters = document.querySelectorAll('.letter'); //unrevealed letters collection\n\tfor (i = 0; i < letters.length; i++) {\n\t\tif (guess.textContent == letters[i].textContent) {\n\t\t\tletters[i].classList.add('show');\n\t\t\tmatch = true;\n\t\t}\n\t}\n\treturn match;\n}", "function stageComplete() {\n\n\n document.getElementById('word-blank').innerHTML = correctLetters.join(\" \");\n document.getElementById('num-guesses').innerHTML = guessesLeft;\n document.getElementById('wrong-guesses').innerHTML = wrongLetters.join(\" \");\n\n\n console.log(lettersInword);\n console.log(correctLetters);\n if (lettersInword.join(\" \") === correctLetters.join(\" \")) {\n winningScore++;\n document.getElementById('win-counter').innerHTML = winningScore;\n startGame();\n window.setTimeout(Winner, 1000);\n } else if (guessesLeft === 0) {\n document.getElementById('loss-counter').innerHTML = losingScore++;\n document.getElementById('wrong-guesses').innerHTML = \"\";\n alert(\"Sorry no more moves left!\");\n startGame();\n }\n\n\n}", "function fillEmptyLetter(){\n\n var underline= [];\n var checkWin = word.length;\n var firstLetterValue;\n for(var i= 0; i <= word.length; i++){\n //get the letter from indice\n firstLetterValue = word.charAt(i);\n //verify the word if contains \n if(firstLetterValue == letter()){\n underline[i]= firstLetterValue;\n //count until the lenght of the word to win\n win = win +1;\n //set goodwords with the good letter\n underline.forEach((value,x ) =>{\n if(value == firstLetterValue){\n goodwords[i]= firstLetterValue;\n }\n \n //if is the same lenght the game is finished\n if(win == checkWin){\n alert('you won the game congratulations!!!, the word was ' + word);\n document.getElementById('restart').click();\n }\n })\n \n }\n }\n}", "checkLettersForGuessed() {\n // Initialize a count\n let count = 0;\n for (let i in this.array) {\n let LetterObj = this.array[i];\n // If the letter hasn't been guessed yet increase count\n if (!LetterObj.guessed) {\n count++;\n }\n }\n // If there are still unguessed letters, return true. If all letters have been guessed return false.\n if (count > 0) {\n return true;\n } else {\n return false;\n }\n }", "function isInWord() {\n //gets the first position of the letter value in the word\n pos = word.indexOf(guess);\n //check to see if the letter is in the word\n if (word.indexOf(guess) > -1 ) { \n //if letter is in the word, enter the letter into the word array and html \n enterLetters(); \n\n //function wordSolved to see if the word is solved and if anyone won and to switch players\n wordSolved(); \n\n\n } else {\n //the letter is not in the word\n document.getElementById('audio').play();\n hangTheMan();\n };\n}", "function isCorrectGuess(letter) {\n //if false, this should also decrement lives\n if (!currentWordArray.includes(letter)) {\n livesRemaining -= 1;\n gameEnding.innerHTML = \"Lives Remaining: \" + livesRemaining;\n wrongLetters.push(letter);\n displayWrongLetterBank();\n } else {\n remainingLetters -= 1;\n displayStatus(currentWord)\n }\n}", "function Incorrect(letter){\n if (\n ChosenWordarr.indexOf(letter.toLowerCase()) === -1 \n && \n ChosenWordarr.indexOf(letter.toUpperCase()) === -1\n ){\n guessesLeft--;\n IncorrectGuesses.push(letter);\n LettersGuessed.innerHTML = IncorrectGuesses.join(' ');\n RemainingGuesses.innerHTML = guessesLeft;\n Destroy();\n }\n \n Loss();\nGameOver();\n }", "checkLetter(letter) {\r\n let keyboard = document.getElementById('qwerty');\r\n //check if button is clicked\r\n if (this.phrase.includes(letter)) {\r\n return true;\r\n // console.log(true)\r\n // this.showMatchedLetter(letter)\r\n } else {\r\n return false;\r\n }\r\n }", "checkLetter(){\n /** will correctly match if letter is on the current phrase**/\n let matched = this;\n let phraseLi = document.getElementById(\"phrase\").getElementsByTagName(\"li\");\n $('.keyrow button').bind('click', function(){\n for (var i = 0; i < phraseLi.length; i++) {\n if ($(this).text() === phraseLi[i].innerHTML) {\n $(this).addClass(\"phraseLetters\");\n phraseLi[i].classList.add(\"correct\");\n matched.showMatchedLetter();\n }\n }\n })\n }", "checkForWin(){\n const $hidenLetters = $('#phrase .hide');\n if($hidenLetters.length === 0){\n return true;\n }\n return false;\n }", "checkLetter(letterToCheck) {\n\n let checkForMatch = 0;\n\n for (let i = 0; i < this.phrase.length; i++) {\n if (letterToCheck === this.phrase[i].toLowerCase()) {\n checkForMatch++\n }\n }\n if (checkForMatch > 0) {\n return true;\n } else {\n return false;\n }\n }", "function validateLetter (usersKeypress) {\n message.innerText = \"\";\n\n var repeatGuess = lettersGuessed.some(function(item){\n return item === usersKeypress;\n })\n\n //alert player if the above code is true.\n if (repeatGuess) {\n //alert(usersKeypress + \" already guessed. Try again!\");\n message.innerHTML = \"<span class='duplicateMessage'>Already guessed that. Try again!</span>\";\n\n //if it is not a repeat guess, check if it's in word\n } else {\n lettersGuessed.push(usersKeypress);\n console.log(\"Guessed so far\", lettersGuessed);\n\n //show user's input in browser\n showLettersGuessed();\n //is user's input a match to computer guess\n guessMatch(usersKeypress);\n }\n\n}", "function checkLetter(arr) { \n let buttonClicked = arr;\n let phraseLetters = document.getElementsByClassName('letter');\n let letterMatched = null;\n\n for (let i = 0; i < phraseLetters.length; i += 1) {\n if (buttonClicked.toUpperCase() === phraseLetters[i].textContent.toUpperCase()) { \n phraseLetters[i].className += ' show';\n letterMatched = buttonClicked;\n }\n }\n\n return letterMatched;\n}", "function isKeyInWord() {\n var isinword = false;\n\n // Compare the KEYINPUT with the characters of the word\n for (var i = 0; i < word.length; i++) {\n if (keyinput == word[i]) {\n isinword = true;\n // Replace the guessed character in GUESS\n guess[i] = keyinput;\n }\n }\n\n // If KEYINPT is not a match increase a bad guess and remove a life\n if (!isinword) {\n $(\".audioDoh\").trigger('play');\n lives--;\n badguess++;\n if (lives < 1) {\n matchesLost++;\n gamedone = true;\n }\n }\n\n // Update the labels\n updateGame();\n }", "function checkRepeat(userGuess) {\n if (userGuesses.includes(userGuess) || hiddenWord.includes(userGuess)) {\n console.log('REPEAT');\n } else {\n // If it's a fresh letter we check for a match\n checkMatch(userGuess);\n }\n}", "showMatchedLetter(letter){\r\n $(letter).addClass('show');\r\n // display the char of the corresponding letters check if game is won\r\n }", "checkForWin() {\n const letters = document.getElementById('phrase').querySelector('ul').querySelectorAll('li');\n let result = true;\n for (let i = 0; i < letters.length; i++) {\n if (!letters[i].classList.contains(\"matched\") && !letters[i].classList.contains(\"space\")) {\n result = false;\n }\n }\n return result;\n }", "function checkLetter(event) {\n var userGuess = event.key.toLowerCase();\n if ($(\"#loseModal\").css(\"display\") !== \"block\" && $(\"#winModal\").css(\"display\") !== \"block\") {\n if ((event.which >= 65 && event.which <= 90) || ((event.which >= 97 && event.which <= 122)) && (guesses.indexOf(userGuess) == -1)) { \n guesses.push(userGuess);\n guessMatch(userGuess);\n appearLetters(indexChecker, userGuess);\n }\n winOrLose(winCounter, lives);\n indexChecker = [];\n }\n}", "function checkWord() {\n for (i = 0; i < answer.length; i++) {\n if (guess === answer[i] && letterInWord === false) {\n emptyWord[i] = String.fromCharCode(event.keyCode).toLowerCase();\n document.getElementById(\"empty-word\").innerHTML = emptyWord.join(\" \");\n countBlank -= 1;\n }\n }\n if (guess != answer[i]) {\n lives -= 1;\n }\n console.log(countBlank);\n }", "checkLetter(letter)\r\n {\r\n // get the index of the letter in the phrase (-1 if not found)\r\n\r\n let foundIndex = this.phrase.indexOf(letter);\r\n\r\n // if not found\r\n\r\n if (foundIndex === -1) \r\n {\r\n // return false\r\n\r\n return false;\r\n } \r\n else \r\n {\r\n // if found show the letters on the phrase area and return true\r\n //this.showMatchedLetter(letter);\r\n return true;\r\n }\r\n\r\n }", "function checkLetter(button) {\n let phraseElements = document.querySelectorAll('li.letter');\n let match = false;\n for(let i = 0; i < phraseElements.length; i++) {\n if (phraseElements[i].textContent.toUpperCase() === button.textContent.toUpperCase()) {\n phraseElements[i].classList.add('show');\n match = true;\n }\n }\n return match;\n}", "function checkUserGuess() {\n /*if user choice doesn't exist in the array of prior picks, and doesn't exist in the array of the letters of the wordToGuess, then reduce guessesLeft by one and play sound. Verify if the user's choice was a letter in the alphabet, if not ignore it. */\n if (printWord.indexOf(userGuess) < 0 && guessesMade.indexOf(userGuess) < 0 && letters.indexOf(userGuess) >= 0) {\n guessesLeft--;\n var audio = new Audio (\"assets/audio/mp3.mp3\");\n audio.play();\n }\n // add all alphabetic guess to guessesMade if not already there\n if (guessesMade.indexOf(userGuess) < 0 && letters.indexOf(userGuess) >= 0) {\n guessesMade[guessesMade.length]=userGuess;\n }\n\n //if userGuess exists in the array then change is associated array pair from false to true\n for (var i = 0; i < printWord.length; i++) {\n if (printWord[i] === userGuess) {\n // if the letter wasn't already guessed then play audio\n if (printWord[i+1] == false) {\n var audio = new Audio(\"assets/audio/mp3b.mp3\");\n audio.play();\n }\n printWord[i+1] = true;\n }\n }\n}", "function checkLetter(guess) {\n const letterAnswers = document.querySelectorAll('.letter');\n const li = document.querySelectorAll('.letter');\n let match;\n for (let i = 0; i < letterAnswers.length; i +=1) {\n let show = letterAnswers[i].textContent;\n if (show === guess) {\n li[i].classList.add('spin');\n li[i].className += ' show';\n match = show;\n }\n }\n return match;\n }", "function checkWin() {\n let show = document.querySelectorAll('.show');\n let letter = document.querySelectorAll('.letter');\n let next = getRandomPhraseArray(phrases);\n if (show.length === letter.length ) {\n overlay.className = 'win';\n overlay.style.display = 'flex';\n title.textContent = 'Well done, you won!'\n button.textContent = 'Play again?';\n } else if (missed === 5) {\n overlay.className = 'lose';\n overlay.style.display = 'flex';\n title.textContent = 'Oops you lost!'\n button.textContent = 'Play again?';\n }\n\n startBtn.addEventListener('click', (event) => {\n missed = 0;\n UL.textContent = '';\n overlay.style.display = 'none';\n for (let i = 0; i < heart.length; i+= 1) {\n heart[i].src = 'images/liveHeart.png';\n }\n for (i = 0; i < keyboardButton.length; i+= 1) {\n keyboardButton[i].removeAttribute('class');\n keyboardButton[i].removeAttribute('disabled');\n }\n addPhraseToDisplay(next);\n });\n}", "function checkWin () {\n const showLetters = document.getElementsByClassName('show');\n const letters = document.getElementsByClassName('letter');\n const totalShownLetters = showLetters.length;\n const totalLetters = letters.length;\n\n if (missed > 4) {\n winOrLose('lose');\n } else if (totalShownLetters === totalLetters) {\n winOrLose('win');\n } \n}", "function checkLetter (letter){\r\n var letterInSong = false; \r\n\r\n for (var i = 0; i < underscores; i++){\r\n if(chosenWord [i] === letter){\r\n letterInSong = true; \r\n }\r\n }\r\n if (letterInSong){\r\n for ( i = 0; i < underscores; i++){\r\n if(chosenWord [i] === letter){\r\n rightGuesses[i] = letter; \r\n }\r\n }\r\n }\r\n else{\r\n numGuesses --;\r\n wrongGuesses.push(letter)\r\n }\r\n\r\n\r\n// once you guess one song\r\ndocument.getElementById(\"wordBlank\").innerHTML = rightGuesses.join(\" \");\r\ndocument.getElementById(\"attemptsLeft\").innerHTML = numGuesses.join(\" \");\r\ndocument.getElementById(\"wrongGuess\").innerHTML = wrongGuesses.join(\" \");\r\n\r\nconsole.log(letterInWord);\r\nconsole.log(rightGuesses);\r\n\r\nif(letterInWord.join(\" \") === rightGuesses.join(\" \")){\r\n winCounter++;\r\n alert (\"YOU WIN\");\r\n document.getElementById(\"winCounter\").innerHTML = winCounter;\r\n startGame();\r\n}\r\nelse if(numGuesses === 0){\r\n document.getElementById(\"lossCounter\").innerHTML = lossCounter++;\r\n document.getElementById(\"wrongGuess\").innerHTML = \"\";\r\n alert (\"You lost... try again!\");\r\n startGame();\r\n}\r\n}", "function winLose() {\n if(randomWord.length === correctLetters.length) {\n alert ('You won!');\n document.getElementById('button').disabled = true;\n document.getElementById('guessed-letters').textContent = 'CONGRATULATIONS! YOU WON!';\n\n } else {\n if(maxTries === 0) {\n alert('You lose!');\n document.getElementById('button').disabled = true;\n }\n }\n}", "checkLetter(letter){\r\n if( this.phrase.indexOf(letter) > -1 ){\r\n this.showMatchedLetter(letter);\r\n return true; \r\n }\r\n }", "function addCorrectLetter(letter) {\n for (var i = 0; i < character.length; i++) {\n // If current letter(input) has already been pressed\n if (letter.key === character[i]) {\n // change letter inputed to uppercase\n answerArray[i] = letter.key.toUpperCase();\n currentWordDisplay();\n //reduce letters left remaining to guess by 1\n lettersRemaining--;\n console.log(\"letters Remaning: \" + lettersRemaining);\n //if letters left to guess are equal to 0 \n if (lettersRemaining === 0) {\n winScore++;\n displayWinCount();\n alert(\"YOU WON!!!\");\n restartGame();\n\n\n }\n }\n }\n}", "function checkMatch(userGuess) {\n\n // Runs if the user selected a matching letter\n if (lettersToGuess.includes(userGuess)) {\n console.log(\"bingo\");\n\n // This will check the matching letter and replace it in the hidden word\n for (let i = 0; i < numLetters; i++) {\n if (userGuess === lettersToGuess[i]) {\n\n hiddenWord[i] = userGuess;\n document.querySelector('#hiddenWord').innerHTML = hiddenWord;\n\n // This is used in order to determine if all letters have been matched\n numMatches++;\n\n console.log(\"It's a match\");\n console.log(hiddenWord);\n } \n }\n // Runs if the user selected a non-matching letter\n } else {\n // Decrease number of remaining guesses\n numGuesses--;\n\n // Add the user's guess to the non-matching guesses and rewrite info to the screen\n userGuesses.push(userGuess);\n document.querySelector('#userGuesses').innerHTML = 'Guesses: ' + userGuesses;\n document.querySelector('#numGuesses').innerHTML = 'Guesses Left: ' + numGuesses;\n\n console.log(userGuesses);\n console.log('numGuesses: ' + numGuesses);\n }\n\n // Runs after each match or mismatch to determine if the game has been won or lost\n checkWinLoss();\n}", "function checkAnswer(guess) {\n console.log(\"Checking guess: \" + guess);\n\n // Clear the answer field\n window.answerTextField.value = \"\";\n\n // Re-focus the answer field\n window.answerTextField.focus();\n\n if ( window.gameMode == \"anagram\") {\n if ( guess.toLowerCase() == window.currentWord.toLowerCase() ) {\n console.log(\"Correct\");\n return true;\n }\n else {\n console.log(\"Incorrect\");\n return false;\n }\n }\n else {\n if ( window.correctLetters.includes(guess) ) {\n console.log(\"Correct\");\n return true;\n }\n else {\n console.log(\"Incorrect\");\n return false;\n }\n }\n\n}", "function checkLetters(userkey) {\n\n\t//See if the userkey exists in the wrong guesses array\n\tvar letterExist = false;\n\n\tfor (var i = 0; i < wrongGuesses.length; i++) {\n\n\t\tif(userkey === wrongGuesses[i]){\n\n\t\t\tletterExist = true;\n\n\t\t};\n\n\t};\n\n\tif (letterExist === false) {\n\n\t\tvar flag = false;\n\n\t\tfor (var i = 0; i < numBlanks; i++) {\n\t \t\n\t \t\tif(randomWord[i] === userkey) {\n\t \t\t\tflag = true;\n\t \t\t}\n\t \t}\n\n\n\t\t// If the letter exists somewhere in the word, then figure out exactly where (which indices).\n\t\tif (flag) {\n\n\t\t // Loop through the word.\n\t\t for (var i = 0; i < numBlanks; i++) {\n\n\t\t //If the first letter equals the user's input, make it capitalized\n\t\t\t\tif (randomWord[0] === userkey) {\n\n\t\t\t\t\tlettersInWord[0] = userkey.toUpperCase();;\n\n\t\t\t\t} \n\n\t\t\t\t//Else set the specific space in blanks and letter equal to the letter when there is a match.\n\t\t\t\telse if(randomWord[i] === userkey) {\n\n\t\t\t\t\tlettersInWord[i] = userkey\n\n\t\t\t\t};\n\t\t }\n\t\t}\n\n\t\t // If the letter doesn't exist at all...\n\t\telse {\n\n\t\t // ..then we add the letter to the list of wrong letters, and we subtract one of the guesses.\n\t\t\twrongGuesses.push(userkey);\n\n\t\t // numGuesses--;\n\t\t turns--;\n\t\t \n\t \t\tdocument.getElementById(\"turns\").innerHTML = turns;\n\t \n \t\t}\t\n\n\t roundComplete();\n\t}\n}", "function checkAnswer() {\n if (underScore.join(\"\") == chosenWord) {\n wins++;\n changeColor();\n resetWord();\n audio.play();\n } else if (guessesLeft == 0) {\n losses++;\n resetWord();\n };\n updateDomElements();\n}", "handleInteraction(){\r\n //get letter and check if its on the active phrase \r\n \r\n const matchedLetter = this.activePhrase.checkLetter(event.target.textContent);\r\n \r\n if(matchedLetter){\r\n this.activePhrase.showMatchedLetter(event.target.textContent);\r\n event.target.classList.add('chosen');\r\n event.target.disabled = 'true';\r\n this.checkForWin();\r\n // show the letter if true else remove a life \r\n }\r\n else if(!matchedLetter){\r\n if(event.target.className === 'key'){\r\n event.target.disabled = 'true';\r\n event.target.classList.add('wrong');\r\n this.removeLife();\r\n \r\n }\r\n }\r\n\r\n }", "checkLetter(letter) {\n console.log(this.phrase);\n if (this.phrase.includes(letter)) {\n return true;\n } else {\n return false;\n }\n }", "checkLetter(letter) {\n let status = false;\n for (let i = 0; i < this.phrase.length; i++) {\n if (letter === this.phrase[i].toLowerCase()) {\n status = true;\n }\n }\n return status;\n }", "checkLetter(guess) {\n for (let i = 0; i < this.phrase.length; i++) {\n if (this.phrase.charAt(i) === guess) {\n return true;\n }\n }\n }", "function checkLetter(event){\r\n\tlet howMany = 0;\r\n\tfor (var u=0; u < letters.length; u++){\r\n\t\tif(letters[u] == undefined) u++;\r\n \t\telse if(letters[u].character === event.key){howMany++;}\r\n\t\tif (howMany > 1) break;\r\n\t\t\r\n\t}\r\n\tif (howMany < 2){setScore(playerScore-2);}\r\n\telse\r\n\t{\r\n\tletters.forEach((letter)=>{if (letter.character === event.key) {\r\n\t\tsetScore(playerScore+1);\r\n\t\tletter.destroy();\r\n\t}});\r\n\thowMany = 0;\r\n\t}\r\n\t}", "function checkWin() { \n let lettersWithLetters = document.getElementsByClassName('letter');\n let lettersWithShow = document.getElementsByClassName('show');\n\n if (lettersWithShow.length == lettersWithLetters.length) {\n sectionOverlay.className = 'win';\n sectionOverlay.style.display = '';\n pageTitle.textContent = 'You won! Play again?';\n startButton.textContent = ' Play again! ';\n }\n}", "checkLetter(letter){\r\n if(this.phrase.includes(letter)){\r\n return true;\r\n }else {\r\n return false;\r\n }\r\n\r\n }", "checkLetter(selectedLetter){\n const lis = document.getElementById('phrase').querySelector('ul').children;\n let isCorrect = false;\n for(let i = 0; i < lis.length; i++){\n if(lis[i].textContent === selectedLetter){\n this.showMatchedLetter(lis[i]);\n isCorrect = true;\n }\n }\n return isCorrect;\n }", "function checkLetter() {\n const sContainer = selectElement(\".secret-word\");\n let word = secretWord.toUpperCase();\n\n //Check if word includes this letter\n if (word.includes(this.textContent)) {\n this.classList.add(\"true\");\n let indexArr = [];\n //Get all indexs where we must replace symbol\n for (let i = 0; i < secretWord.length; i++) {\n let symbol = word.indexOf(this.textContent, i);\n if (symbol != -1) {\n indexArr.push({ index: symbol });\n }\n }\n //Replace symbols\n for (let i = 0; i < indexArr.length; i++) {\n let wordSize = (+indexArr[i].index) ?\n this.textContent.toLowerCase() : this.textContent;\n sContainer.textContent = sContainer.textContent\n .replaceAt(indexArr[i].index, wordSize);\n }\n\n if (sContainer.textContent == secretWord) {\n wictoryFun();\n }\n }\n else {\n selectElement(\".hangman img\").classList.add(\"hide\");\n selectElement(\".hangman img\").src = `image/${count}.png`;\n setTimeout(() => selectElement(\".hangman img\").classList.remove(\"hide\"), 400);\n this.classList.add(\"false\");\n count++;\n if (count == 13) {\n setTimeout(overFun, 1500);\n };\n }\n this.removeEventListener('click', checkLetter);\n}", "function keyPress(){\n\n\tguessedLetters[counter] = event.key.toUpperCase();\t\n\n\tvar correct = 0;\n\tfor(var i = 0; i < randomWord.length; i++){\n\t\tif(guessedLetters[counter] == randomWord.charAt(i)){\n\t\t\thiddenLetters[i] = guessedLetters[counter];\t\n\t\t\tcorrect++;\n\t\t\t}\n\t}\n\n\n\tif(isDuplicate() !== true && (guessedLetters[counter].charCodeAt(0) >= 65 && guessedLetters[counter].charCodeAt(0) <= 90 && guessedLetters[counter].length <= 1)){\n\t\tcounter++;\n\t\tdocument.getElementById(\"hangmanTextLower\").textContent = \"Guessed Letters: \" + guessedLetters;\n\n\t\trefresh();\n\t\tifWon();\n\t\tifLost(correct);\n\t}\n}", "function roundComplete() {\n /*\n 1. Update the HTML with the letters that are in the word\n 2. Update the HTML with guesses we have left\n 3. Update the HTML to show the wrong guesses\n 4. Determine if the user won the game or not\n */\n document.getElementById(\"hiddenWord\").innerHTML = blanksAndSuccesses.join(\n \" \"\n );\n document.getElementById(\"numbers\").innerHTML = numGuesses;\n document.getElementById(\"letters\").innerHTML = wrongGuesses.join(\" \");\n\n console.log(lettersInChosenWord);\n console.log(blanksAndSuccesses);\n if (lettersInChosenWord.join(\" \") === blanksAndSuccesses.join(\" \")) {\n winCounter++;\n alert(\"You win!!\");\n document.getElementById(\"w_Number\").innerHTML = winCounter;\n startGame();\n } else if (numGuesses === 0) {\n document.getElementById(\"l_Number\").innerHTML = lossCounter++;\n document.getElementById(\"letters\").innerHTML = \" \";\n alert(\"you don't have anymore guesses left\");\n startGame();\n hangmanSlides();\n }\n}", "checkForWin() {\n //Returns false if there are any hidden letter, returns true if there are none\n return ($('#phrase ul .hide').length === 0);\n }", "checkLetter(letter) {\n return this.phrase.includes(letter.textContent);\n }", "function checkWin() {\n let letters = document.querySelectorAll(\".letter\");\n let correct = document.querySelectorAll(\".show\");\n if (letters.length == correct.length) {\n overlay.className = \"win\";\n overlay.firstElementChild.textContent = \"You Win!!\";\n overlay.style.display = \"flex\";\n startBtn.textContent = \"Play Again\";\n reset();\n } else if (missed > 4) {\n overlay.className = \"lose\";\n overlay.firstElementChild.textContent = \"Better luck next time :(\";\n overlay.style.display = \"flex\";\n startBtn.textContent = \"Play Again\";\n reset();\n }\n}", "function checkLetters(letter) {\n\t// check if letter exists in word at all\n\tvar isLetterInWord = false;\n\tfor (var i=0; i<hiddenWord.length; i++) {\n\t\tif (hiddenWord[i]===letter) {\n\t\t\tisLetterInWord= true;\n\t\t\tconsole.log('Letter found');\n\t\t}\n\t}\n\n\tif (isLetterInWord) {\n\t\t// check where in the word the letter exists\n\t\tfor (i=0; i<hiddenWord.length; i++) {\n\t\t\tif(hiddenWord[i]===letter) {\n\t\t\t\tdashes[i] = letter;\n\n\t\t\t}\n\t\t}\n\t\t$('#hiddenWord').html(dashes);\n\t} else {\n\t\twrongGuesses.push(letter+' ');\n\t\tguessesLeft--;\n\t\t$('#guessesLeft').html(guessesLeft);\n\t\t$('#wrongGuesses').html(wrongGuesses);\n\t}\n}", "drawSecretWord() {\n ctx.clearRect(0,canvas.height-40,canvas.width,40)\n GAME.secretWord.includes(PLAYER.guess) ? PLAYER.guessStatus = true : PLAYER.guessStatus = false\n for (let i = 0; i < GAME.secretWord.length; i++) {\n const element = GAME.secretWord[i];\n if(str_replace(from,to,element) === PLAYER.guess) {\n PLAYER.guessStatus = true\n GAME.answerArray[i] = element\n }\n let x = (canvas.width - ((GAME.secretWord.length * 24) + ((GAME.secretWord.length - 1) * 4))) + (i * (24 + 4))\n ctx.beginPath()\n ctx.font = \"32px calibri\"\n ctx.fillText(GAME.answerArray[i], x, canvas.height - 6)\n ctx.closePath()\n }\n }", "function checkForLetter(letter) {\n var foundLetter = false\n \n // loop through word letters\n for (var i = 0, j = hiddenWord.length; i < j; i++) {\n\n // if matching letter, assign to guessing word array\n if (letter === hiddenWord[i]) {\n wordBeingGuessed[i] = letter\n foundLetter = true\n\n // if all letters match hidden word, increase winTotal, reset game\n if (wordBeingGuessed.join(\"\") === hiddenWord) {\n winTotal++\n removePicture()\n displayPicture()\n updateDisplay()\n resetGame()\n }\n }\n }\n // if letter doesnt match, lower guessing remaining\n if (!foundLetter) {\n if (!guessedLetters.includes(letter)) {\n guessedLetters.push(letter)\n guessesRemaining--\n }\n\n // if guesses are 0, display the word and reset game\n if (guessesRemaining === 0) {\n wordBeingGuessed = hiddenWord.split()\n resetGame()\n }\n }\n\n updateDisplay()\n}", "function checkLetter(input){\n\t\t// Check if word has been used before\n\t\tvar counter = 0; // counts how many times the letter appears in the word\n\t\tfor(l=0; l< word.length; l++){\n\t\t\tvar currentGuess = input;\n\t\t\tvar currentCheck = word.charAt(l);\n\t\t\tif(currentGuess === currentCheck){\n\t\t\t\tcorrectGuesses++;\n\t\t\t\tcounter++;\n\t\t\t}\n\t\t}\n\n\t\tif(counter === 0){\n\t\t\t\tincorrectGuesses++;\n\t\t\t\tplayVideo();\n\t\t\t}\n\n\t\tfor(k=0; k < word.length; k++){\n\t\t\tvar currentGuess = input;\n\t\t\tvar currentCheck = word.charAt(k);\n\t\t\tif(input === word.charAt(k)){\n\t\t\t\tanswerMask[k] = input;\n\t\t\t\t// correctGuesses++;\n\t\t\t}\n\t\t}\n\t\theartbeat = chances - incorrectGuesses;\n\t\t// log(\"incorrectGuesses \" + incorrectGuesses);\n\t\t// log(\"correctGuesses\" + correctGuesses);\n\n\t\tguessedLetters.push(input);\n\t}", "function isLetterInWord(playedLetter) {\n var playedFound = false;\n for (var index = 0; index < wordDisplay.length; index++) {\n var displayLetter = wordDisplay[index];\n var found = false;\n if (playedLetter.trim() == displayLetter) {\n found = true;\n playedFound = true;\n }\n if (found) {\n wordToUse[index] = playedLetter;\n }\n }\n if (!playedFound) {\n wrongGuessCount++;\n }\n //Loop through the word to use and create a nice set of fields\n cleanUpHiddenWord();\n var imgLink = \"../images/\" + wrongGuessCount + \".jpg\";\n document.getElementById(\"hangman\").innerHTML = formatImage(imgLink);\n if (allLetterSlotsFilled()) {\n window.alert(\"Congratulations, you solved the word\");\n //newGame();\n }\n if (maxWrongGuess == wrongGuessCount) {\n window.alert(\"Sorry, max number of wrong guesses met for word > \" + wordInfo);\n //newGame();\n }\n}", "checkLetter(letter) {\r\n const phrase = this.phrase;\r\n if (phrase.includes(letter)) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "showMatchedLetter(letter) {\n const phraseLis = document.getElementById('phrase').children[0].children;\n\n for(let i = 0; i < phraseLis.length; i++) {\n if(phraseLis[i].textContent.includes(letter)) {\n phraseLis[i].className = 'show';\n }\n }\n }", "function checkLetter(target) {\n const letter = document.querySelectorAll(\".letter\");\n const clickedLetter = target.textContent;\n let letterFound = null;\n\n for (let i = 0; i < letter.length; i++) {\n if (letter[i].textContent.toLocaleLowerCase() === clickedLetter) {\n letter[i].classList.add(\"show\");\n letterFound = letter[i].textContent;\n }\n }\n return letterFound;\n }", "checkLetter(letter) { \n if (this.phrase.includes(letter)) {\n return true; \n }\n }", "checkForWin() {\r\n const chosen = document.querySelectorAll('.show');\r\n const space = document.querySelectorAll('.space');\r\n if (this.activePhrase.phrase.length === (chosen.length + space.length)) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "function checkWin() {\n if(document.getElementById(\"letterLines\").innerHTML === currentWord){ // so proud!!!!!\n document.getElementById(\"result\").innerHTML = \"You Win!\";\n console.log(\"result\", result);\n }\n \n else if (attempt===0) { \n document.getElementById(\"result\").innerHTML = \"You lost!\";\n console.log(\"result\", result);\n event();\n }\n }", "function hangMan() {\n document.onkeyup = function (event) { //when key pressed\n let userGuess = event.key.toLowerCase(); //assign the input to userGuess\n let resultVar = currentWord.search(userGuess);\n document.getElementById('directionsText').innerHTML = (''); //sets resultVar to if the letter is in word or not\n if (resultVar > -1) //if it is,\n {\n rightGuess++; //add one to rightguess\n for (i = 0; i <= cwLength; i++) //a for loop, should run for as long as the currentword, but it doesn't.\n {\n if (userGuess === currentWord.charAt(i)) //if the input is in current word,\n {\n wordArray[i] = currentWord.charAt(i);\n console.log(wordArray);\n let hiddenWord = document.getElementById(\"currentWord\");\n hiddenWord.innerHTML = 'your current word is ' + wordArray;\n }\n } if (wordArray.join(\"\") === currentWord) {\n document.getElementById('directionsText').innerHTML = ('<p>Congratulations! You have won. Press any key to begin again.</p>')\n winCount++\n //victory message\n document.onkeyup = function (event) //reload page on keyup\n {\n location.reload();\n }\n }\n }\n else { //runs if input is incorrect\n guessVar--; //minus one guess\n wrongGuess.push(userGuess); //add to empty array of wrong input\n document.getElementById('incorrectGuesses').innerHTML = ('Wrong letters guessed: ' + wrongGuess); //displays info\n document.getElementById('guessCount').innerHTML = ('Guesses left: ' + guessVar);\n if (guessVar === 0) { //if you run out of guesses\n document.getElementById('directionsText').innerHTML = (\"<p> I'm sorry, you have lost. Press any key to begin again.</p>\")\n lossCount++//loss screen\n document.onkeyup = function (event) {\n location.reload();\n }\n }\n }\n }\n}", "checkLetter(button, selectedLetter) {\n let isChosen = true;\n //iterates through phrase and adds 'chosen' class if there is a match\n if (this.phrase.indexOf(selectedLetter) >= 0) {\n $(button).addClass('chosen');\n //displays letter to user if they guessed right\n this.showMatchedLetter(selectedLetter)\n isChosen = true;\n //iterates through phrase and adds 'wrong' class if there is no match\n } else if ($(button).attr('class') === 'key') {\n $(button).addClass('wrong');\n isChosen = false;\n } \n return isChosen\n }", "function showWord(letter) {\n\n console.log(chosenWord);\n // Check if current letter exists\n for (var i = 0; i < chosenWord.length; i++) {\n // If the letter exists, display it on screen\n if (chosenWord[i].toLowerCase() === letter) {\n hideWord[i] = letter;\n hidden.innerHTML = hideWord.join(\"\");\n }\n }\n\n // If the letter doesn't exist, decrement the guess counter\n if (!chosenWord.includes(letter)) {\n startingGuesses--;\n guesses.innerHTML = startingGuesses;\n\n // If there are no remaining guesses, show the word on screen\n if (startingGuesses === 0) {\n losses++;\n alert(\"game over\");\n hidden.innerHTML = chosenWord;\n //gameInitalLoad();\n }\n // If all of the letters have been guessed, increment wins by 1\n else if (!hideWord.includes(\"-\") && guesses > 0) {\n wins++;\n var showWins = document.getElementById(\"wins\");\n showWins.innerHTML = wins;\n }\n }\n}", "function hasMoreMoves (wordArray) {\n\n var word = formWord(wordArray);\n for (var i = 0; i < wordArray.length; i++) {\n\n // Only check if a word can be made by changing the letter at i if \n // the letter is actually available for changing\n if (!(wordArray[i].color === state.toColor)) {\n var letter = word.charAt(i);\n for (var j = 0; j < 26; j++) {\n // It is invalid to change a letter to itself, so ignore that case\n if (alphabet[j] !== letter.toUpperCase()) {\n var newWord = word.slice(0, i) + alphabet[j] + word.slice(i + 1);\n if (checkWord(newWord)) {\n state.hint = {\n fromWord: word,\n toWord: newWord\n };\n return true;\n }\n }\n }\n }\n }\n return false;\n}" ]
[ "0.7196467", "0.71727264", "0.71602255", "0.71580786", "0.7141586", "0.70473367", "0.699682", "0.69952816", "0.69315636", "0.69069725", "0.6887574", "0.68518746", "0.678878", "0.6781155", "0.6747107", "0.662387", "0.65888125", "0.65854025", "0.6561763", "0.65555155", "0.6528451", "0.6520295", "0.6514817", "0.64922166", "0.6487018", "0.6484641", "0.6481778", "0.6461508", "0.64469886", "0.64432037", "0.643585", "0.64340013", "0.64305735", "0.64266247", "0.64230037", "0.641646", "0.64160985", "0.6409414", "0.64064336", "0.6396331", "0.63929176", "0.63829994", "0.63770485", "0.6374647", "0.6358238", "0.6349079", "0.6348533", "0.63355815", "0.6333332", "0.6331059", "0.6330261", "0.6325092", "0.6317628", "0.6310909", "0.63018006", "0.6299865", "0.6297472", "0.62877333", "0.62831104", "0.62747276", "0.62716335", "0.62661034", "0.6255954", "0.62482804", "0.6247047", "0.62430996", "0.6238698", "0.6234313", "0.622509", "0.6219161", "0.62172467", "0.62126964", "0.62110746", "0.62047935", "0.62029296", "0.6199896", "0.61960244", "0.619363", "0.61920357", "0.61881214", "0.6181012", "0.61772454", "0.6172358", "0.61667603", "0.6159224", "0.6147924", "0.61470467", "0.6146356", "0.6145951", "0.6145151", "0.6144976", "0.61417973", "0.6139169", "0.61334777", "0.61320496", "0.61274517", "0.61263686", "0.6125662", "0.61256254", "0.6125538", "0.61247647" ]
0.0
-1
If player loses 5 lives, game ends
gameOver(gameWon) { const startScreen = document.getElementById('overlay'); startScreen.style.display = 'block'; const gameEndMessage = document.getElementById('game-over-message'); const gameEndOverlay = document.getElementById('overlay'); if (gameWon) { gameEndMessage.textContent = 'Good Work, You Won!'; gameEndOverlay.classList.replace('start', 'win'); } else { gameEndMessage.textContent = 'You Lost... Beter Luck Next Time!'; gameEndOverlay.classList.replace('start', 'lose'); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function loseLife() {\n\n lives--;\n\n if (lives <= 0) {\n gameView = VIEW_MAIN_MENU;\n\n // Go to leaderboard submission\n if (score > 0) {\n submitScore();\n }\n\n if (sndMusic) {\n sndMusic.stop();\n }\n }\n}", "function livesDecrease() {\n guessesLeft--;\n }", "function loseLife() {\n\n // Decrease the number of lives the player has remaining\n _lives--;\n\n // Pause the player's movements\n freezePlayer();\n\n // Inform other code modules that the player has lost a life\n Frogger.observer.publish(\"player-lost-life\");\n\n if (_lives === 0) {\n // Declare the game to be over if the player has no lives remaining\n gameOver();\n } else {\n\n // If there are lives remaining, wait 2000 milliseconds (2 seconds) before\n // resetting the player's character and other obstacles to their initial\n // positions on the game board\n setTimeout(reset, 2000);\n }\n }", "function gameLose() {\n\tplayCounter++;\n\tloseCount++;\n\tconsole.log(\"You lose...\");\n\tif (playCounter < 3) {\n\t\tgame.state.start('lose');\n\t}\n\telse {\n\t\tgame.state.start('complete');\n\t}\n}", "function outOfBounds() {\n if (lives > 0) {\n lives--;\n } else {\n game = false;\n }\n }", "function loseLife() {\n // Only decrement when greater than zero\n if (player.lives > 0) {\n player.lives--; // decrement lives\n const lives = document.querySelectorAll('.lifebar img'); // Get the life meter\n lives[player.lives].classList.toggle('hide'); // Remove one life on screen\n }\n if (player.lives === 0) {\n gameOver();\n }\n}", "removeLife() {\r\n const scoreboard = document.getElementsByClassName('tries');\r\n // Replace last heart with empty heart.\r\n scoreboard[scoreboard.length-this.missed-1].getElementsByTagName('img')[0].src = 'images/lostHeart.png'\r\n // count up missed property\r\n this.missed += 1;\r\n\r\n // Call gameOver() if player lost all lives\r\n if(this.missed === 5) {\r\n this.gameOver();\r\n }\r\n }", "removeLife(){\n this.missed++;\n const $lostHeart = $('#scoreboard img[src=\"images/liveHeart.png\"]:last');\n $lostHeart.attr('src', 'images/lostHeart.png');\n if(this.missed >= 5){\n let isWon = false;\n this.gameOver(isWon);\n }\n \n }", "NumberOfLives()\n {\n NofLives = NofLives -1 ;\n\n if (NofLives >= 1 && NofLives <=3 )\n {\n this.ResetGame();\n }\n\n else \n {\n alert(\"You Collision 3 times \\n Game Ends\");\n // to stop the Game\n game = setTimeout(gameLoop, 1000 / 30);\n }\n\n }", "dieScene() {\n this.time+=10\n ufo_sound.stop()\n if(this.count > 6){\n if(this.life <= 0) \n {\n push()\n fill(255)\n textSize(15)\n text('GAME OVER', 130, 130);\n pop()\n this.gameover()\n }\n\n else\n {\n this.changePlayer()\n }\n }\n if(this.time<100 &&this.count<6) {\n image(image_player_dead_1, this.position_x, this.position_y, this.width, this.height);\n }\n else if(this.time>=100&&this.count<6) {\n image(image_player_dead_2, this.position_x, this.position_y, this.width, this.height);\n }\n if(this.time>200) {\n this.time =0\n this.count++\n }\n}", "function checkPlayerDie()\n{\n if (gameChar_y > height)\n {\n stopGameMusic();\n gameSounds.died.play();\n \n if (lives > 0)\n { \n lives--;\n startGame();\n }\n } \n}", "function loseCheck(){\n\t\tif (currentAmount > targetAmount){\n\t\t\talert(\"Boss: I heard that the equipment broke down after getting overloaded. We'll try again - don't overload the gear next time!\");\n\t\t\t loseExped++;\n\t\t\t $(\"#losses\").html(loseExped);\n\t\t\t resetGame();\n\t\t}\n\t}", "function updatePlayerLives() {\n playerLives = playerLives - 1;\n //play sad fog horn sound\n fogHorn.play();\n //display the new number of lives\n drawPlayerLives()\n //if the player has no more lives, make gameOver true\n if (playerLives < 1) {\n gameOver = true;\n }\n}", "function endgame() {\n if(player1pointscore - player2pointscore == 6) {\n showwinner();\n }\n if (player2pointscore - player1pointscore == 6) {\n showwinner();\n }\n if (player1pointscore + player2pointscore > 10) {\n showwinner();\n }\n}", "function checkLives() {\n if (lives <= 0) {\n swal(\"Game Over!\", \"You reached Level \" + level + \" in \" + time + \" seconds!\", \"error\");\n stopTimer();\n newGame();\n } else {\n swal(\"Whatch out! Lives don't grow on trees, you know.\" ,\"You get one heart every 5 levels.\", \"warning\");\n }\n}", "function endGame() {\n\n if (userNum === targetNum) {\n\n $(\"#message\").text(\"You won!\");\n wins = wins + 1;\n $(\"#wins\").html(wins);\n gameFlag = false;\n\n }\n if (userNum > targetNum) {\n\n $(\"#message\").text(\"You lost!\");\n losses = losses + 1;\n $(\"#losses\").html(losses);\n gameFlag = false;\n\n }\n\n }", "function GameOver()\n {\n if(points > 10 || points2 > 10)\n {\n endGame();\n }\n }", "isGameOver () {\n const completedCoins = this._players[this.currentTurn].getCompletedCoins()\n return completedCoins.length === 4\n }", "function checkPlayerDie() {\n\tif (gameChar_y > height) {\n\t\tlives -= 1;\n\t\tstartGame();\n\t\tsplashSound.play();\n\t}\n}", "removeLife () {\n const lives = document.getElementsByClassName(\"tries\");\n this.missed++;\n for (let i=0; i<this.missed; i++){\n lives[i].innerHTML = `<img src=\"images/lostHeart.png\" alt=\"Lost Heart Icon\" height=\"35\" width=\"30\">`;\n }\n // Lose the game if user runs out of lives\n if (this.missed === 5){\n this.gameOver(false);\n }\n }", "gameLost(){\n if (this.loseLives()) {\n this.next();\n }\n }", "function lost(){\n pause();\n playing = false;\n lose = true;\n setHighscore();\n html('rows','Game Over')\n }", "function hasUserLost() {\n //check to see if the user has won\n if (guessesLeft == 0 ) {\n console.log(\"USER LOSES\");\n //user has won, increment wins\n losses++;\n //add image and audio HTML if you have time. \n resetGame();\n }\n\n}", "function isGameOver(){\n sounds.explosion.cloneNode().play();\n if(lives <= 0){\n triggerModal(overWindow);\n }\n else{\n lives--;\n livesElem.innerText = lives;\n document.querySelector('.footer-left').querySelector('.spaceship').remove()\n }\n}", "function userLoses() {\n userObject.losses++;\n databaseModify.update();\n userScreen.lose();\n setTimeout(function() {\n game.newRound();\n }, 2000);\n }", "checkLose() {\n\t\tfor (let j = 0; j < 10; j++) {\n\t\t\tif (this.grid.squares[0][j].visible) {\n\t\t\t\t/* Update the high score if needed. */\n\t\t\t\tif (this.score > this.high) {\n\t\t\t\t\tthis.high = this.score;\n\t\t\t\t\tthis._updateScoreBox();\n\t\t\t\t}\n\n\t\t\t\tclient.playerLost(this.high);\n\t\t\t\tthis.gameOverSelectorBox.initialize();\n\t\t\t\tthis.state = STATE_GAME_OVER;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}", "removeLife() {\n const lives = document.getElementsByClassName(\"tries\"); //Total Lives\n const triesLeft = lives.length - this.missed; //Total tries left: length - missed\n\n //If we have more than 0 tries then change the pic and add to missed\n if (triesLeft > 0) {\n lives[this.missed].firstElementChild.src = \"images/lostHeart.png\"; //change heart image\n this.missed += 1; // add one to missed\n }\n\n //If missed count is 5, call gameOver\n if (this.missed == 5) {\n this.gameOver(false);\n }\n }", "function gameOver() {\n if (guessesRemaining < 1) {\n alert('Game Over')\n }\n }", "removeLife() {\r\n const hearts = document.querySelectorAll('.tries');\r\n for (let i = 0; i <= this.missed; i++) {\r\n hearts[i].lastElementChild.src = 'images/lostHeart.png';\r\n }\r\n\r\n this.missed += 1;\r\n \r\n if (this.missed === 5) {\r\n this.gameOver(this.checkForWin()); \r\n }\r\n }", "function addLives(){\n if (livesCount <= 2) {\n livesCount++;\n }\n}", "kill(){\r\n this.lives--;\r\n this.livesLost++;\r\n if(this.lives<0){\r\n this.gameOver = true;\r\n }else{\r\n this.resetBoard();\r\n }\r\n }", "loseLive(player, enemy) {\n if (!this.invulnerable) {\n this.lives--;\n this.invulnerable = true;\n this.zelda.alpha = 0.5;\n }\n }", "function livesLeft(){\n if (lives <= 0){\n sessionStorage.setItem(\"score\",`${score}`);\n document.location.href = 'gameover.html';\n };\n }", "function takeAwayGuesses() {\n numOfGuesses--;\n if (numOfGuesses <= 0) {\n nonWinner();\n }\n }", "function winLose() {\n\n if (luminousScore === collectorScore) {\n winCount++;\n $(\"#status\").text(luminousScore + \" Bling! You Won! Click any crystal to begin!\")\n startGame();\n } else if (luminousScore > collectorScore) {\n lossCount++;\n $(\"#status\").text(luminousScore + \"oops! To many, Click a any crystal to try again!\")\n startGame();\n }\n if (lossCount === 12) {\n alert(\"too many rounds lost. Let's try again, Shine on!\")\n restartGame();\n }\n}", "function checkGameOver() {\r\n if (lives == 0) {\r\n console.log(\"game over\");\r\n return true;\r\n }\r\n return false;\r\n}", "function gameLose() {\n\talert(\"Oh no! You ran out of guesses. Go ahead and try again\");\n\tstartGame();\n}", "removeLife() {\r\n const tries = document.getElementsByClassName('tries')[this.missed];\r\n tries.firstChild.src = \"images/lostHeart.png\";\r\n this.missed += 1;\r\n if (this.missed === 5) {\r\n this.gameOver(false)\r\n }\r\n }", "function answerIsWrong(){\r\n levens--;\r\n lives.innerHTML = \"<p>Levens: \" + levens + \"</p>\";\r\n\r\n if (levens <= 0) {\r\n \t clearInterval(TIMER);\r\n \tgameOverRender();\r\n }\r\n}", "function checkGameOver(totalDead){\n if(totalDead >= globalPopulation && gameOver != 3){\n gameOver = 1; // winner\n }else if (cure.progressRate > 100 && gameOver != 3) {\n gameOver = 2; // loser\n }\n}", "function died() {\n if (lives == 0) {\n document.documentElement.style.setProperty('--blinkyAnimation', '0s');\n document.documentElement.style.setProperty('--pinkyAnimation', '0s');\n document.documentElement.style.setProperty('--inkyAnimation', '0s');\n document.documentElement.style.setProperty('--clydeAnimation', '0s');\n document.documentElement.style.setProperty('--ghostsWalking', '0s');\n hud.style.color = '#FE2502';\n hud.innerText = 'GAME OVER';\n siren.stopAudio();\n invincible.stopAudio();\n regenerating.stopAudio();\n } else {\n dotsBeforeExit = [\n [0, 0, 0],\n [7, 7, 7],\n [10, 10, 10],\n [15, 15, 15]\n ];\n pacmanGraphic.style.transform = 'scale(1)';\n initialize();\n }\n }", "function ballLeaveScreen()\n{\n lives--;\n if(lives) // if there's life left\n {\n // decrease the score increment based on how many lives are left.\n (lives == 2) ? scoreIncrement = 5 : scoreIncrement = 1;\n livesText.setText('Lives: '+ lives);\n lifeLostText.visible = true;\n ball.reset(game.world.width * 0.5, paddle.y - 30);\n paddle.reset(game.world.width * 0.5, game.world.height * 0.90);\n game.input.onDown.addOnce(function(){\n lifeLostText.visible = false;\n ball.body.velocity.set(200, -200);\n }, this);\n }\n else // no more lives left. Game over.\n {\n showDialog();\n }\n}", "function endGame() {\n if (score === randNum) {\n wins += 1;\n $(\"#score-dis\").html(\"\");\n reset();\n }\n else if (score > randNum) {\n losses += 1;\n $(\"#score-dis\").html(\"\");\n reset();\n }\n }", "function endGame() {\n // Update the max level achieved board\n if (level > maxLevelAchieved) {\n maxLevelAchieved = level;\n $(\".max-level\").text(maxLevelAchieved);\n }\n\n // Make game over sound\n let sound = new Audio(\"sounds/wrong.mp3\");\n sound.play();\n\n // Add visual aspects of game over\n $(\"body\").addClass(\"game-over\");\n setTimeout(function() {\n $(\"body\").removeClass(\"game-over\");\n }, 100);\n $(\"h1\").text(\"Game Over! Press Any Key to Replay\");\n\n // Reinitializing letiables for a new round\n level = 0;\n newGame = true;\n}", "removeLife() {\r\n let lives = document.querySelectorAll('img');\r\n //console.log(lives);\r\n lives[this.missed].src=\"images/lostHeart.png\";\r\n this.missed += 1;\r\n\r\n if (this.missed === 5) {\r\n //console.log('Game Over');\r\n // const overlay = document.getElementById('overlay');\r\n // const heading = document.getElementById('game-over-message');\r\n // //console.log(overlay);\r\n // overlay.className = 'lose';\r\n // overlay.style.display = 'flex';\r\n // heading.textContent = 'GAME OVER';\r\n this.gameOver(false);\r\n }\r\n}", "function lose() {\n losses++;\n startGame();\n}", "function decrementLives() {\r\n\t\tlives--;\r\n\t\t\r\n\t\tif (lives == 0) {\r\n\t\t\tgameOver();\r\n\t\t} else {\r\n\t\t\tdisplayLives();\r\n\t\t}\r\n\t\t\r\n}", "function livesDown()\r\n{\r\n if(bonusHeartCount == 0)\r\n bonusHeartCount = 1;\r\n\r\n //change the relevent status from visable to hidden\r\n if(lives == 3){\r\n document.getElementById(\"firstLife\").style.visibility = \"hidden\";\r\n }\r\n else if(lives == 2){\r\n document.getElementById(\"secondLastLife\").style.visibility = \"hidden\";\r\n }\r\n else if(lives == 1){\r\n document.getElementById(\"lastLife\").style.visibility = \"hidden\";\r\n }\r\n lives--;\r\n\r\n //if the player stil have live - he didnt lost yet- then reset the board\r\n if(lives > 0)\r\n reset(board);\r\n}", "deathOfEither(){\n if (playerPosition === this.position && !cells[playerPosition].classList.contains('powerUp')){\n endTheGame()\n winOrLoseScreen()\n win = false\n } else if (playerPosition === this.position && cells[playerPosition].classList.contains('powerUp')){\n this.position = 337\n playerScore += 5000\n cells[this.position].classList.remove(this.classname)\n gameoverAudio()\n this.eggTimer()\n }\n\n }", "function loseOneLife() {\n\t\t//Vérifier que le nombre de vie est supérieur à 1\n\t\tif(getLife()>1)\n\t\t{\n\t\t\t//moins 10%\n\t\t\tsetLife(getLife()-10);\n\t\t}\n\t\telse //Il n'y avait plus qu'une vie\n\t\t{\n\t\t\t//Une vie perdu\n\t\t\tsetLife(getLife()-1);\n\n\t\t\t//Le joueur n'a plus de vie : jeu terminé\n\t\t\tendGame();\n\t\t}\n\t}", "playerLoses() {\n this.roundEnds('LOSER');\n }", "function dead(){\n if (appleY > height){\n state = \"end\";\n }\n else if (millis() > lastTimeSwitched + gametime){\n state = \"end\";\n }\n}", "function gameOver() {\n if (guessesRemaining < 1) {\n alert('Game Over')\n }\n}", "function finishGame() {\r\n if (computerPoints == 5 && playerPoints == 5) {\r\n finalResult.innerHTML = \"GAME OVER. It's a tie!\";\r\n removeClick();\r\n }\r\n else if (computerPoints == 5) {\r\n finalResult.innerHTML = \"GAME OVER. You lost!\";\r\n removeClick();\r\n }\r\n else if (playerPoints == 5) {\r\n finalResult.innerHTML = \"GAME OVER. You won!\";\r\n removeClick();\r\n }\r\n}", "function keepScore(computer, player) {\r\n\r\n playerWins += player;\r\n computerWins += computer;\r\n results.innerText = \"Player Wins: \" + playerWins + \"\\n\" + \"Computer Wins: \" + computerWins;\r\n\r\n if (playerWins == 5 || computerWins == 5) {\r\n newGame();\r\n }\r\n\r\n} // End Function", "removeLife() {\n // Get the first element with the class \"tries\"\n const heart = document.getElementsByClassName('tries')[0];\n // Remove the heart\n heart.parentNode.removeChild(heart);\n // Increase the \"missed\" counter\n this.missed++;\n // Conditional to test if all \"lives\" have been used\n if (this.missed === 5) {\n // Call the gameOver method with the losing message\n this.gameOver(`Oh noes! No more lives left! The phrase was: \"${this.chosenPhrase.phrase}\"`);\n }\n }", "function gameOver(numberOfLives){\n if(numberOfLives <= 0){\n return true\n }else{\n return false\n }\n}", "function checkLives(lives) {\r\n if (lives <= 0){\r\n getGameOver.innerHTML = \"You lost\";\r\n getGameOver.style.display = \"block\";\r\n getRestartGame.style.display = \"block\";\r\n\r\n updateHighscore();\r\n }\r\n}", "function checkLives() {\n\tif (lives <= 0){\n\t\tscore = (winCount * 100) + (lives * 1000);\n\t\tcheckScore();\n\t\tendGame();\n\t}\n\tif (numberPokemon<= 0){\n\t\tscore = (winCount * 100) + (lives * 1000);\n\t\tcheckScore();\n\t\tendGame(); \n\t}\n}", "function playerDeathCheck() {\n if (player.hp < 0) {\n player.hp = 0;\n playerHp.innerText = player.name + ' hit points: ' + player.hp;\n go.style.display = 'none';\n newMessage(player.name + ' died. GAME OVER');\n } else {\n player.hp = player.hp;\n }\n}", "function ifYouLose() {\n if(remainingGuesses === 0)\n {\n losses++; \n alert(\"You lost!!!\");\n $(\"#losediv\").html(\"losses: \" + losses);\n return;\n }\n}", "function userWinOrLose() {\n if (result > randomNum) {\n losses++;\n console.log(\"user lost\");\n // alert(\"You lost! Try again.\");\n initializeGame();\n }\n\n if (result === randomNum) {\n wins++;\n console.log(\"user won\");\n // alert(\"You won! Great job. Best out of 5?\");\n initializeGame();\n }\n}", "function youLose(){\n\t\t$('#winOrLose').text(youLost);\n\t\tgamesLost++;\n\t\t$('#losses').text(gamesLost);\n\t\tnewGame();\n\t}", "function endGameCheck(){\n if(teamScore > 0){\n console.log(\"You won!\")\n for(i=0; i < starters.length; i ++){\n starters[i].goodGame()\n starters[i].printStats()\n \n }\n }\n else if(teamScore < 0){\n console.log(\"You lost! \")\n for(i=0; i < starters.length; i ++){\n starters[i].badGame()\n starters[i].printStats()\n }\n }\n else{\n starters[i].printStats()\n }\n count++\n playgame()\n }", "removeLife() {\n this.missed += 1;\n let triesElement = document.getElementsByClassName('tries');\n triesElement[this.missed-1].firstElementChild.src = \"images/lostHeart.png\"\n if (this.missed == 5) {\n this.gameOver(false);\n }\n }", "function lose() {\n\ttime.Stop();\n\talive = false;\n\t\n\tstatistics.addGame(difficulty, statistics.state.lose);\n\tstatistics.addSeconds(difficulty, statistics.state.lose, seconds);\n\tstatistics.addDiscovered(difficulty, statistics.state.lose, calculateDiscoveredPercent());\n\t\n\t// Die statistics speichern\n\tPersistanceManager.saveStatistics(statistics);\n\t\n\tmessage(\"Sie haben verloren!<br> <br>\" + \n\t\t\t\"Schwierigkeit: \" + $('#difficulty :selected').text() + \" <br>\" +\n\t\t\t\"Benötigte Zeit: \" + timeCalculator(seconds) + \" <br>\" +\n\t\t\t\"Aufgedeckte Felder: \" + percCalculator(calculateDiscoveredPercent()) + \"%\");\n}", "removeLife() {\n //replace image source\n let tries = document.querySelectorAll('.tries img')\n tries[this.missed].src = 'images/lostHeart.png';\n //increase missed count\n this.missed += 1\n if (this.missed === 5) {\n //call gameOver once out of lifes\n this.gameOver(false)\n }\n }", "function endRound() {\n const initialPlayerLife = currentPlayerHealth;\n const playerDmg = dealPlayerDamage(monsterAttackVal);\n currentPlayerHealth -= playerDmg;\n writeLog(logEventMonsterAttack, playerDmg, currentMonsterHealth, currentPlayerHealth);\n\n if (currentPlayerHealth <= 0 && hasBonusLife) {\n hasBonusLife = false;\n removeBonusLife();\n currentPlayerHealth = initialPlayerLife;\n alert(\"You would be dead, but bonus life saved you!\");\n setPlayerHealth(initialPlayerLife);\n }\n\n if (currentMonsterHealth <= 0 && currentPlayerHealth > 0) {\n alert('YOU WON!');\n writeLog(logEventGameOver, 'PLAYER WON', currentMonsterHealth, currentPlayerHealth);\n reset();\n } else if (currentPlayerHealth <= 0 && currentMonsterHealth > 0 ) {\n alert('YOU LOST');\n writeLog(logEventGameOver, 'MONSTER WON', currentMonsterHealth, currentPlayerHealth);\n reset();\n } else if (currentPlayerHealth <= 0 && currentMonsterHealth <= 0 ) {\n alert('DRAW');\n writeLog(logEventGameOver, 'DRAW', currentMonsterHealth, currentPlayerHealth);\n reset();\n }\n\n}", "function checkGameOver() {\n var crashed = myObstacles.some(function(obstacle) {\n return player.crashWith(obstacle);\n });\n \n if (player.health < 1) {\n player.health = 0;\n window.alert(`Game over! You scored ${document.querySelector(\".score\").innerHTML} points`)\n myGameArea.stop();\n }\n }", "function endGame(){\n\t\tif(playerTotal === randomNumber){\n\t\t\twins++;\n\t\t\trandomNumber = ((Math.floor(Math.random() *101)) +19);\n\t\t\tplayerTotal = 0;\n\t\t\tdocument.getElementById(\"wins\").innerHTML = (\"Wins: \" + wins);\t\t\t\t\t\t\n\t\t\tdocument.getElementById(\"random-number\").innerHTML = randomNumber;\t\t\t\n\t\t\tdocument.getElementById(\"total\").innerHTML = playerTotal;\n\t\t}\n\t\telse if(playerTotal > randomNumber){\n\t\t\tlosses++;\n\t\t\trandomNumber = ((Math.floor(Math.random() *101)) +19);\n\t\t\tplayerTotal = 0;\n\t\t\tdocument.getElementById(\"losses\").innerHTML = (\"Losses: \" + losses);\t\t\t\t\t\t\n\t\t\tdocument.getElementById(\"random-number\").innerHTML = randomNumber;\t\t\t\n\t\t\tdocument.getElementById(\"total\").innerHTML = playerTotal;\n\t\t}\n\t}", "function hasLost(){\n if (total_score > targetNumber){\n loss++;\n $(\".loss\").text(loss);\n $(\".reset_game\").show();\n $(\".clickImg\").off();\n console.log(\"you lost\");\n return true;\n }\n else{\n return false;\n }\n }", "removeLife() {\n const tries = document.getElementsByClassName('tries');\n tries[this.missed].firstElementChild.src = \"images/lostHeart.png\";\n this.missed += 1; \n //If missed guess count gets to 5, the player loses\n if (this.missed === 5) {\n this.gameOver();\n }\n }", "function playerLives() {\n\tconst scorePanel = document.querySelector('.score-panel');\n\tconst lives = scorePanel.getElementsByTagName('img');\n\t// Set limits for lives based on player.reset() function call count\n\tif (callCount === 1) {\n\t\tlives[0].style.display = 'none';\n\t} else if (callCount === 2) {\n\t\tlives[0, 1].style.display = 'none';\n\t} else if (callCount === 3) {\n\t\tlives[0, 1, 2].style.visibility = 'hidden';\n\t\t// Display game over modal\n\t\tsetTimeout(gameOver, 500);\n\t}\n}", "function winGame() {\n score();\n // reset the game\n player.reset();\n document.getElementById(\"score\").innerHTML = youScore;\n document.getElementById(\"crashed\").innerHTML = crashedTimes;\n var probability = parseInt(Math.random()*10);\n if (probability < 5 && allEnemies.length < 5) {\n allEnemies.push(new Enemy(0,40 + Math.random()*100,40 + Math.random()*100));\n }\n \n}", "function isLoser() {\n // if the numGuessesRemaining is 0 then -1 numLosses and switch isFinished to true\n if (numGuessesRemaining <= 0) {\n numLosses++;\n isFinished = true;\n document.getElementById(\"numLosses\").style.color = \"#e12d2e\";\n } if (numLosses === 3){\n alert(\"Sorry buddy, game over!\");\n window.location.reload(true);// Reload the current page without the browser cache\n }\n}", "function loseGame() {\n\t alert(\"You lose! Try again!\");\n\t lossCount = lossCount + 1;\n\t $(\".losses\").text(\"Losses: \" + lossCount);\n\t resetGame();\n\t}", "removeLife(){\r\n const scoreboard = document.querySelectorAll('#scoreboard img')\r\n scoreboard[this.missed].src = \"images/lostHeart.png\"\r\n this.missed += 1;\r\n\r\n if(this.missed === 4){\r\n document.querySelector('.main-container').classList.add('onelife');\r\n }\r\n\r\n if(this.missed === 5){\r\n this.gameOver();\r\n document.querySelector('.main-container').classList.remove('onelife');\r\n }\r\n }", "removeLife() {\n const tries = document.querySelectorAll(\".tries img\");\n tries[4 - this.missed].setAttribute(\"src\", \"images/lostHeart.png\");\n this.missed++;\n if (this.missed === 5) {\n this.gameOver(false);\n }\n }", "gameOverCheck() {\n if (gameState.lives <= 0) {\n this.hiScoreCheckAndSave(); \n this.cameras.main.fade(gameState.FADE_TIME_FAST, 0, 0, 0, false, function(camera, progress) {\n if (progress >= 1.0) {\n sfx.gameover.play();\n this.scene.stop('MainScene');\n\t\t\t this.scene.start('GameOverScene');\n }\n });\n }\n }", "removeLife(){\n this.missed++;\n let images = document.querySelector(\"img[src='images/liveHeart.png']\");\n if (this.missed < 5) {\n images.src = \"images/lostHeart.png\";\n } else if (this.missed === 5) {\n this.gameOver(true);\n }\n }", "function gameComplete () {\n if (matches === 8) {\n gameMessage();\n stopTime();\n }\n}", "removeLife() {\n let heart = document.querySelector(\"img[src='images/liveHeart.png']\");\n heart.src = \"images/lostHeart.png\";\n this.missed += 1;\n if(this.missed === 5){\n this.gameOver(this.checkForWin());\n }\n }", "function momBabyCollison() {\r\n if (data.fruitNum > 0 && !data.gameOver) {\r\n var l = calLength2(mom.x, mom.y, baby.x, baby.y);\r\n if (l < 900) {\r\n baby.babyBodyCount = 0;\r\n mom.momBodyCount = 0;\r\n data.addScore();\r\n halo.born(baby.x,baby.y)\r\n }\r\n }\r\n}", "function winLose() {\n\t\tvar ul = $('.pastGuess').eq(guessLog);\n\t\tvar cloud = '-='+50*turn;\n\t\tif(correct === 5) {\n\t\t\tsetTimeout(function() {\n\t\t\t\t$('.win').removeClass('disable');\n\t\t\t\t$('body').css('backgroundColor', 'rgb(69, 130, 166)');\n\t\t\t\t$(ul).children().css('backgroundColor', 'transparent');\n\t\t\t\t$('#glowcloud').addClass('disable');\n\t\t\t}, 3000);\n\t\t} else if (turn === 5 && user.toString() != computer.toString()) {\n\t\t\tsetTimeout(function() {\n\t\t\t\t$('.lose').removeClass('disable');\n\t\t\t\t$('body').css('backgroundColor', '#000000;')\n\t\t\t\t}, 3000);\n\t\t\t}\n\n\t}", "function outOfTime(){\n gameState = 3;\n timeUp = true;\n wrongCount++;\n resolveAnswer();\n}", "removeLife() {\n this.missed += 1;\n const tries = document.getElementById('scoreboard').querySelector('ol').querySelectorAll('li');\n for (let i = 0; i < this.missed; i++) {\n tries[i].innerHTML = '<img src=\"images/lostHeart.png\" alt=\"Heart Icon\" height=\"35\" width=\"30\"></img>';\n tries[i].className = \"lost\";\n }\n if (this.missed >= 5) {\n this.gameOver(false);\n }\n }", "removeLife() {\n\n // select the heart DOM element and log it to ensure you're selecting the correct elements\n const heartTries = document.querySelectorAll('.tries img');\n\n if (this.missed < heartTries.length) {\n\n heartTries[this.missed].src = 'images/lostHeart.png';\n\n }\n\n //increment the games missed property by 1 using either this.missed += 1 or this.missed++\n this.missed++;\n\n if (this.missed === 5) {\n this.gameOver(false);\n }\n\n }", "function gameEnd(){\n\n game.startBanner = game.add.image(phaser.config.width / 2, phaser.config.height / 2, \"start-banner\")\n \n //If your score is higher than the opponent score, you win, else, you lose.\n if(score > oppScore){\n game.youWin = game.add.image(phaser.config.width / 2, phaser.config.height / 2, \"you-win\")\n }else{\n game.youLose = game.add.image(phaser.config.width / 2, phaser.config.height / 2, \"you-lose\")\n }\n\n game.scene.pause(); //Pause the scene\n\n setTimeout(function(){ //Set timeout then return to menu\n game.scene.start('menu')\n score = 0; //Set score back to 0\n Client.socket.emit('gameEnd');\n },5000)\n }", "function guessRemaining() {\n if(chances === 0) {\n loss();\n };\n}", "function checkIfGameEnded() {\r\n if (chances == 10) gameOver();\r\n if (win == true) winner();\r\n}", "removeLife() {\r\n this.missed += 1;\r\n let life = document.querySelector('.tries')\r\n life.style.display = \"none\";\r\n if(missed == 5){\r\n this.gameOver();\r\n }\r\n}", "function nay() {\n loses++;\n $(\"#win_msg\").hide();\n $(\"#lose_msg\").show();\n $(\"#loses\").text(loses);\n resetGame();\n }", "onGameEnd(){\n if (this.store.board.winner === null)\n this.emote(\"tie\");\n else if (this.store.board.winner)\n this.emote(\"defeat\");\n else\n this.emote(\"victory\");\n }", "minus1Life() {\n console.log(\"entered\")\n if (this.lifesGroup.getTotalUsed() == 0) {\n console.log(\"game over\")\n this.scene.scene.stop();\n this.scene.music.stop();\n console.log(this.scene.pontos)\n this.scene.scene.start(\"GameOver\",{points: this.scene.pontos})\n\n } else {\n console.log(\" a tirar vida\")\n let heartzito = this.lifesGroup.getFirstAlive();\n heartzito.active = false;\n heartzito.visible = false;\n //heartzito.killAndHide()\n console.log(this.lifesGroup.getTotalUsed())\n }\n\n }", "removeLife(){\n\t\t$('.tries:first').remove();\n\t\tthis.missed +=1\n\t\t\tif (this.missed === 5) {\n\t\t\t\tthis.gameOver();\n\t\t\t}\n}", "endLevel() {\n\t\tgame.tss = 0;\n\t\tconst sp = 10;\n\t\tfor( let i = 0; i < 5; i++ ) {\n\t\t\tgame.setCB( () => {\n\t\t\t\tplaySound( 'lvlc' );\n\t\t\t}, sp );\n\t\t}\n\t\tgame.fade( false );\n\t\tif( game.lvln === 3 ) {\n\t\t\tgame.end( true );\n\t\t\treturn;\n\t\t}\n\t\tgame.setCB( () => {\n\t\t\tgame.lvln++;\n\t\t\tgame.fade( true );\n\t\t\tgame.camToLvl( game.lvln );\n\t\t\tgame.tss = TSS;\n\t\t\tplaySound( 'lvls' );\n\t\t}, 5 * 60 );\n\t}", "removeLife() {\n const hearts = document.querySelector(\"img[src='images/liveHeart.png']\");\n hearts.src = \"images/lostHeart.png\";\n\n this.missed += 1;\n if (this.missed === 5) {\n this.gameOver();\n }\n }", "function endOfFight(player) {\n if (player.life <= 0) {\n player.warriorInfo();\n swal({\n title: \"End Of The Game !!\",\n text: `${player.name}, You lost the fight`,\n button: {\n text:`GAME RESTART IN 3 SECS!!`,\n }\n\n });\n setTimeout(function(){\n location.reload();\n }, 3000)\n }\n }", "function lifeCount() {\n if (lives > 1) {\n document.getElementById(\"attempts\").innerText = (lives + \" attempts remaining.\")\n }\n else if (lives === 1) {\n document.getElementById(\"attempts\").innerText = (lives + \" attempt remaining.\")\n }\n else if (lives == 0) {\n gameOver();\n }\n}", "function stay() {\r\n if (!gameInProgress) return alert(\"Game has finished, please start a new game\");\r\n //checking whether there are players left to act \r\n const check = utilFunctions.players.filter(player => player.isAlive)\r\n if (check.length >= 1){\r\n alert(`Player ${utilFunctions.determineCurrentPlayer().name} is next`);\r\n }\r\n else{\r\n // ending the game in case where everyone has acted\r\n utilFunctions.completeDealerCards()\r\n for (let player of utilFunctions.players){\r\n //checking who has won based on their regular and split cards result \r\n if (player.splitSum > 0) {\r\n player.isSplit = false\r\n utilFunctions.determineWinners(player, player.splitSum)\r\n }\r\n player.isAlive = false\r\n utilFunctions.determineWinners(player, player.sum)\r\n }\r\n utilFunctions.startOver()\r\n gameInProgress = false\r\n }\r\n}", "loseTurn(){\n this.playerTurn = (this.playerTurn % 2) + 1;\n this.scene.rotateCamera();\n this.previousBishops = ['LostTurn'];\n this.activeBishop = null;\n }" ]
[ "0.744876", "0.72901064", "0.7182619", "0.71585816", "0.7095602", "0.70593554", "0.6994691", "0.697262", "0.6950658", "0.6918213", "0.6916512", "0.68931323", "0.6870362", "0.6862543", "0.6860329", "0.6825252", "0.6821924", "0.6817644", "0.68064684", "0.67798775", "0.67669076", "0.67505425", "0.67408", "0.6735896", "0.671951", "0.67057353", "0.6702635", "0.6695168", "0.66616136", "0.6660727", "0.6642343", "0.66389763", "0.6635842", "0.6634635", "0.6632471", "0.66319937", "0.66310203", "0.6612973", "0.66081953", "0.6594405", "0.6580812", "0.65728563", "0.65676993", "0.65614307", "0.6556859", "0.6556724", "0.655633", "0.6548873", "0.6536926", "0.65353584", "0.6530522", "0.652364", "0.650849", "0.6503995", "0.64962983", "0.6491151", "0.64855486", "0.6485379", "0.6484481", "0.6477319", "0.6476678", "0.6473382", "0.647257", "0.6470106", "0.64666015", "0.645498", "0.64488447", "0.64410543", "0.64393455", "0.64341885", "0.6431947", "0.64274555", "0.6426302", "0.64230466", "0.6420892", "0.6414356", "0.6413669", "0.6412455", "0.64094025", "0.64036375", "0.6399531", "0.63856864", "0.63828695", "0.63773763", "0.6375368", "0.63682806", "0.6359605", "0.63539577", "0.63514954", "0.63500434", "0.6348089", "0.63475883", "0.63459945", "0.6345795", "0.63438123", "0.6343457", "0.63409", "0.6339956", "0.633993", "0.6338261", "0.6337808" ]
0.0
-1
Removes a life if player is wrong
removeLife() { let heart = document.getElementsByTagName('img'); heart[this.missed].setAttribute('src', 'images/lostHeart.png'); this.missed += 1; if (this.missed === 5) { this.gameOver(); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "removeLife() {\r\n const scoreboard = document.getElementsByClassName('tries');\r\n // Replace last heart with empty heart.\r\n scoreboard[scoreboard.length-this.missed-1].getElementsByTagName('img')[0].src = 'images/lostHeart.png'\r\n // count up missed property\r\n this.missed += 1;\r\n\r\n // Call gameOver() if player lost all lives\r\n if(this.missed === 5) {\r\n this.gameOver();\r\n }\r\n }", "function loseLife() {\n\n // Decrease the number of lives the player has remaining\n _lives--;\n\n // Pause the player's movements\n freezePlayer();\n\n // Inform other code modules that the player has lost a life\n Frogger.observer.publish(\"player-lost-life\");\n\n if (_lives === 0) {\n // Declare the game to be over if the player has no lives remaining\n gameOver();\n } else {\n\n // If there are lives remaining, wait 2000 milliseconds (2 seconds) before\n // resetting the player's character and other obstacles to their initial\n // positions on the game board\n setTimeout(reset, 2000);\n }\n }", "removeLife() {\n heartNodes[this.missed].src = 'images/lostHeart.png';\n this.missed += 1;\n if (this.missed === heartNodes.length) {\n this.gameOver(false);\n }\n }", "function loseOneLife() {\n\t\t//Vérifier que le nombre de vie est supérieur à 1\n\t\tif(getLife()>1)\n\t\t{\n\t\t\t//moins 10%\n\t\t\tsetLife(getLife()-10);\n\t\t}\n\t\telse //Il n'y avait plus qu'une vie\n\t\t{\n\t\t\t//Une vie perdu\n\t\t\tsetLife(getLife()-1);\n\n\t\t\t//Le joueur n'a plus de vie : jeu terminé\n\t\t\tendGame();\n\t\t}\n\t}", "function loseLife() {\n // Only decrement when greater than zero\n if (player.lives > 0) {\n player.lives--; // decrement lives\n const lives = document.querySelectorAll('.lifebar img'); // Get the life meter\n lives[player.lives].classList.toggle('hide'); // Remove one life on screen\n }\n if (player.lives === 0) {\n gameOver();\n }\n}", "removeLife(){\n\t\t$('.tries:first').remove();\n\t\tthis.missed +=1\n\t\t\tif (this.missed === 5) {\n\t\t\t\tthis.gameOver();\n\t\t\t}\n}", "removeLife(){\n this.missed++;\n const $lostHeart = $('#scoreboard img[src=\"images/liveHeart.png\"]:last');\n $lostHeart.attr('src', 'images/lostHeart.png');\n if(this.missed >= 5){\n let isWon = false;\n this.gameOver(isWon);\n }\n \n }", "removeLife() {\n // Get the first element with the class \"tries\"\n const heart = document.getElementsByClassName('tries')[0];\n // Remove the heart\n heart.parentNode.removeChild(heart);\n // Increase the \"missed\" counter\n this.missed++;\n // Conditional to test if all \"lives\" have been used\n if (this.missed === 5) {\n // Call the gameOver method with the losing message\n this.gameOver(`Oh noes! No more lives left! The phrase was: \"${this.chosenPhrase.phrase}\"`);\n }\n }", "removeLife() {\n const lives = document.getElementsByClassName(\"tries\"); //Total Lives\n const triesLeft = lives.length - this.missed; //Total tries left: length - missed\n\n //If we have more than 0 tries then change the pic and add to missed\n if (triesLeft > 0) {\n lives[this.missed].firstElementChild.src = \"images/lostHeart.png\"; //change heart image\n this.missed += 1; // add one to missed\n }\n\n //If missed count is 5, call gameOver\n if (this.missed == 5) {\n this.gameOver(false);\n }\n }", "removeLife () {\n const lives = document.getElementsByClassName(\"tries\");\n this.missed++;\n for (let i=0; i<this.missed; i++){\n lives[i].innerHTML = `<img src=\"images/lostHeart.png\" alt=\"Lost Heart Icon\" height=\"35\" width=\"30\">`;\n }\n // Lose the game if user runs out of lives\n if (this.missed === 5){\n this.gameOver(false);\n }\n }", "removeLife() {\n const lives = document.querySelectorAll('.tries');\n lives[this.missed].firstElementChild.setAttribute('src', 'images/lostHeart.png');\n this.missed += 1;\n if(this.missed > 4) {\n this.gameOver(false);\n }\n }", "removeLife() {\n const liveHeart = document.querySelector('[src=\"images/liveHeart.png\"]');\n liveHeart.setAttribute('src', 'images/lostHeart.png');\n this.missed += 1;\n if (this.missed === 5) {\n this.gameOver();\n }\n }", "removeLife() {\r\n const tries = document.getElementsByClassName('tries')[this.missed];\r\n tries.firstChild.src = \"images/lostHeart.png\";\r\n this.missed += 1;\r\n if (this.missed === 5) {\r\n this.gameOver(false)\r\n }\r\n }", "removeLife() {\n this.missed += 1;\n const heart = document.querySelector(\"img[src*='live']\")\n if (heart){\n heart.setAttribute('src', 'images/lostHeart.png');\n }\n else if (!heart) {\n this.gameOver();\n }\n }", "removeLife(){\n \t\tconst remainingTries = document.querySelectorAll('[src=\"images/liveHeart.png\"]')\n \t\tconst remainingTriesIndex = remainingTries.length-1\n\n \t\tif(this.missed < 4){\n \t\t\tthis.missed += 1\n \t\t\tremainingTries[remainingTriesIndex].src=\"images/lostHeart.png\"\n \t\t}else{\n \t\t\tthis.gameOver(false);\n \t\t}\n \t}", "function playerOneDead() {\n $('.playerOne').remove();\n loser();\n}", "removeLife() {\r\n const hearts = document.querySelectorAll('.tries');\r\n for (let i = 0; i <= this.missed; i++) {\r\n hearts[i].lastElementChild.src = 'images/lostHeart.png';\r\n }\r\n\r\n this.missed += 1;\r\n \r\n if (this.missed === 5) {\r\n this.gameOver(this.checkForWin()); \r\n }\r\n }", "removeLife() {\n this.missed += 1;\n let triesElement = document.getElementsByClassName('tries');\n triesElement[this.missed-1].firstElementChild.src = \"images/lostHeart.png\"\n if (this.missed == 5) {\n this.gameOver(false);\n }\n }", "removeLife() {\r\n this.missed += 1;\r\n\r\n if (this.missed === 5) {\r\n this.gameOver(false);\r\n } else {\r\n document.querySelector(\".tries\").firstElementChild.src =\r\n \"images/lostHeart.png\";\r\n document\r\n .querySelector(\".tries\")\r\n .firstElementChild.parentElement.classList.remove(\"tries\");\r\n }\r\n }", "removeLife() {\n const hearts = document.querySelector(\"img[src='images/liveHeart.png']\");\n hearts.src = \"images/lostHeart.png\";\n\n this.missed += 1;\n if (this.missed === 5) {\n this.gameOver();\n }\n }", "removeLife() {\r\n this.missed += 1;\r\n let life = document.querySelector('.tries')\r\n life.style.display = \"none\";\r\n if(missed == 5){\r\n this.gameOver();\r\n }\r\n}", "removeLife(){\n \n const tries = document.querySelectorAll(\".tries\");\n tries[this.missed].firstElementChild.setAttribute(\"src\",\"images/lostHeart.png\");\n this.missed += 1;\n if(this.missed == 5) {\n console.log('game over!');\n this.gameOver(this.checkForWin());\n }\n \n }", "removeLife() {\n\n // select the heart DOM element and log it to ensure you're selecting the correct elements\n const heartTries = document.querySelectorAll('.tries img');\n\n if (this.missed < heartTries.length) {\n\n heartTries[this.missed].src = 'images/lostHeart.png';\n\n }\n\n //increment the games missed property by 1 using either this.missed += 1 or this.missed++\n this.missed++;\n\n if (this.missed === 5) {\n this.gameOver(false);\n }\n\n }", "removeLife(){\n const hearts = document.querySelectorAll('.tries img');\n\n if (this.missed < hearts.length) {\n hearts[this.missed].src = 'images/lostHeart.png';\n }\n \n this.missed++;\n\n\n if (this.missed === 5) {\n this.gameOver(false);\n }\n }", "removeLife() {\n // increment missed count\n this.missed += 1;\n\n // remove a life if there are still lifes left\n if(this.missed !== 5) {\n\n // flag to track if lifes left image has already been changed\n let scoreboardChanged = false;\n \n // let's reference the li elements holding number of lifes left\n const scoreBoardElement = $('#scoreboard li');\n\n // iterate over the lifes li elements\n scoreBoardElement.each( (i, li) => {\n // reference scoreboard image element\n let img = li.firstElementChild;\n\n // get current image name\n let currentImgName = img.src.substring(img.src.lastIndexOf(\"/\")+1, img.src.length);\n\n // change image source to lost image if current image name is liveHeart.png and we haven't updated \n // the image yet in this iteration\n if(currentImgName === 'liveHeart.png' && scoreboardChanged === false) {\n img.src = 'images/lostHeart.png';\n scoreboardChanged = true;\n }\n });\n\n } else {\n // missed five times already, we end the game\n this.gameOver('lost');\n }\n }", "removeLife() {\n //replace image source\n let tries = document.querySelectorAll('.tries img')\n tries[this.missed].src = 'images/lostHeart.png';\n //increase missed count\n this.missed += 1\n if (this.missed === 5) {\n //call gameOver once out of lifes\n this.gameOver(false)\n }\n }", "function loseLife() {\n\n lives--;\n\n if (lives <= 0) {\n gameView = VIEW_MAIN_MENU;\n\n // Go to leaderboard submission\n if (score > 0) {\n submitScore();\n }\n\n if (sndMusic) {\n sndMusic.stop();\n }\n }\n}", "function playerTwoDead() {\n $('.playerTwo').remove();\n loser();\n}", "removeLife() {\n // const hearts = document.querySelector('#scoreboard > ol').children;\n const lifeHeartHTML = `<img src=\"images/liveHeart.png\" alt=\"Heart Icon\" height=\"35\" width=\"30\">`;\n const lostHeartHTML = `<img src=\"images/lostHeart.png\" alt=\"Heart Icon\" height=\"35\" width=\"30\">`;\n const lifeTaker = arr => {\n for (let i = 0; i < arr.length; i++) {\n if (arr[i].innerHTML == lifeHeartHTML) {\n arr[i].innerHTML = lostHeartHTML;\n break;\n }\n }\n }\n\n this.missed++;\n this.missed > 4 ? this.gameOver() : lifeTaker(hearts);\n }", "removeLife() {\r\n const tries = document.querySelectorAll('.tries');\r\n tries[this.missed].firstElementChild.setAttribute('src', 'images/lostHeart.png');\r\n this.missed += 1;\r\n if (this.missed === 5) {\r\n this.gameOver();\r\n };\r\n }", "removeLife(){\n if(overlay.classList.contains('win')){\n } else {\n const liveHeart = [];\n this.missed ++;\n for(let x = 0; x < hearts.length; x++){\n if(hearts[x].firstElementChild.classList != 'lostLife'){\n liveHeart.push(hearts[x]);\n }\n }\n if(liveHeart.length > 1){//if they have any lives left\n liveHeart[0].firstElementChild.src = 'images/lostHeart.png';\n liveHeart[0].firstElementChild.classList.add('lostLife');\n } else { //else if no lives left, then game is over\n this.gameOver();\n }\n }\n }", "function removeLife() {\n let lifeToRemove;\n if (lives === 3) {\n lifeToRemove = document.getElementById('heart_three');\n lifeToRemove.style.display = \"none\";\n lives = 2;\n }\n else if (lives === 2) {\n lifeToRemove = document.getElementById('heart_two');\n lifeToRemove.style.display = \"none\";\n lives = 1;\n }\n else if (lives === 1) {\n lifeToRemove = document.getElementById('heart_one');\n lifeToRemove.style.display = \"none\";\n lives = 0;\n }\n}", "removeLife() {\n const liveHeart = document.querySelector(\"img[src='images/liveHeart.png']\");\n liveHeart.setAttribute(\"src\", \"images/lostHeart.png\");\n this.missed++;\n if (this.missed === 5) {\n this.gameOver();\n }\n }", "removeLife() {\n //selects the scoreboard div\n const scoreboard = document.getElementsById('scoreboard');\n const arrayScoreBoard = scoreboard.map(heart => heart.innerHTML);\n for (let i = 0; i < arrayScoreBoard[i].length; i++) {\n //one of the liveHeart.png images is replaced with a lostHeart.png image\n scoreboard[i].src.replace('liveHeart.png', 'lostHeart.png');\n //increments the missed property\n return this.missed++;\n }\n //if the player has lost the game\n if (this.missed < 4) {\n //call the gameOver() method\n this.gameOver();\n }\n }", "removeLife(){\n const firstHeart = document.querySelector('img[src=\"images/liveHeart.png\"]');\n if(firstHeart){\n firstHeart.src = 'images/lostHeart.png';\n }\n this.missed++;\n if(this.missed >= 5){\n this.gameOver();\n }\n }", "removeLife(){\r\n const scoreboard = document.querySelectorAll('#scoreboard img')\r\n scoreboard[this.missed].src = \"images/lostHeart.png\"\r\n this.missed += 1;\r\n\r\n if(this.missed === 4){\r\n document.querySelector('.main-container').classList.add('onelife');\r\n }\r\n\r\n if(this.missed === 5){\r\n this.gameOver();\r\n document.querySelector('.main-container').classList.remove('onelife');\r\n }\r\n }", "function playerDead() {\n\n\tshipLivesContainer.removeAllChildren();\n\tfor(var i = 0; i < gameState.lives; i++) {\n\t\tvar sprite = new createjs.Sprite(playerSpriteSheet, \"still\");\n\t\tsprite.scaleX = .5;\n\t\tsprite.scaleY = .5;\n\n\t\tsprite.x = i*25;\n\t\tsprite.y = 0;\n\n\t\tshipLivesContainer.addChild(sprite);\n\t}\n\n\n\tvar x = player.x;\n\tvar y = player.y;\n\n\n\tshipContainer.removeChild(player.animations);\n\n\tplayer = null;\n\n\tfunction showPlayerAgain() {\n\t\tplayer = new Player(x,y);\n\t\tshipContainer.addChild(player.animations);\n\t}\n\n\tsetTimeout(showPlayerAgain, 2000)\n}", "function takeLifeAway() {\r\n // identify id of the heart image to remove\r\n var lifeId = \"h\" + lives;\r\n console.log(\"heart id: \" + lifeId);\r\n var life = document.getElementById(lifeId);\r\n // if answer is wrong, decrement lives and remove a heart on the screen\r\n if (!checkAnswer()) {\r\n lives--;\r\n console.log(\"lives left: \" + lives);\r\n life.style.display = \"none\";\r\n\t\tdocument.getElementById('wrong').play();\r\n }\r\n}", "removeLife() {\n const tries = document.getElementsByClassName('tries');\n tries[this.missed].firstElementChild.src = \"images/lostHeart.png\";\n this.missed += 1; \n //If missed guess count gets to 5, the player loses\n if (this.missed === 5) {\n this.gameOver();\n }\n }", "function playerDeathCheck() {\n if (player.hp < 0) {\n player.hp = 0;\n playerHp.innerText = player.name + ' hit points: ' + player.hp;\n go.style.display = 'none';\n newMessage(player.name + ' died. GAME OVER');\n } else {\n player.hp = player.hp;\n }\n}", "removeLife() {\n let lives = document.getElementsByClassName('tries');\n lives = Array.from(lives);\n lives = lives.filter( el => el.firstChild.getAttribute(\"src\") === \"images/liveHeart.png\");\n lives[0].firstChild.setAttribute('src','images/lostHeart.png');\n this.missed += 1;\n if (this.missed === 5){\n this.gameOver(false);\n }\n }", "removeLife() {\n const tries = document.querySelectorAll(\".tries img\");\n tries[4 - this.missed].setAttribute(\"src\", \"images/lostHeart.png\");\n this.missed++;\n if (this.missed === 5) {\n this.gameOver(false);\n }\n }", "function endOfFight(player) {\n if (player.life <= 0) {\n player.warriorInfo();\n swal({\n title: \"End Of The Game !!\",\n text: `${player.name}, You lost the fight`,\n button: {\n text:`GAME RESTART IN 3 SECS!!`,\n }\n\n });\n setTimeout(function(){\n location.reload();\n }, 3000)\n }\n }", "lose_life(meteor) {\n // Remove the correct meteor that caused a life to be lost\n for (var i = 0; i < this.meteors.length; i++) {\n if (meteor === this.meteors[i]) {\n app.stage.removeChild(this.meteors[i]);\n this.meteors.splice(i, 1);\n }\n }\n // There are still lives, keep playing game\n if (this.dinos.length > 0) {\n let rmDino = this.dinos.pop();\n app.stage.removeChild(rmDino);\n }\n // All lives lost, end game\n else {\n this.end_game();\n this.is_done = true;\n }\n }", "removeLife() {\n const wrongSound = document.querySelector('.wrongSound');\n const heartImage = document.getElementsByTagName('img');\n heartImage[this.missed].src = 'images/lostHeart.png'\n wrongSound.play();\n \n \n\n \n if(this.missed >= 4){\n this.gameOver(false) ;\n } else {\n this.missed += 1;\n }\n \n \n }", "deathOfEither(){\n if (playerPosition === this.position && !cells[playerPosition].classList.contains('powerUp')){\n endTheGame()\n winOrLoseScreen()\n win = false\n } else if (playerPosition === this.position && cells[playerPosition].classList.contains('powerUp')){\n this.position = 337\n playerScore += 5000\n cells[this.position].classList.remove(this.classname)\n gameoverAudio()\n this.eggTimer()\n }\n\n }", "removeLife() {\n $('.tries img').eq(this.missed).remove();\n $('.tries').eq(this.missed).append('<img src=\"images/lostHeart.png\" alt=\"Missing Heart Icon\" height=\"35\" width=\"30\"></img>');\n this.missed += 1;\n if (this.missed === 5) {\n this.gameOver();\n }\n }", "removeLife() {\n this.missed++\n const tries = document.querySelectorAll('.tries img')\n if (this.missed === 1) {\n tries[0].src = 'images/emptyHeart.png'\n } else if (this.missed === 2) {\n tries[1].src = 'images/emptyHeart.png'\n } else if (this.missed === 3) {\n tries[2].src = 'images/emptyHeart.png'\n } else if (this.missed === 4) {\n tries[3].src = 'images/emptyHeart.png'\n } else if (this.missed === 5) {\n tries[4].src = 'images/emptyHeart.png'\n this.gameOver()\n }\n }", "removeLife(){\n const triesImgs = document.querySelectorAll('.tries img');\n\n triesImgs[this.missed].src = \"images/lostHeart.png\";\n this.missed += 1;\n\n if(this.missed === triesImgs.length){\n this.gameOver(false);\n }\n }", "removeLife() {\r\n this.missed += 1;\r\n if(this.missed === 5){\r\n this.gameOver(false);\r\n };\r\n document.querySelectorAll('.tries img')[this.missed -1].src = 'images/lostHeart.png'; \r\n }", "function loseLife() {\n _character.playAnimation(\"lose-life\");\n }", "function checkPlayerDie() {\n\tif (gameChar_y > height) {\n\t\tlives -= 1;\n\t\tstartGame();\n\t\tsplashSound.play();\n\t}\n}", "removeLife() {\r\n\r\n }", "checkGameOver() {\n if (this.player.health <= 0) {\n // game lost\n this.animations.push(new Animation(explosionParameters, this.player.position.x, this.player.position.y));\n this.player.destroy();\n this.gameOver = true;\n }\n }", "removeLife(){\n this.missed++;\n let images = document.querySelector(\"img[src='images/liveHeart.png']\");\n if (this.missed < 5) {\n images.src = \"images/lostHeart.png\";\n } else if (this.missed === 5) {\n this.gameOver(true);\n }\n }", "removeLife() {\r\n // increment here, to facilitate generating the\r\n // heartListOl.children index below\r\n this.missed = this.missed + 1;\r\n if (this.missed > maxMisses) {\r\n this.gameOver(false);\r\n } else {\r\n const li = heartListOl.children[heartListOl.children.length-this.missed];\r\n li.children[0].src=\"images/lostHeart.png\";\r\n }\r\n }", "removeLife() {\r\n this.missed += 1;\r\n let listScore = document.querySelectorAll('#scoreboard ol li');\r\n for(let i=0; i<listScore.length; i++){\r\n if(i === this.missed-1){\r\n let img = listScore[i].querySelector('img');\r\n img.setAttribute('src','images/lostHeart.png');\r\n }\r\n }\r\n if(this.missed === listScore.length){\r\n this.gameOver(false);\r\n }\r\n\r\n }", "removeLife() {\n let hearts = document.getElementsByClassName(\"tries\");\n if (this.missed < 5) {\n hearts[this.missed].firstElementChild.src = \"images/lostHeart.png\";\n this.missed++;\n }\n // } else {\n // this.gameOver(false);\n // }\n }", "removeLife() {\r\n let lives = document.querySelectorAll('img');\r\n //console.log(lives);\r\n lives[this.missed].src=\"images/lostHeart.png\";\r\n this.missed += 1;\r\n\r\n if (this.missed === 5) {\r\n //console.log('Game Over');\r\n // const overlay = document.getElementById('overlay');\r\n // const heading = document.getElementById('game-over-message');\r\n // //console.log(overlay);\r\n // overlay.className = 'lose';\r\n // overlay.style.display = 'flex';\r\n // heading.textContent = 'GAME OVER';\r\n this.gameOver(false);\r\n }\r\n}", "loseLive(player, enemy) {\n if (!this.invulnerable) {\n this.lives--;\n this.invulnerable = true;\n this.zelda.alpha = 0.5;\n }\n }", "removeLife() {\n this.missed += 1;\n const tries = document.getElementById('scoreboard').querySelector('ol').querySelectorAll('li');\n for (let i = 0; i < this.missed; i++) {\n tries[i].innerHTML = '<img src=\"images/lostHeart.png\" alt=\"Heart Icon\" height=\"35\" width=\"30\"></img>';\n tries[i].className = \"lost\";\n }\n if (this.missed >= 5) {\n this.gameOver(false);\n }\n }", "checkDeath() {\n if(this.lives <= 0) {\n this.isDead = true;\n }\n }", "function playerDeath(player, cause) {\n this.player.kill();\n this.player.x = this.characterX;\n this.player.y = this.characterY;\n playerLives--;\n this.death.play();\n this.livesCounter.text = '= ' + playerLives;\n if (playerLives == 0) {\n // game over!\n let gameOver = game.add.text(225, 250, 'GAME OVER!', {fill:'white', fontSize:'50px', boundsAlignH:'center', boundsAlignV:'middle'});\n gameOver.fixedToCamera = true;\n game.time.events.add(5000, quitGame, this);\n }\n else this.player.revive();\n }", "death(currentPlayer, consequence, channel){//Kills the player\n this.players = this.players.filter(player => {return player.id !== currentPlayer.id})\n channel.send(consequence.description).catch(err => {console.error(err);})\n this.utils.saveUniverse(this)\n }", "removeLife() {\r\n const lifeIcon = document.querySelector('[alt=\"Heart Icon\"]'); // returns first one it finds\r\n \r\n /* Apply heart icon css animation */\r\n lifeIcon.className = 'spin-heart';\r\n \r\n /* Allow animation to complete before changing to lost heart icon */\r\n window.setTimeout(() => {\r\n lifeIcon.className = null;\r\n lifeIcon.setAttribute('alt', 'Lost Heart Icon');\r\n lifeIcon.setAttribute('src', 'images/lostHeart.png');\r\n }, 750);\r\n \r\n this.missed += 1;\r\n if (this.missed === 4) this.gameOver(false);\r\n }", "removeLife() {\n //Selects all heart images in the DOM\n const healthPoints = document.querySelectorAll('img');\n \n //A heart is selected and changed to a 'lostHeart' based on the missed property index value\n healthPoints[this.missed].src = \"images/lostHeart.png\";\n \n // Increases the value of the missed property\n this.missed++;\n }", "removeLife() {\n const hearts = document.querySelectorAll('.tries');\n this.missed += 1;\n if (this.missed === 5) {\n this.gameOver('lose');\n } else {\n for (let i=0; i < this.missed; i++) {\n hearts[i].firstElementChild.setAttribute('src', 'images/lostHeart.png');\n }\n }\n }", "function isGameOver(){\n sounds.explosion.cloneNode().play();\n if(lives <= 0){\n triggerModal(overWindow);\n }\n else{\n lives--;\n livesElem.innerText = lives;\n document.querySelector('.footer-left').querySelector('.spaceship').remove()\n }\n}", "kill(){\r\n this.lives--;\r\n this.livesLost++;\r\n if(this.lives<0){\r\n this.gameOver = true;\r\n }else{\r\n this.resetBoard();\r\n }\r\n }", "function livesDecrease() {\n guessesLeft--;\n }", "removeLife() {\n //Store the value of 'img'\n let hearts = (document.querySelectorAll('img'));\n //Store the value of lost heart\n let gray = 'images/lostHeart.png';\n hearts[this.missed].src = gray\n //Missed guesses increase by 1\n this.missed++;\n //If missed guess is eaquals to 5\n if (this.missed === 5) {\n //Gameover\n this.gameOver()\n }\n }", "function checkPlayerDie()\n{\n if (gameChar_y > height)\n {\n stopGameMusic();\n gameSounds.died.play();\n \n if (lives > 0)\n { \n lives--;\n startGame();\n }\n } \n}", "function died() {\n if (lives == 0) {\n document.documentElement.style.setProperty('--blinkyAnimation', '0s');\n document.documentElement.style.setProperty('--pinkyAnimation', '0s');\n document.documentElement.style.setProperty('--inkyAnimation', '0s');\n document.documentElement.style.setProperty('--clydeAnimation', '0s');\n document.documentElement.style.setProperty('--ghostsWalking', '0s');\n hud.style.color = '#FE2502';\n hud.innerText = 'GAME OVER';\n siren.stopAudio();\n invincible.stopAudio();\n regenerating.stopAudio();\n } else {\n dotsBeforeExit = [\n [0, 0, 0],\n [7, 7, 7],\n [10, 10, 10],\n [15, 15, 15]\n ];\n pacmanGraphic.style.transform = 'scale(1)';\n initialize();\n }\n }", "removeLife() {\n let heart = document.querySelector(\"img[src='images/liveHeart.png']\");\n heart.src = \"images/lostHeart.png\";\n this.missed += 1;\n if(this.missed === 5){\n this.gameOver(this.checkForWin());\n }\n }", "checkCollisions() {\n livesTracker.innerHTML = player.lives;\n \n if (player.x < this.x + this.width &&\n player.x + player.width > this.x &&\n player.y < this.y + this.height &&\n player.height + player.y > this.y) {\n \n //if collide, moves player back to starting position, and -1 life.\n player.x = 200;\n player.y = 485;\n player.lives--;\n //if player life = 0 , game resets\n player.gameLost();\n }\n }", "function removeLife (){\n Images.frog.src = '../images/icons8-Poison-96.png'\n frogImages[lives - 1].remove()\n setTimeout(function(){\n Images.frog.src = '../images/frog.png'\n }, 700)\n x = 225\n y = 560\n counter = 60\n}", "function takeLife() {\n if (nodeListOfDivs[walker.index].classList.contains('life')) {\n nodeListOfDivs[walker.index].classList.remove('life')\n score = score + 2;\n audioWaterDrop.play();\n displayScore.innerHTML = score;\n }\n }", "function checkForDead() {\n if (mainPlayer.checkCollision(badguy)) {\n mainPlayer.setPosition(64, 64);\n mainPlayer.speed = 0;\n }\n }", "removeLife() {\n this.missed+=1;\n const liTries = document.getElementsByClassName(\"tries\");\n \n \n for (let i = 0; i < this.missed; i ++) {\n liTries[i].firstElementChild.src = \"images/lostHeart.png\";\n }\n \n if (this.missed === 5) {\n game.gameOver(false);\n }\n \n }", "function livesDown()\r\n{\r\n if(bonusHeartCount == 0)\r\n bonusHeartCount = 1;\r\n\r\n //change the relevent status from visable to hidden\r\n if(lives == 3){\r\n document.getElementById(\"firstLife\").style.visibility = \"hidden\";\r\n }\r\n else if(lives == 2){\r\n document.getElementById(\"secondLastLife\").style.visibility = \"hidden\";\r\n }\r\n else if(lives == 1){\r\n document.getElementById(\"lastLife\").style.visibility = \"hidden\";\r\n }\r\n lives--;\r\n\r\n //if the player stil have live - he didnt lost yet- then reset the board\r\n if(lives > 0)\r\n reset(board);\r\n}", "function resetPlayer() {\n\tif (lives > 0) {\n\t\tlives = lives - 1;\n\t\ttransform.position = startPosition;\n\t} else {\n\t\tgamestatusscript.gameLost();\n\t}\n}", "function checkIfDead() {\n if (player.hp <= 0) {\n console.log(\"death\");\n console.log(badEnding.stuff);\n // go back to start screen\n } else {\n // return to game\n }\n}", "removeLife() {\n // get all the li that has heart images\n let liLives = document.querySelector('#scoreboard ol').children;\n this.missed += 1;\n // Loops through the li with heart images to find the one that needs to be changed\n for (let i = 0; i < liLives.length; i++) {\n // Selecting image of li\n const heartImg = liLives[i].querySelector('img');\n // if missed is less than 5 AND heartimg.src includes liveHeart.png then replaces image with lostHeart\n if (this.missed < 5 && heartImg.src.includes(\"liveHeart.png\")) {\n heartImg.src = \"images/lostHeart.png\";\n break;\n\n } else if (this.missed >= 5){\n // Replaces the last heart image with lostHeart image \n heartImg.src = \"images/lostHeart.png\";\n this.gameOver(false);\n }\n }\n }", "function lose() {\n if (currentTime === 0 || (squares[currentIndex].classList.contains('c1')) || (squares[currentIndex].classList.contains('l5')) || (squares[currentIndex].classList.contains('l4'))) {\n result.innerHTML = 'YOU LOSE';\n squares[currentIndex].classList.remove('frog');\n clearInterval(timerId);\n document.removeEventListener('keyup', moveFrog);\n }\n }", "function die() {\n\t//If hes already dead -> do nothing\n\tif (!alive) return;\n\n\t//Set alive to false\n\talive = false;\n\n\t//Make screen black and white to signal death\n\tdocument.querySelector('canvas').classList.add('c-died');\n\n\t//Hide player\n\tplayer.setActive(false);\n\tplayer.setVisible(false);\n\n\t/**\n\t * If multiplayer send status update\n\t */\n\tif (multiplayer) {\n\t\tmqttClient.publish(\n\t\t\t`afloat/lobby/${lobbyId}/game`,\n\t\t\tJSON.stringify({\n\t\t\t\tclientId: clientId,\n\t\t\t\tstatus: 'died',\n\t\t\t\tscore: score\n\t\t\t})\n\t\t);\n\t\t//If both players are dead -> End Game\n\t\tif (!otherPlayerData.alive) {\n\t\t\tendGame();\n\t\t} else {\n\t\t\tdocument.querySelector('.js-deathscreen-popup__score').innerHTML = score;\n\t\t\tdocument.querySelector('.js-deathscreen-popup').classList.remove('u-hidden');\n\t\t}\n\t\t/**\n\t\t * If singleplayer End Game\n\t\t */\n\t} else {\n\t\tendGame();\n\t}\n}", "removeLife(){\n let pictureElement = document.getElementsByClassName('tries');\n this.missed += 1;\n //console.log(this.missed);\n if(this.missed == 1){\n pictureElement[4].firstElementChild.setAttribute('src', 'oop_game-v2/images/lostHeart.png');\n }\n if(this.missed == 2){\n pictureElement[3].firstElementChild.setAttribute('src', 'oop_game-v2/images/lostHeart.png');\n }\n if(this.missed == 3){\n pictureElement[2].firstElementChild.setAttribute('src', 'oop_game-v2/images/lostHeart.png');\n }\n if(this.missed == 4){\n pictureElement[1].firstElementChild.setAttribute('src', 'oop_game-v2/images/lostHeart.png');\n }\n if (this.missed == 5){\n pictureElement[0].firstElementChild.setAttribute('src', 'oop_game-v2/images/lostHeart.png');\n this.gameOver(false);\n }\n }", "function outOfBounds() {\n if (lives > 0) {\n lives--;\n } else {\n game = false;\n }\n }", "onPlayerRemoved(player) {\n if (this.#teamAlpha_.has(player)) {\n this.#teamAlphaScore_ -= this.#teamAlpha_.get(player);\n this.#teamAlpha_.delete(player);\n }\n \n if (this.#teamBravo_.has(player)) {\n this.#teamBravoScore_ -= this.#teamBravo_.get(player);\n this.#teamBravo_.delete(player);\n }\n }", "minus1Life() {\n console.log(\"entered\")\n if (this.lifesGroup.getTotalUsed() == 0) {\n console.log(\"game over\")\n this.scene.scene.stop();\n this.scene.music.stop();\n console.log(this.scene.pontos)\n this.scene.scene.start(\"GameOver\",{points: this.scene.pontos})\n\n } else {\n console.log(\" a tirar vida\")\n let heartzito = this.lifesGroup.getFirstAlive();\n heartzito.active = false;\n heartzito.visible = false;\n //heartzito.killAndHide()\n console.log(this.lifesGroup.getTotalUsed())\n }\n\n }", "function creatureDeathCheck() {\n if (creature.hp < 0) {\n creature.hp = 0;\n enemyHp.innerText = creature.name + ' hit points: ' + creature.hp;\n newMessage(player.name + ' has slain the ' + creature.name + '.');\n kills += 1;\n slain.innerText = 'Enemies slain: ' + kills;\n if (player.itemsBelt.length < 3) {\n itemDrop(creature);\n } else {\n player.itemsBelt = player.itemsBelt;\n }\n newEnemy();\n } else {\n creature.hp = creature.hp;\n }\n}", "function CheckDeath()\n{\n\tif (Health <= 0)\n\t{\n\t\tGameObject.Instantiate(Explosion, this.transform.position, Quaternion.identity);\n\t\tGameObject.Destroy(this.gameObject);\n\t\tBoss.GetComponent(AlienBoss).Health -= 1;\n\t\tDead = true;\n\t}\n}", "function lossCheck() {\n if (playerChar === \"roy\"){\n if (roy.health <= 0){\n alert(\"You lose!\")\n reset();\n \n }\n }\n\n if (playerChar === \"ridley\"){\n if (ridley.health <= 0){\n alert(\"You lose!\")\n reset();\n }\n }\n\n if (playerChar === \"cloud\"){\n if (cloud.health <= 0){\n alert(\"You lose!\")\n reset();\n }\n }\n\n if (playerChar === \"incineroar\"){\n if (incineroar.health <= 0){\n alert(\"You lose!\")\n reset();\n }\n }\n}", "setPlayerDead(playerID, reason) {\n\t\tthis.stage.removePlayer(playerID, reason);\n\t}", "endGame( curPlayer, curCellule ){\n\n if( curPlayer.curCellule != curCellule){\n console.log(\"heyeyyeye\")\n this.endTraj( curPlayer );\n\n curPlayer.addCellule(curCellule)\n }\n }", "function playerDeath() {\n if(player.health >0)\n {\n player.health -= 1;\n }\n else if (player.health <= 0)\n {\n player.tint = 10;\n reviveTimer = game.time.now + 2000;\n game.time.events.add(3000, slowHeroDeath, this)\n }\n}", "function onPlayerDeath(data){\n\t//find the player by id in the players array\n\tvar deadPlayer = playerById(data.id);\n\t//Player not found\n\tif(!deadPlayer){\n\t\tconsole.log(\"A player was claimed dead, but wasn't found\");\n\t\treturn;\n\t};\n\t//set the players dead variable to true\n\tconsole.log(\"On player death - \" + data.id);\n\tdeadPlayer.setDead(true);\n}", "frogHit(){\n\n if(this.lives <= 1){\n\n this.gameOverAudio.play()\n //display that you died\n this.gameBoard.deathOverlay.style.display=\"block\"\n this.stopTheCars()\n document.removeEventListener(\"keydown\", this.keyDownHandler)\n\n // reset the game (reload page) in 4 seconds\n reloadInterval = setInterval(this.resetGame, 4000)\n\n }else{\n\n \n this.pause()\n this.gameBoard.pauseOverlay.style.display = \"none\"\n let span = this.gameBoard.lifeOverlay.getElementsByTagName(\"span\")[0]\n span.innerText = `Lives remaining: ${this.lives - 1}`\n this.gameBoard.lifeOverlay.style.display=\"block\"\n document.removeEventListener(\"keydown\", this.keyDownHandler)\n\n lifeInterval = setInterval(this.removeLifeOverlay, 3000)\n \n // this.setupNextLife()\n }\n }", "function death()\n{\t\n\n\tplayer.velocity.y = 20;\t\n\tfor(var i = 0; i < boundaries.length; i ++) boundaries.get(i).velocity.x = 0;\n\tfor(var i = 0; i < rocks.length; i ++) rocks.get(i).velocity.x = 0;\n\tif(player.bounce(rocks)) player.velocity.y = 0;\n\tdeathScreen();\n}", "removeLife(){\r\n let hearts = document.querySelectorAll('.tries img')\r\n hearts[this.missed].setAttribute('src', 'images/lostHeart.png')\r\n this.missed +=1;\r\n if(this.missed === 5){\r\n this.gameOver()\r\n }\r\n}", "async onPlayerDeath(player, killer, reason) {}" ]
[ "0.748021", "0.7457874", "0.7362768", "0.73250383", "0.72790605", "0.7277616", "0.726063", "0.72018504", "0.7181556", "0.7088839", "0.70352113", "0.7019711", "0.6970146", "0.6924143", "0.6897564", "0.68833065", "0.6873854", "0.68714863", "0.6869394", "0.6844467", "0.6839018", "0.68316627", "0.68235636", "0.68214726", "0.6762877", "0.67531234", "0.67498404", "0.6748516", "0.67461216", "0.67445064", "0.6735343", "0.67343783", "0.6734088", "0.67335916", "0.6721581", "0.66923994", "0.66906655", "0.6671402", "0.6670715", "0.6662265", "0.6645804", "0.6626752", "0.6595709", "0.6586012", "0.65796226", "0.657433", "0.6564866", "0.65546197", "0.6554235", "0.654679", "0.65428895", "0.65277946", "0.6522482", "0.6511797", "0.650466", "0.64981145", "0.6484323", "0.64814055", "0.6478092", "0.6473957", "0.6472209", "0.6466628", "0.64417", "0.6430753", "0.64194024", "0.64123774", "0.63845086", "0.63838124", "0.6371849", "0.63629854", "0.63596916", "0.6352256", "0.6347374", "0.6347052", "0.6346157", "0.63431376", "0.6339413", "0.6336007", "0.63212496", "0.63206416", "0.6271269", "0.62423724", "0.62407625", "0.6235169", "0.6228891", "0.61963224", "0.61871463", "0.61670095", "0.6152846", "0.6152828", "0.6143656", "0.61376417", "0.61371356", "0.6133233", "0.6131962", "0.6131001", "0.6123057", "0.6114891", "0.6110664", "0.610938" ]
0.6510468
54
Disable selected letter's onscreen keyboard button If phrase dosent include guessed letter , add wrong (CSS class) If phrase includes the right letter, add correct (CSS class)
handleInteraction(keyButton) { const keys = document.getElementsByClassName('key'); for (let key of keys) { if (key.textContent === keyButton.textContent) { key.setAttribute('disabled', 'disabled'); } } const isMatched = this.activePhrase.checkLetter(keyButton.textContent); if (isMatched) { keyButton.classList.add('chosen'); this.activePhrase.showMatchedLetter(keyButton.textContent); if (this.checkForWin()) { this.gameOver(this.checkForWin()); } } else { keyButton.classList.add('wrong'); this.removeLife(); } console.log(keyButton); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function correctLetter(letter) {\n for (let key of keyboard) {\n if (key.textContent == letter) {\n key.classList.add(\"chosen\");\n key.disabled = true;\n }\n }\n}", "function incorrectLetter(letter) {\n for (let key of keyboard) {\n if (key.textContent == letter) {\n key.classList.add(\"wrong\");\n key.disabled = \"true\";\n }\n }\n}", "handleInteraction(letter) { \n //console.log(letter);\n if (this.activePhrase.checkLetter(letter)) {\n this.activePhrase.showMatchedLetter(letter);\n\n /* loops through keyboard elements to find which element matches \n the selected letter then adds the disabled class */\n const keyboardElements = document.getElementsByClassName('key');\n for (let i = 0; i < keyboardElements.length; i++) {\n if (keyboardElements[i].textContent === letter) {\n keyboardElements[i].setAttribute('disabled', true);\n keyboardElements[i].className = 'chosen';\n }\n }\n if (this.checkForWin()) {\n this.gameOver();\n const overlay = document.getElementById('overlay');\n overlay.className = 'win';\n const youWon = overlay.querySelector('.Win');\n youWon.style.display = 'block';\n }\n } \n \n else {\n /* loops through keyboard elements to find which element matches \n the selected letter then changes the class name to 'wrong' */\n const keyboardElements = document.getElementsByClassName('key');\n for (let i = 0; i < keyboardElements.length; i++) {\n if (keyboardElements[i].textContent === letter) {\n keyboardElements[i].disabled = 'true';\n keyboardElements[i].className = 'wrong';\n }\n }\n this.removeLife();\n const overlay = document.getElementById('overlay');\n overlay.className = 'lose';\n const youlost = overlay.querySelector('.lose');\n youlost.style.display = 'block';\n }\n }", "checkLetter(button, selectedLetter) {\n let isChosen = true;\n //iterates through phrase and adds 'chosen' class if there is a match\n if (this.phrase.indexOf(selectedLetter) >= 0) {\n $(button).addClass('chosen');\n //displays letter to user if they guessed right\n this.showMatchedLetter(selectedLetter)\n isChosen = true;\n //iterates through phrase and adds 'wrong' class if there is no match\n } else if ($(button).attr('class') === 'key') {\n $(button).addClass('wrong');\n isChosen = false;\n } \n return isChosen\n }", "handleInteraction(letter) {\n const buttons = document.querySelectorAll('.keyrow > button');\n if(this.activePhrase.checkLetter(letter.toLowerCase())){\n this.activePhrase.showMatchedLetter(letter.toLowerCase());\n for(let i = 0; i < buttons.length; i++) {\n if(buttons[i].innerHTML === letter.toLowerCase()){\n buttons[i].classList.add('chosen')\n }\n }\n if(this.checkWin()) {\n this.gameOver();\n }\n } else {\n for(let i = 0; i < buttons.length; i++) {\n if(letter.toLowerCase() === buttons[i].innerHTML) {\n buttons[i].disabled = true;\n buttons[i].classList.add('wrong');\n }\n }\n this.removeLife();\n }\n }", "function keyboardSetup() {\n for (let letters of keyboard) {\n letters.classList.remove(\"chosen\", \"wrong\");\n letters.disabled = false;\n }\n}", "handleInteraction(letter) {\n if ($(letter).data('clicked', true)) {\n $(letter).prop('disabled', true);\n\n if (this.activePhrase.checkLetter($(letter).text()) === true) {\n game.activePhrase.showMatchedLetter($(letter).text());\n $(letter).attr('class','chosen');\n game.checkForWin();\n if (game.checkForWin() === true) {\n game.gameOver(true);\n }\n \n } else if (this.activePhrase.checkLetter($(letter).text()) === false) {\n $(letter).attr('class','wrong');\n game.removeLife();\n }\n }\n}", "showMatchedLetter(keyPressed){\n let letters = document.getElementsByClassName('js-letter');\n for (let j = 0; j < letters.length; j++){\n if(letters[j].textContent === keyPressed){\n letters[j].classList.remove('hide');\n letters[j].classList.add('show');\n }\n }\n }", "handleInteraction(key){\n key.disabled = true;\n if (this.activePhrase.checkLetter(key.textContent) === true) {\n key.classList = \"chosen\";\n this.activePhrase.showMatchedLetter(key.textContent);\n if (this.checkForWin() === true) {\n this.gameOver(false);\n }\n } else {\n key.classList = \"wrong\";\n this.removeLife();\n }\n }", "handleInteraction(){\r\n //get letter and check if its on the active phrase \r\n \r\n const matchedLetter = this.activePhrase.checkLetter(event.target.textContent);\r\n \r\n if(matchedLetter){\r\n this.activePhrase.showMatchedLetter(event.target.textContent);\r\n event.target.classList.add('chosen');\r\n event.target.disabled = 'true';\r\n this.checkForWin();\r\n // show the letter if true else remove a life \r\n }\r\n else if(!matchedLetter){\r\n if(event.target.className === 'key'){\r\n event.target.disabled = 'true';\r\n event.target.classList.add('wrong');\r\n this.removeLife();\r\n \r\n }\r\n }\r\n\r\n }", "handleInteraction(e) {\r\n if (prevGuesses.indexOf(e) === -1){\r\n let clickedLetter = (e)\r\n let buttons = document.getElementsByClassName('key')\r\n if(this.activePhrase.checkLetter(splitPhraseArray,clickedLetter)){\r\n for(let i = 0; i < buttons.length; i++){\r\n if(buttons[i].textContent === clickedLetter){\r\n buttons[i].disabled = true;\r\n buttons[i].classList.add('chosen')\r\n }\r\n }\r\n } else {\r\n for(let i = 0; i < buttons.length; i++){\r\n if(buttons[i].textContent === clickedLetter){\r\n buttons[i].disabled = true;\r\n buttons[i].classList.add('wrong')\r\n prevGuesses.push(clickedLetter);\r\n this.removeLife();\r\n }\r\n }\r\n }\r\n this.activePhrase.showMatchedLetter(clickedLetter)\r\n if(this.checkForWin()){\r\n this.gameOver()\r\n };\r\n }\r\n }", "handleInteraction(button) {\r\n button.setAttribute('disabled', '');\r\n\r\n const letter = button.textContent;\r\n const letterInPhrase = game.activePhrase.checkLetter(letter);\r\n\r\n if (letterInPhrase) {\r\n button.classList.add('chosen');\r\n this.activePhrase.showMatchedLetter(letter);\r\n if (this.checkForWin()) this.gameOver(true);\r\n \r\n } else {\r\n button.classList.add('wrong');\r\n this.removeLife();\r\n }\r\n\r\n }", "showMatchedLetter(correctLetter){\n correctLetter.classList.remove('hide');\n correctLetter.classList.add('show');\n }", "function inputFieldClass() {\n if (event.key >= 'a' && event.key <= 'z') {\n var inputSlice = input.value + event.key;\n var currentWordSlice = randomWords[currentWord].slice(0, inputSlice.length);\n input.className = inputSlice === currentWordSlice ? '' : 'wrong';\n }else if (event.key === 'Backspace') {\n var inputSlice = event.ctrlKey ? '' : input.value.slice(0, input.value.length - 1);\n var currentWordSlice = randomWords[currentWord].slice(0, inputSlice.length);\n input.className = inputSlice === currentWordSlice ? '' : 'wrong';\n } else if (event.key === ' ') {\n input.className = '';\n }\n }", "handleInteraction(button) {\n const letter = button.innerHTML; \n const checkLetter = this.activePhrase.checkLetter(letter); \n button.setAttribute('disabled',true);\n if (checkLetter) { \n button.classList.add('chosen');\n game.activePhrase.showMatchedLetter(letter);\n if (this.checkForWin()) {\n this.gameOver(true);\n }\n } else { \n button.classList.add('wrong');\n this.removeLife();\n }\n\n }", "checkLetter(){\n /** will correctly match if letter is on the current phrase**/\n let matched = this;\n let phraseLi = document.getElementById(\"phrase\").getElementsByTagName(\"li\");\n $('.keyrow button').bind('click', function(){\n for (var i = 0; i < phraseLi.length; i++) {\n if ($(this).text() === phraseLi[i].innerHTML) {\n $(this).addClass(\"phraseLetters\");\n phraseLi[i].classList.add(\"correct\");\n matched.showMatchedLetter();\n }\n }\n })\n }", "showMatchedLetter(char) {\r\n const letters = document.getElementsByClassName('letter');\r\n for (let i = 0; i < letters.length; i++) {\r\n if (char === letters[i].textContent) {\r\n letters[i].classList.add(\"show\");\r\n }\r\n }\r\n }", "handleInteraction(button) {\n\n let letter = button.innerHTML;\n button.disabled = true;\n \n if(this.activePhrase.checkLetter(letter)){\n button.className = \"chosen\";\n this.activePhrase.showMatchedLetter(letter);\n if(this.checkForWin()) {\n this.gameOver(true);\n }\n } else { //else if the letter is is not the activePhrase\n button.className = \"wrong\"\n this.removeLife()\n }\n\n }", "handleInteraction(key) {\r\n key.disabled = true;\r\n if (this.activePhrase.checkLetter(key.textContent) == false) {\r\n key.className += ' wrong';\r\n this.removeLife();\r\n } else if ((this.activePhrase.checkLetter(key.textContent))) {\r\n key.className += ' chosen';\r\n this.activePhrase.showMatchedLetter(key.textContent);\r\n if (this.checkForWin() === true) {\r\n this.gameOver();\r\n };\r\n }\r\n }", "showMatchedLetter(letter) {\n const list = document.getElementsByClassName('hide letter');\n for (const li of list) {\n if (li.textContent === letter.textContent) {\n li.className = 'show';\n letter.classList.add(\"chosen\");\n letter.disabled = true;\n }\n }\n // called twice to fix bug: the same consecutive letter was not being revealed, i.e., in the word `call` guessing l would only display the first l.\n for (const li of list) {\n if (li.textContent === letter.textContent) {\n li.className = 'show';\n letter.classList.add(\"chosen\");\n letter.disabled = true;\n }\n }\n }", "handleInteraction(button) {\n let clickedButton = button; \n let letter = button.innerText;\n clickedButton.disabled = true;\n\n if(!this.activePhrase.checkLetter(letter)) {\n clickedButton.classList.add(\"wrong\");\n this.removeLife();\n } else {\n clickedButton.classList.add(\"chosen\");\n this.activePhrase.showMatchedLetter(letter);\n this.checkForWin();\n }\n }", "handleInteractions(button, letter) {\n button.disabled = true;\n //If the guess is right, mark keyboard letter as chosen and show matched letters in phrase\n if (this.activePhrase.checkLetter(letter)) {\n button.classList.add('chosen');\n this.activePhrase.showMatchedLetter(letter);\n //If the guess reveals the full phrase, the game is over!\n if (this.checkForWin()) {\n this.gameOver();\n }\n //If the guess is wrong, disable keyboard letter by marking as wrong and remove a life\n } else {\n button.classList.add('wrong');\n this.removeLife();\n }\n }", "showMatchedLetter(letter){\r\n $(letter).addClass('show');\r\n // display the char of the corresponding letters check if game is won\r\n }", "showMatchedLetter(l) {\r\n\r\n let letterToBeShown = game.activePhrase.toLowerCase().split(\"\").find(i => i === l);\r\n let listOfDOMElementLetters = document.getElementsByClassName(letterToBeShown);\r\n for (let i = 0; i < listOfDOMElementLetters.length; i++) {\r\n listOfDOMElementLetters[i].className = \"show letter \" + letterToBeShown;\r\n }\r\n }", "handleInteraction(clickedElement, method) {\n\n // define checkLetter to be used \n // to hold if the letter guessed is correct or not\n let checkLetter;\n if(method === \"virtual\") { // virtual keyboard used\n\n // check to see if guessed correct letter\n checkLetter = this.activePhrase.checkLetter(clickedElement.textContent);\n \n // disable the letter button clicked\n clickedElement.disabled = true;\n \n\n if (checkLetter) { // guessed correct letter\n // add css class \"chosen\"\n clickedElement.classList.add(\"chosen\");\n\n // show guessed letter on the UI\n this.activePhrase.showMatchedLetter(clickedElement.textContent);\n\n // check if player won the game\n if(this.checkForWin()) {\n // end the game\n this.gameOver(\"won\");\n }\n\n } else {\n // add css class \"wrong\"\n clickedElement.classList.add(\"wrong\");\n\n // remove a life\n this.removeLife();\n\n }\n } else { // physical keyboard used\n \n // virtualButton will hold the virtual button that holds the letter that was guessed\n let virtualButton;\n\n // reference all qwerty buttons\n const $qwertyButtons = $(\"#qwerty button\");\n\n // iterate through the virtual buttons to compare with the letter guessed\n $qwertyButtons.each( (i, el) => {\n\n // let's find the button that holds the letter guessed\n if(clickedElement === el.textContent) {\n virtualButton = el;\n }\n });\n\n // disable button \n if(virtualButton.disabled === false) {\n\n // check to see if guessed correct letter\n checkLetter = this.activePhrase.checkLetter(clickedElement);\n if(checkLetter) {\n // add css class \"chosen\"\n virtualButton.classList.add(\"chosen\");\n \n // show guessed letter\n this.activePhrase.showMatchedLetter(clickedElement);\n \n // check if player won game\n if(this.checkForWin()) {\n this.gameOver(\"won\");\n }\n } else {\n // add css class \"wrong\"\n virtualButton.classList.add(\"wrong\");\n \n // remove a life for wrong guesses\n this.removeLife();\n }\n }\n\n // disable virtual key\n virtualButton.disabled = true;\n }\n }", "function checkLetter(guess) {\n const letterAnswers = document.querySelectorAll('.letter');\n const li = document.querySelectorAll('.letter');\n let match;\n for (let i = 0; i < letterAnswers.length; i +=1) {\n let show = letterAnswers[i].textContent;\n if (show === guess) {\n li[i].classList.add('spin');\n li[i].className += ' show';\n match = show;\n }\n }\n return match;\n }", "handleInteraction(letter, eventText){\n\t\tletter.disabled = true; \n\t\tconst letterClicked = eventText;\n\t\tconst inPhrase = this.activePhrase.checkLetter(letterClicked);\n\t\tif(inPhrase){\n\t\t\tletter.className = \"key chosen\";\n\t\t\tthis.activePhrase.showMatchedLetter(letterClicked);\n\t\t\tif(this.checkForWin()){\n\t\t\t\tthis.gameOver(true);\n\t\t\t}\n\t\t}else{\n\t\t\tletter.className = \"key wrong\";\n\t\t\tthis.removeLife()\n\t\t};\n\t}", "showMatchedLetter(letter) {\r\n const phraseDivUl = document.getElementById('phrase').firstElementChild.children;\r\n for (let i = 0; i < phraseDivUl.length; i++) {\r\n if (letter === phraseDivUl[i].textContent) {\r\n phraseDivUl[i].className = `show letter ${phraseDivUl[i].textContent}`;\r\n }\r\n }\r\n }", "showMatchedLetter(letter) {\r\n const phrase = document.querySelectorAll(\".letter\");\r\n phrase.forEach((char) => {\r\n if (char.textContent === letter) {\r\n char.classList.add(\"show\");\r\n char.classList.remove(\"hide\");\r\n }\r\n });\r\n }", "handleInteraction(keyboardButton) {\r\n if (this.ready) {\r\n keyboardButton.disabled = true;\r\n if (this.activePhrase.phrase.includes(keyboardButton.textContent)) {\r\n keyboardButton.classList.add(\"chosen\");\r\n this.activePhrase.showMatchedLetter(keyboardButton.textContent);\r\n if (this.checkForWin()) {\r\n this.gameOver(true);\r\n }\r\n } else {\r\n keyboardButton.classList.add(\"wrong\");\r\n this.removeLife();\r\n }\r\n }\r\n }", "showMatchedLetter(letter) {\n const listOfLetters = document.getElementsByClassName(`hide letter ${letter}`);\n this.listOfLettersLenght = listOfLetters.length;\n \n while (listOfLetters.length) {\n listOfLetters[0].className = \"show\";\n }\n }", "handleInteraction(button) {\n const currentPhrase = this.activePhrase.phrase\n const letter = button.textContent\n button.disabled = true;\n\n if(!currentPhrase.split('').includes(letter)) {\n // if the selected letter is NOT in the phrase, do this\n button.className = 'wrong'\n this.removeLife()\n } else {\n button.className = 'chosen'\n this.activePhrase.showMatchedLetter(letter)\n if (this.checkForWin()) {\n this.gameOver(true)\n }\n }\n }", "function checkLetter() {\n const sContainer = selectElement(\".secret-word\");\n let word = secretWord.toUpperCase();\n\n //Check if word includes this letter\n if (word.includes(this.textContent)) {\n this.classList.add(\"true\");\n let indexArr = [];\n //Get all indexs where we must replace symbol\n for (let i = 0; i < secretWord.length; i++) {\n let symbol = word.indexOf(this.textContent, i);\n if (symbol != -1) {\n indexArr.push({ index: symbol });\n }\n }\n //Replace symbols\n for (let i = 0; i < indexArr.length; i++) {\n let wordSize = (+indexArr[i].index) ?\n this.textContent.toLowerCase() : this.textContent;\n sContainer.textContent = sContainer.textContent\n .replaceAt(indexArr[i].index, wordSize);\n }\n\n if (sContainer.textContent == secretWord) {\n wictoryFun();\n }\n }\n else {\n selectElement(\".hangman img\").classList.add(\"hide\");\n selectElement(\".hangman img\").src = `image/${count}.png`;\n setTimeout(() => selectElement(\".hangman img\").classList.remove(\"hide\"), 400);\n this.classList.add(\"false\");\n count++;\n if (count == 13) {\n setTimeout(overFun, 1500);\n };\n }\n this.removeEventListener('click', checkLetter);\n}", "function checkLetter(guess) {\n\tmatch = null;\n\tlet letters = document.querySelectorAll('.letter'); //unrevealed letters collection\n\tfor (i = 0; i < letters.length; i++) {\n\t\tif (guess.textContent == letters[i].textContent) {\n\t\t\tletters[i].classList.add('show');\n\t\t\tmatch = true;\n\t\t}\n\t}\n\treturn match;\n}", "handleInteraction(button) {\n button.disabled = true;\n const letter = button.textContent;\n if(this.activePhrase.checkLetter(letter) === false) {\n button.className = 'key wrong';\n this.removeLife();\n } else {\n button.className = 'key chosen';\n this.activePhrase.showMatchedLetter(letter);\n if(this.checkForWin()) {\n this.gameOver(true);\n }\n }\n }", "showMatchedLetter(letter) {\n const letterCollection = document.getElementById('phrase').firstElementChild.children;\n for (let i = 0; i < letterCollection.length; i++) {\n if (letterCollection[i].textContent.toLowerCase() === letter) {\n letterCollection[i].className = 'show letter ' + letter;\n }\n }\n }", "showMatchedLetter(guess){\n //phrase colors \n let phraseLetter = document.querySelectorAll('li.hide.letter');\n phraseLetter.forEach(letter =>{\n if(guess == letter.textContent.toLowerCase()){\n letter.classList.add('show');\n letter.classList.remove('hide');\n }\n })\n }", "showMatchedLetter(e) {\n let lettersToCheck = document.getElementsByClassName(e.target.innerText)\n for (i = 0; i < lettersToCheck.length; i++) {\n\n lettersToCheck[i].classList.remove(\"hide\")\n lettersToCheck[i].classList.add(\"show\")\n };\n }", "showMatchedLetter(letter){\n const correctPhrase = document.querySelectorAll('#phrase ul li ');\n for(let i = 0; i<correctPhrase.length;i++){\n if(correctPhrase[i].innerHTML === letter) {\n correctPhrase[i].className = 'show'; \n }\n }\n }", "showMatchedLetter(e) {\n \t\t$('li').parent().children(`.${this.letterGuess}`).removeClass('hide').addClass('show');\n\n\t}", "function checkLetter(button) {\nlet letterMatch = null;\n\n for (var i = 0; i < document.querySelectorAll('.letter').length; i++) {\n if (button.innerText.toLowerCase() === document.querySelectorAll('.letter')[i].innerText.toLowerCase()) {\n document.querySelectorAll('.letter')[i].classList.add(\"show\");\n letterMatch = \"match\";\n } \n}\nreturn letterMatch\n}", "function checkLetter(guessBtn) {\n // Loop through the characters in the phrase\n for (let i = 0; i < li.length; i++) {\n // Make sure a letter is chosen\n if ( li[i].classList.contains('letter') ) {\n\n // Check the textContent of the button to see if there's a match\n if (li[i].textContent === guessBtn) {\n // Add the 'show' class\n li[i].classList.add('show');\n // Save the correct guess\n letterFound = guessBtn;\n }\n }\n }\n\n // Return the matching letter guessed correct;\n // Otherwise, return null for incorrect guess\n return letterFound;\n}", "showMatchedLetter(){\n $('.correct').css('color', 'black');\n $('.correct').css('background-color', 'green');\n $('.correct').css('text-shadow', '4px black');\n }", "function checkLetter(arr) { \n let buttonClicked = arr;\n let phraseLetters = document.getElementsByClassName('letter');\n let letterMatched = null;\n\n for (let i = 0; i < phraseLetters.length; i += 1) {\n if (buttonClicked.toUpperCase() === phraseLetters[i].textContent.toUpperCase()) { \n phraseLetters[i].className += ' show';\n letterMatched = buttonClicked;\n }\n }\n\n return letterMatched;\n}", "function checkLetter(event) {\n let char = document.querySelectorAll('.letter');\n let result = null;\n\n for (let i = 0; i < char.length; i++) {\n if (char[i].textContent == event.textContent) {\n\n char[i].classList.add(\"show\");\n \tchar[i].style.boxShadow = '5px 4px 10px 0px #9e9e9e';\n \tchar[i].style.transition = 'ease 0.5s';\n\n result = event;\n }\n }\n return result;\n}", "handleInteraction(button){\n const currLetter = button.innerText;\n button.disabled = true;\n\n if(this.activePhrase.checkLetter(currLetter)){\n button.classList.add('chosen');\n this.activePhrase.showMatchedLetter(currLetter);\n if(this.checkForWin()){\n this.gameOver(this.checkForWin());\n }\n } else {\n button.classList.add('wrong');\n this.removeLife();\n }\n }", "handleInteraction(button) {\r\n const keyButton = document.querySelector(`button[value=\"${button}\"]`);\r\n const activeLetters = this.activePhrase.phrase.split('');\r\n const selectedLetter = document.querySelectorAll(`li.show.letter`);\r\n\r\n this.activePhrase.showMatchedLetter(button);\r\n\r\n if (activeLetters.includes(keyButton.value)) {\r\n keyButton.className = 'chosen';\r\n keyButton.disabled = true;\r\n if (this.checkForWin()) {\r\n this.gameOver(true);\r\n }\r\n } else if (activeLetters.includes(keyButton.value) === false) {\r\n keyButton.className = 'wrong';\r\n keyButton.disabled = true;\r\n this.removeLife();\r\n }\r\n\r\n if (this.missed === 5) {\r\n this.gameOver(this.checkForWin());\r\n }\r\n\r\n }", "handleInteraction(button) {\r\n let letter = button.textContent;\r\n let isLetterInPhrase = false;\r\n button.disabled = true;\r\n if(this.activePhrase){\r\n isLetterInPhrase = this.activePhrase.checkLetter(letter);\r\n if(isLetterInPhrase){\r\n button.classList.add('chosen');\r\n this.activePhrase.showMatchedLetter(letter);\r\n if(this.checkForWin()){\r\n this.gameOver(true);\r\n }\r\n } else {\r\n button.classList.add('wrong');\r\n this.removeLife();\r\n }\r\n }\r\n }", "showMatchedLetter(letter) {\r\n const letters = document.querySelectorAll(`.hide.${letter}`);\r\n for (let i=0; i<letters.length; i+=1) {\r\n if (letter === letters[i].textContent.toLowerCase()) {\r\n letters[i].className = `show letter ${letter}`;\r\n }\r\n }\r\n }", "function checkLetter(clickedButton) {\n let match = null;\n document.querySelectorAll('.letter').forEach( (letter) => {\n if (clickedButton === letter.textContent.toLowerCase() ) {\n letter.classList.add('show');\n match = clickedButton;\n }\n });\n return match;\n}", "function rightType(char) {\n //display right letter\n answerList.forEach(span => {\n if (span.classList.contains(char)) {\n span.style.color = 'black';\n }\n })\n //delete from answerletter\n answerLetter.forEach(ans => {\n if (ans === char) {\n const idx = answerLetter.indexOf(ans);\n answerLetter.splice(idx, 1);\n }\n })\n if (answerLetter.length === 0) {\n showRefresh('Clear! 😁');\n }\n}", "function checkLetter(button) {\n const letters = document.querySelectorAll('.letter');\n let match = null;\n let chosenLetter = button.textContent.toUpperCase();\n\n for (let i = 0; i < letters.length; i++) {\n if (chosenLetter === letters[i].textContent) {\n letters[i].className += ' show';\n match = letters[i].textContent;\n }\n }\n return match;\n}", "function checkLetter(button) {\n let phraseElements = document.querySelectorAll('li.letter');\n let match = false;\n for(let i = 0; i < phraseElements.length; i++) {\n if (phraseElements[i].textContent.toUpperCase() === button.textContent.toUpperCase()) {\n phraseElements[i].classList.add('show');\n match = true;\n }\n }\n return match;\n}", "handleInteraction(button){\r\n button.setAttribute(\"disabled\", \"\");\r\n if(this.activePhrase.checkLetter(button.innerText)){\r\n button.className = 'chosen';\r\n this.activePhrase.showMatchLetter(button.innerText)\r\n if(this.checkForWin()){\r\n this.gameOver();\r\n }\r\n } else {\r\n button.className = 'wrong';\r\n this.removeLife();\r\n }\r\n }", "handleInteraction(button) {\r\n let clicked = button\r\n //console.log(clicked);\r\n clicked.disabled = true;\r\n\r\n if (this.activePhrase.checkLetter(clicked.textContent)) {\r\n //console.log('checked Letter');\r\n this.activePhrase.showMatchedLetter(clicked.textContent);\r\n clicked.className = 'chosen';\r\n this.checkForWin();\r\n if (this.checkForWin()) {\r\n this.gameOver(true);\r\n \r\n }\r\n \r\n \r\n } else {\r\n clicked.className = 'wrong';\r\n this.removeLife();\r\n \r\n \r\n }\r\n }", "handleInteraction(e) {\n // If the event is coming from physical keyboard and catching with 'keydown'\n if (e.type == \"keydown\") {\n const char = qwerty.querySelectorAll(\"button\"); //find all the buttons\n for (let i = 0; i < char.length; i++) {\n const button = char[i];\n const buttonText = button.innerText;\n if (e.key.toLowerCase() == buttonText) {\n // if the buttons has the text of the key pressed\n\n button.disabled = true; //disable the button\n\n if (this.activePhrase.checkLetter(buttonText)) {\n //if active phrase has the button text\n button.className = \"chosen\"; //change the class of button to chosen\n this.activePhrase.showMatchedLetter(buttonText); //display the matched letter\n if (this.checkForWin()) {\n this.gameOver(true); //check if the user is won. then display gameOver\n }\n } else {\n if (button.className != \"wrong\") {\n //if the button class is not already wrong\n button.className = \"wrong\"; //set it to wrong\n this.removeLife(); //remove life\n }\n }\n }\n }\n //If the event is coming the mouse click\n } else if (e.type == \"click\") {\n e.disabled = true;\n const button = e.target;\n\n const buttonText = button.textContent;\n\n if (this.activePhrase.checkLetter(buttonText)) {\n //if active phrase has the button text\n button.className = \"chosen\"; //change the class of button to chosen\n this.activePhrase.showMatchedLetter(buttonText); //display the matched letter\n if (this.checkForWin()) {\n this.gameOver(true); //check if the user is won. then display gameOver\n }\n } else {\n if (button.className != \"wrong\") {\n //if the button class is not already wrong\n button.className = \"wrong\"; //set it to wrong\n this.removeLife(); //remove life\n }\n }\n }\n }", "checkLetter(letter) {\r\n let keyboard = document.getElementById('qwerty');\r\n //check if button is clicked\r\n if (this.phrase.includes(letter)) {\r\n return true;\r\n // console.log(true)\r\n // this.showMatchedLetter(letter)\r\n } else {\r\n return false;\r\n }\r\n }", "showMatchedLetter(letter) {\n const selectedLetter = document.querySelectorAll(\".letter\");\n selectedLetter.forEach(element => {\n if (element.innerHTML === letter) {\n element.className = \"show\";\n }\n });\n }", "showMatchedLetter(letter) {\r\n\r\n // Get the matchedLetters that have a class name letter\r\n const matchedLetters = document.getElementsByClassName(letter);\r\n\r\n // Loop through the matchedLetters and replace the hide class with show\r\n for (let k = 0; k < matchedLetters.length; k++) {\r\n matchedLetters[k].className = matchedLetters[k].className.replace(/\\bhide\\b/g, \"show\");\r\n } \r\n }", "function disableTheLetters(letter) {\n letter.removeClass(\"btn-dark\");\n letter.addClass(\"btn-danger\");\n letter.attr(\"disabled\", \"disabled\");\n letter.prop(\"disabled\", true);\n }", "function checkLetter(button) {\n let letters = document.querySelectorAll(\".letter\");\n let match = null;\n for (i = 0; i < letters.length; i++) {\n if (button === letters[i].textContent) {\n letters[i].classList.add(\"show\");\n match = true;\n }\n }\n return match;\n}", "showMatchedLetter(letter) {\n const letterSpace = document.getElementsByClassName(`hide letter ${letter}`);\n\n // keeps the length of letterSpace array value constant\n const letterLength = letterSpace.length;\n \n /* loops through all classes with the 'hide letter (letter parameter)' \n and changes the class name to 'show letter (letter parameter)'*/\n for (let i = 0; i < letterLength; i++) {\n letterSpace[0].className = `show letter ${letter}`;\n }\n }", "showMatchedLetter(letter) {\n const phraseLis = document.getElementById('phrase').children[0].children;\n\n for(let i = 0; i < phraseLis.length; i++) {\n if(phraseLis[i].textContent.includes(letter)) {\n phraseLis[i].className = 'show';\n }\n }\n }", "handleInteraction(key) {\n $key.eq(key).prop('disabled', true);\n if (gamePhrase.checkLetter(key) === 0) {\n $key.eq(key).addClass('wrong');\n game.removeLife();\n } else {\n $key.eq(key).addClass('chosen');\n if (this.checkForWin()) {\n this.gameOver();\n }\n }\n }", "function checkLetter(letter) {\n // Get all li elements with class: letter\n const liLetters = document.getElementsByClassName('letter');\n // Other variables used in function \n let letterFound = null;\n \n // Loop through all li letters and check if match with pressed letter\n for (let i = 0; i < liLetters.length; i++) {\n if (liLetters[i].textContent === letter) {\n liLetters[i].className += ' ' + 'show';\n letterFound = liLetters[i].textContent;\n }\n } \n // If the letter is guessed return the letter or otherwise null\n return letterFound;\n}", "handleInteraction(button){\n const key = button.textContent;\n const checkKey = this.activePhrase.checkLetter(key);\n\n if (checkKey) {\n button.disabled = true;\n button.className = 'chosen';\n this.activePhrase.showMatchedLetter(key);\n this.checkForWin()\n \n if (this.checkForWin() === true) {\n this.gameOver();\n }\n \n \n } else if (!checkKey) {\n this.removeLife()\n button.disabled = true;\n button.className = 'wrong';\n \n }\n this.resetGame()\n \n }", "function checkLetter(keyLetter) {\n let list = document.querySelectorAll('.letter');\n let correctLetter = false;\n \n for (let i = 0; i < list.length; i++) {\n \n let listLetter = list[i].textContent;\n \n if (listLetter === keyLetter) {\n correctLetter = true;\n list[i].classList.add('show');\n // CSS transistion added for exceed expectations\n list[i].style.transition = 'all 2s';\n } \n }\n \n if (correctLetter === false) {\n missed += 1;\n } if (missed == 1) {\n life[0].style.display = 'none';\n } if (missed == 2) {\n life[1].style.display = 'none';\n } if (missed == 3) {\n life[2].style.display = 'none';\n } if (missed == 4) {\n life[3].style.display = 'none';\n } if (missed == 5) {\n life[4].style.display = 'none';\n }\n \n return correctLetter;\n}", "function handleGuess(chosenLetter) {\r\n guessed.indexOf(chosenLetter) === -1 ? guessed.push(chosenLetter) : null;\r\n document.getElementById(chosenLetter).setAttribute('disabled', true);\r\n\r\n if (answer.indexOf(chosenLetter) >= 0) {\r\n guessedWord();\r\n checkIfGameWon();\r\n } else if (answer.indexOf(chosenLetter) === -1) {\r\n mistakes++;\r\n updateMistakes();\r\n checkIfGameLost();\r\n updatedinoPicture();\r\n }\r\n}", "handleInteraction(button) {\r\n button.setAttribute('disabled', 'true');\r\n if (this.activePhrase.phrase.search(button.textContent) === -1) {\r\n button.classList.add('wrong');\r\n this.removeLife();\r\n \r\n } else {\r\n button.classList.add('chosen');\r\n this.activePhrase.showMatchedLetter(button.textContent);\r\n let win = this.checkForWin();\r\n\r\n if (win) {\r\n this.gameOver(win)\r\n }\r\n }\r\n }", "handleInteraction(button) {\n let letter = button.textContent;\n if(this.activePhrase.checkLetter(letter)) {\n if(!button.classList.contains('chosen')) {\n button.classList.add('chosen');\n button.disabled = true;\n this.activePhrase.showMatchedLetter(letter);\n if(this.checkForWin()) {\n this.gameOver(true);\n }\n }\n \n } else {\n if(!button.classList.contains('wrong')) {\n button.classList.add('wrong');\n button.disabled = true;\n this.removeLife();\n }\n }\n }", "showMatchedLetter(letter) {\n for (let i = 0; i < ul.children.length; i++) {\n let letterVisible = document.querySelector(`#phrase > ul > li.hide.letter.${letter}`);\n // if letter matches set class to show letter\n if (letterVisible !== null) {\n letterVisible.className = `show letter ${letter}`;\n }\n }\n }", "function correctWordGuess() {\n\tlet letters = document.querySelectorAll(\".letter\");\n\n\tfor (let i = 0; i < guess.length; i++) {\n\t\tletters[i].innerText = guess[i];\n\t\tletters[i].style.borderBottom = \"none\";\n\t}\n}", "handleInteraction(button) {\n button.disabled = true;\n if (this.activePhrase.checkLetter(button.textContent) === true) {\n this.activePhrase.showMatchedLetter(button.textContent);\n button.className = \"chosen\";\n if (this.checkForWin()) {\n setTimeout( () => this.gameOver(true), 500);\n }\n } else if (this.activePhrase.checkLetter(button.textContent) === false) {\n this.removeLife();\n button.className = \"wrong\";\n }\n }", "showMatchedLetter(guess) {\r\n\t\t// selects all the elements with the class matching the letter guessed\r\n\t\tlet classSelector = `.${guess}`;\r\n\t\t// removes the hide class and adds the show class\r\n\t\t$(classSelector).removeClass(\"hide\").addClass(\"show\");\r\n\t}", "stopLetterSelect(letter) {\n this.isSelecting = false\n\n // Let's check to see if they selected an actual word :)\n if (\n this.firstLetter &&\n this.endLetter &&\n this.firstLetter !== this.endLetter &&\n (this.firstLetter.data.startWord || this.endLetter.data.startWord) &&\n this.checkLetterAlignment(this.endLetter)\n ) {\n var result = this.checkSelectedLetters()\n\n if (result) {\n this.highlightCorrectWord(result)\n this.foundWords.push(result.word)\n }\n\n // Check word list, game won?\n if (this.foundWords.length === this.solution.length) {\n this.gameWon()\n }\n }\n\n this.grid.setAll('frame', 0)\n\n this.clearLine()\n }", "function checkLetter(button) {\n const letter = $(button)[0].textContent;\n let letterFound = null;\n\n $.each($('.letter'), function(index, value) {\n\n if (value.textContent.toLowerCase() === letter) {\n $(value).addClass('show');\n letterFound = letter;\n }\n }); // end of each\n\n return letterFound;\n} // end of checkLetter", "function gameOver() {\r\n \r\n for (i = 0; i < length; i++) {\r\n if (letterSpan[i].innerHTML == \"_\") {\r\n letterSpan[i].innerHTML = word[i];\r\n letterSpan[i].className = \"missing\";\r\n }\r\n \r\n }\r\n\r\n disableInput = true\r\n document.getElementsByTagName(\"html\")[0].className = \"gameOver\";\r\n }", "function checkLetter(clickedButton) {\n const letterMatch = document.querySelectorAll(\".letter\");\n let match = null;\n for (let i = 0; i < letterMatch.length; i++) {\n if (letterMatch[i].innerHTML.toLowerCase() === clickedButton) {\n find = clickedButton;\n letterMatch[i].classList.add(\"show\");\n match = true;\n }\n }\n return match;\n}", "function checkLetter(button) {\r\n const fontClicked = button.innerHTML;\r\n var letterFound = null;\r\n\r\n for (let i = 0; i < letter.length; i++){\r\n if (fontClicked === letter[i].innerHTML.toLowerCase()) {\r\n letter[i].classList.add('show');\r\n letterFound = true;\r\n letterFound = fontClicked;\r\n }\r\n }\r\n return letterFound;\r\n}", "function checkGuess(letter) {\n //if letter is not in guessedLetters array then push the letter to the array, and if the letter isn't in the answer word then -1 the numGuessesRemaining\n if (guessedLetters.indexOf(letter) === -1 && ansWord.indexOf(letter) === -1) {\n guessedLetters.push(letter);\n numGuessesRemaining--;\n //if numGuessesRemaining is 3 or less then change the color\n if (numGuessesRemaining <=3) {\n document.getElementById(\"numGuesses\").style.color = \"#e12d2e\";\n }\n //if letter is in answer then replace the positioned \"_\" with the letter\n } else {\n for (var i = 0; i < ansWord.length; i++) {\n if (letter === ansWord[i]) {\n ansWordArr[i] = letter;\n }\n }\n }\n }", "function selectLetter(e){\n var leftLetter = currentLetter.dataset.left;\n var upLetter = currentLetter.dataset.up;\n var downLetter = currentLetter.dataset.down;\n var rightLetter = currentLetter.dataset.right;\n var userKey = \"e.keycode\";\n\n\n if(userKey === 37){\n formatPuzzle(leftLetter)\n }else if(userKey === 38){\n formatPuzzle(upLetter)\n } else if (userKey === 39 || userKey === 9){\n formatPuzzle(rightLetter)\n }else if(userKey === 40 || userKey === 13){\n formatPuzzle(downLetter)\n }else if(userKey === 8 || userKey === 46){\n currentLetter = \"\";\n }else if (userKey === 32){\n switchTypeDirection()\n }else if(userKey >= 65 && userKey <= 90){\n currentLetter = getChar(userKey)\n }\n\n\n // changes the keyboard\n e.preventDefault()\n\n}", "handleInteraction(letter) {\r\n const button = getButton(letter);\r\n button.disabled = true;\r\n const correct = this.activePhrase.checkLetter(letter);\r\n this.guessedLetters[letter]=true;\r\n if (correct) {\r\n button.classList.add(\"chosen\");\r\n this.activePhrase.showMatchedLetter(letter);\r\n if (this.checkForWin()) {\r\n this.gameOver(true);\r\n }\r\n mainContainer.style.background = \"#AAEEAA\"\r\n setTimeout(clearBackground,backgroundColorTime);\r\n } else {\r\n button.classList.add(\"wrong\");\r\n this.removeLife();\r\n mainContainer.style.background = \"#EEAAAA\"\r\n setTimeout(clearBackground,backgroundColorTime);\r\n }\r\n }", "handleInteraction(button) {\n //(1) Disables the selected letter's onscreen keyboard button\n button.setAttribute('disabled', true);\n\n //if the button clicked by the player does match a letter in the phrase\n if (this.activePhrase.checkLetter(button.innerText) === true) {\n //the CHOSEN CSS class is added to the selected letter's keyboard button\n button.className = 'chosen';\n //the 'showMatchedLetter()' method is called on the phrase\n this.activePhrase.showMatchedLetter(button.innerText);\n\n //if the button clicked by the player does not match a letter in the phrase\n } else {\n //the 'removeLie()' method is called\n this.removeLife();\n //the WRONG CSS class is added to the selected letter's keyboard button\n button.className = 'wrong';\n }\n //if all letters in the phrase are set to show - win\n if (this.checkForWin()) {\n //the 'gameOver()' method is called\n this.gameOver(true);\n }\n }", "handleInteraction(button) {\n\n const checkTrueOrFalse = this.activePhrase.checkLetter(button.textContent);\n console.log(checkTrueOrFalse);\n\n if (checkTrueOrFalse === false) {\n\n this.removeLife();\n button.disabled = true;\n button.className = 'wrong';\n\n }\n\n if (checkTrueOrFalse === true) {\n\n button.disabled = true;\n button.className = 'chosen'\n this.activePhrase.showMatchedLetter(button.textContent);\n this.checkForWin();\n this.gameOver();\n\n }\n\n this.resetGame();\n\n }", "showMatchedLetter(letter) {\r\n const reference = `.hide.letter.${letter}`;\r\n const correctLetters = document.querySelectorAll(reference);\r\n for (let each of correctLetters) {\r\n each.classList.remove('hide');\r\n each.classList.add('show');\r\n }\r\n}", "showMatchedLetter(letter){\n\n const phrases = document.querySelector('#phrase ul').children;\n\n\n\n for (let i = 0; i < phrases.length; i++) {\n if (phrases[i].textContent === letter) {\n phrases[i].setAttribute('class', `show letter ${letter}`);\n\n }\n }\n }", "function checkLetter (guess){\n\t\tconst letter = document.getElementsByClassName(\"letter\");\n\t\tlet foundMatch = null;\n\t\tfor (let i = 0; i < letter.length; i++) {\n\t\t\tif (guess === letter[i].textContent.toLowerCase()) {\n letter[i].classList.add('show');\n foundMatch = letter[i].textContent;\n } \n }\n return foundMatch\n }", "checkLetter(keyClicked) {\r\n if (this.phrase.includes(keyClicked)) {\r\n console.log('Yeah bitch');\r\n return true;\r\n } else {\r\n console.log('No Bitch');\r\n return false;\r\n }\r\n }", "function checkGuess(letter) {\n //if letter is not in guessedLetters array then push the letter to the array\n if (guessedLetters.indexOf(letter) === -1) {\n guessedLetters.push(letter);\n //if the letter isn't in the answer word then -1 the numGuessesRemaining\n if (ansWord.indexOf(letter) === -1) {\n numGuessesRemaining--;\n //if numGuessesRemaining is 3 or less then change the color\n if (numGuessesRemaining <=3) {\n document.getElementById(\"numGuesses\").style.color = \"#e12d2e\";\n }\n //if letter is in answer then replace the positioned \"_\" with the letter\n } else { \n for (var i = 0; i < ansWord.length; i++) {\n if (letter === ansWord[i]) {\n ansWordArr[i] = letter;\n } \n } \n }\n }\n\n}", "showMatchedLetter(letter) {\r\n const listItem = document.querySelectorAll('.letter');\r\n // Add 'show' class if passed letter mathces\r\n for (let li of listItem) {\r\n if (li.innerText === letter) {\r\n li.classList.remove('hide');\r\n li.classList.add('show');\r\n }\r\n }\r\n }", "handleInteraction(){\r\n const button = document.querySelectorAll('#qwerty button');\r\n button.forEach(but => {\r\n but.addEventListener(\"click\", (e)=>{\r\n if(this.activePhrase.includes(e.target.textContent)){\r\n e.target.className = \"chosen\";\r\n but.disabled = true;\r\n newPhrase.showMatchedLetter(e.target.textContent);\r\n this.checkForWin();\r\n } else {\r\n e.target.className = \"wrong\"; \r\n but.disabled = true;\r\n newGame.missed +=1;\r\n this.removeLife();\r\n }\r\n if (this.missed === 5){\r\n const phraseDisplay = document.querySelectorAll('#phrase ul li');\r\n button.forEach(butt => {\r\n butt.disabled = true;\r\n })\r\n phraseDisplay.forEach(letter => {\r\n if (letter.className === \"hide letter\"){\r\n letter.className = \"show_lost\";\r\n }\r\n });\r\n setTimeout(this.gameOver, 4000);\r\n }\r\n } );\r\n }) \r\n document.addEventListener(\"keyup\", (e)=>{\r\n button.forEach(but => {\r\n if(but.textContent.includes(e.key)){\r\n but.click();\r\n }\r\n })\r\n \r\n });\r\n }", "checkChar(inputChars) {\n let len = inputChars.length;\n if(this.chars.slice(0, len).join('') === inputChars.join('')) {\n for(let i = 0; i < len; i++) {\n this.children[i].classList.add('highlight');\n }\n this.isUpdated = true;\n } else if (this.isUpdated) {\n for(let i = 0; i < this.chars.length; i++) {\n this.children[i].classList.remove('highlight')\n }\n }\n }", "function checkLetter(letter) {\n $letterCount = 0;\n for (var x = 0; x < $randomWordArrayExtended.length; x++) {\n if ($randomWordArrayExtended[x] == letter) {\n $screenArray[x] = letter;\n $letterCount++;\n }\n }\n if ($letterCount == 0) {\n\n $attempts--;\n $previous_bg = \".state\" + $image_state;\n $image_state++;\n $current_bg = \".state\" + $image_state;\n $(\".state0\").hide(0);\n $(\"#\" + letter).css({\"pointer-events\": \"none\", \"background-color\": \"#800000\"});\n $($previous_bg).hide();\n $($current_bg).show();\n /* $(\"#\" + letter).addClass(\"used fail\").promise().done(function() {\n $($previous_bg).hide();\n $($current_bg).show();\n }); */\n\n } else {\n $(\"#\" + letter).css({\"pointer-events\": \"none\", \"background-color\": \"#195904\"});\n /* $(\"#\" + letter).addClass(\"used success\"); */\n }\n }", "showMatchedLetter(letter) {\n const letters = document.querySelectorAll(`.${letter}`);\n letters.forEach((buttons) => {\n buttons.classList.remove('hide');\n buttons.classList.add('show');\n });\n }", "showMatchedLetter(letter) {\n const displayedLetters = document.querySelectorAll('.letter')\n\n displayedLetters.forEach(item => {\n if (item.classList.contains('letter') && item.innerHTML === letter) {\n item.classList.add('show');\n item.classList.remove('hide');\n item.innerHTML = `${letter}`;\n }\n })\n }", "showMatchedLetter(letter) {\r\n const letters = Array.from(document.getElementsByClassName(letter));\r\n letters.forEach(match => {\r\n match.classList.remove('hide');\r\n match.classList.add('show');\r\n });\r\n }", "handleInteraction(button){\n //console.log(button);\n if(!this.activePhrase.checkLetter(button.textContent)) {\n button.disabled = true;\n button.className = 'wrong';\n this.removeLife();\n }\n if(this.activePhrase.checkLetter(button.textContent)) {\n button.disabled = true;\n button.className = 'chosen';\n this.activePhrase.showMatchedLetter(button.textContent);\n if(this.checkForWin()){\n this.gameOver(true);\n }\n }\n }", "showMatchedLetter(inputLetter) {\r\n const gameLetterElements = document.querySelectorAll('#phrase li');\r\n console.log(gameLetterElements)\r\n gameLetterElements.forEach(current => {\r\n console.log(`Current phrase letter: ${current.innerText}`);\r\n console.log(`keyed letter: ${inputLetter}`);\r\n if (current.innerText.toLowerCase() == inputLetter) {\r\n current.classList.remove(\"hide\");\r\n current.classList.add(\"show\");\r\n }\r\n })\r\n }", "function bindClick(i) {\n return function () {\n\n /*generate a new array with the string splitted*/\n var final = document.querySelectorAll(\".letter\");\n var rei= [];\n for (var a=0; a<final.length; a++){\n rei.push(final[a].textContent);\n }\n /*check if the selected button's text is included in the phrase */\n for (var b=0; b<final.length; b++){\n if (rei[b] === button[i].textContent){\n final[b].classList.add(\"show\");\n correct++;\n button[i].style.backgroundColor=\"var(--color-neutral)\";\n } \n \n }\n\n /*add the class \"chosen\" and disable the clicked keys */\n console.log(button[i].textContent);\n button[i].classList.add(\"chosen\");\n button[i].setAttribute(\"disabled\", true);\n \n \n\n\n /*if the button clicked is not included in the phrase change the hearths src, \n increase the wrong variable and apply some animations*/\n if (!rei.includes(button[i].textContent)){\n img[wrong].src=\"images/lostHeart.png\";\n wrong++;\n }\n\n /*if the phrase splitted array has same length as the elements with class \"show\" \n the user won. apply the win overlay*/\n if(rei.length === document.getElementsByClassName(\"show\").length){\n console.log(\"you won :)\");\n var overlay=document.getElementById(\"overlay\")\n overlay.style.transform=\"translateX(0)\";\n overlay.classList.add(\"win\");\n document.querySelector(\".title\").innerHTML=\"you won!\";\n document.querySelector(\".header\").style.transform=\"scale(0.9)\";\n document.querySelector(\"ul\").classList.remove(\"phrase\");\n }\n /*if the wrong counter>5 the user lost so we apply the lost overlay */\n if (wrong >= 5) {\n console.log(\"you lost :(\");\n var overlay=document.getElementById(\"overlay\")\n overlay.style.transform=\"translateX(0)\";\n overlay.classList.add(\"lose\");\n document.querySelector(\".title\").innerHTML=\"you lost!\";\n document.querySelector(\".header\").style.transform=\"scale(0.9)\";\n document.querySelector(\"ul\").classList.remove(\"phrase\");\n\n }\n };\n}", "showMatchedLetter(letter) {\n let li = document.querySelectorAll('li')\n for (let i = 0; i < li.length; i++) {\n if (li[i].className === `hide letter ${letter}`) {\n li[i].className = `show letter ${letter}`;\n } else {\n }\n }\n }" ]
[ "0.78025806", "0.77837574", "0.7417684", "0.71316534", "0.7118393", "0.7112934", "0.7112548", "0.7035374", "0.70206225", "0.7018149", "0.69472027", "0.6926001", "0.69098306", "0.688545", "0.68395984", "0.6836015", "0.68318504", "0.681902", "0.6814238", "0.6789591", "0.67643577", "0.6763322", "0.67551863", "0.6752725", "0.67442787", "0.67348415", "0.6720626", "0.66825145", "0.66743726", "0.6671868", "0.66698307", "0.6654707", "0.6649515", "0.66358066", "0.6634824", "0.6632017", "0.6624041", "0.6605742", "0.65863776", "0.6569863", "0.65385646", "0.6537962", "0.6535067", "0.65267944", "0.6517016", "0.65133154", "0.6502251", "0.650008", "0.6491292", "0.6489549", "0.6484742", "0.6483497", "0.6479648", "0.6476124", "0.6470821", "0.64549285", "0.6453329", "0.6445549", "0.64403546", "0.6434996", "0.6420412", "0.6412359", "0.6411825", "0.64015555", "0.6400658", "0.63891447", "0.63830835", "0.63748693", "0.63634413", "0.6359201", "0.63551444", "0.63473815", "0.6340598", "0.6339926", "0.63289547", "0.63255477", "0.63248795", "0.63140696", "0.630972", "0.6305038", "0.6303934", "0.6300049", "0.6300037", "0.6299213", "0.6292525", "0.6281406", "0.6277928", "0.6275208", "0.62611204", "0.6261012", "0.6254914", "0.6251356", "0.6247685", "0.62453747", "0.6239859", "0.6239838", "0.62389666", "0.62363195", "0.62313735", "0.6230814" ]
0.7060315
7
TODO remove password field from serialiser or make read only
componentDidMount() { const context = this.context; fetch("http://localhost:8000/api/profile", { method: "GET", headers: { Authorization: `JWT ${localStorage.getItem("token")}` } }) .then(res => auth.checkLoginstatus(res)) .then(res => res.json()) .then(data => { this.setState({ user: data, loading: false }); context.updateValue("user", this.state.user); localStorage.setItem("user", JSON.stringify(data)); // localStorage.setItem("user", this.state.user); // console.log('user',context) }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "toJSON() {\n let userData = this.get() //.get built into get hte user we are working with\n delete userData.password //this removes the password so when we are passing around user info that the pw isnt a parto f that user object that gets passed between the backend and frontend..but does not remove it from the database\n return userData\n }", "toJSON() {\n let userData = this.get();\n // delete - deletes the key we give it\n delete userData.password;\n return userData;\n }", "get password() {\n return this._password;\n }", "get password (){\n return this.#password\n }", "static fromPassword(password) {\n return { generatePassword: false, password };\n }", "static initialize(obj, password) { \n obj['password'] = password;\n }", "get info() {\n const data = { ...this.dataValues };\n delete data.password;\n return data;\n }", "static get hidden() {\n return ['password'];\n }", "static fromPassword(username, password) {\n return {\n username,\n password,\n usernameAsString: true,\n };\n }", "function createPasswordDataObject() {\n\t\treturn {\n\t\t\toldPassword: $(\"#txtOldPassword\").val(),\n\t\t\tnewPassword: $(\"#txtNewPassword\").val(),\n\t\t\tnewPasswordConfirm: $(\"#txtNewPasswordConfirm\").val(),\n\t\t\tdeleteFlag: DELETE_FLAG_OFF\n\t\t};\n\t}", "static outbound (attributes) {\n delete attributes.password\n return attributes\n }", "static get properties() {\n return {\n ...super.properties,\n username: { type: String },\n password: { type: String },\n errorMSG: { type: String },\n hidePassword: { type: Boolean },\n hasPass: { type: Boolean },\n };\n }", "function writePassword() {}", "get password() {\n return this.form.controls.password;\n }", "function getPassword() {\n var data = getRecord()\n blob = bin2String(Utilities.base64Decode(data[COL_PASSWORD]));\n return blob;\n}", "serialize() {\n var data = super.serialize();\n\n data.username = this.user.username;\n\n return data;\n }", "constructor(props) {\n super(props);\n\n this.state = {\n icEye: 'visibility-off', // default icon to show that password is currently hidden\n password: '', // actual value of password entered by the user\n showPassword: true, // boolean to show/hide the password\n\n password: '',\n userData: {},\n };\n }", "setToken(password){\n this.token = new Buffer(`${this.user}:${password}`).toString('base64')\n return this.token\n }", "function needsPassword() {\n // no password is set neither in the user table nor in the staged record.\n // the user must pick a password\n res.json({\n success: true,\n email: email,\n needs_password: true\n });\n }", "exportPasswordRegistrations() {}", "function readProtect(obj, tag, ba) {\n\tobj.isProtected = true;\n\tif (tag.contentLength > 0) obj.password = ba.readString(tag.contentLength, true);\n}", "static fromPassword(password) {\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_SecretValue(password);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, this.fromPassword);\n }\n throw error;\n }\n return { generatePassword: false, password };\n }", "function passwordJsonReader() {\n var data = fs.readFileSync(\"./passwd.txt\", 'utf-8');\n var dataJson = '{' + '\\n' + ' ' + data + '\\n' + '}';\n var dataJsonString = JSON.parse(dataJson);\n return dataJsonString;\n}", "static fromPassword(username, password) {\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_SecretValue(password);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, this.fromPassword);\n }\n throw error;\n }\n return {\n username,\n password,\n usernameAsString: true,\n };\n }", "get() {\n return () => this.getDataValue('password');\n }", "validatePassword () {\n\t\tif (!this.attributes.password) { return; }\n\t\tlet error = this.userValidator.validatePassword(this.attributes.password);\n\t\tif (error) {\n\t\t\treturn { password: error };\n\t\t}\n\t}", "function setPassword(password) {\n\t\tthis.password = password;\n\t}", "get() {\n return () => this.getDataValue('password')\n }", "get() {\n return () => this.getDataValue('password')\n }", "function stringifyWithoutPassword(message)\n{\n var newMessage = {};\n \n for(var i in message)\n {\n if(i == \"password\" && message[i] != null)\n newMessage[\"password\"] = \"xxx\";\n else\n newMessage[i]=message[i];\n }\n \n return JSON.stringify(newMessage);\n}", "get() {\n return () => this.getDataValue('password');\n }", "get() {\n return () => this.getDataValue('password');\n }", "static get _required_user_attributes() { return ['email' , 'password']; }", "static get jsonSchema() {\n return {\n type: 'object',\n required: ['username', 'pwHash'],\n properties: {\n username: {type: 'string'},\n firstName: {type: 'string'},\n lastName: {type: 'string'},\n email: {type: 'string'},\n isLocalResident: {type: 'string'},\n isVerified: {type: 'boolean'},\n isEmailVerified: {type: 'boolean'},\n pwHash:{ type: 'string'},\n pwSalt: {type: 'string'},\n pwAlgorithm: {type: 'string'},\n isAdmin: {type: 'boolean'},\n dateRegistered: {type: 'number', minimum: 0, maximum: UNIX_EPOCH_MAX},\n lastLogin: {type: 'number', minimum: 0, maximum: UNIX_EPOCH_MAX},\n }\n };\n }", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "serialize() {}", "function PasswordValidator() {\n // Initialize a schema with no properties defined\n this.properties = [];\n}", "function PasswordAdapter(db) {\n this._db = db;\n}", "isValidPassword (password) {\n // don't use plaintext passwords in production\n return password === this.password;\n }", "constructor(){\n //super(BeanState.getPackageContract() + \".BeanUser\");\n super();\n \n this.setType(undefined);\n\n this.setVersion(undefined);\n\n this.setUserId(UserId.newUserId());\n\n this.setKeys(KeyPair.newKeyPair());\n\n this.setPassphrase(undefined);\n \n this.setPublicId(undefined);\n\n this.setPassword(undefined);\n\n this.setInitVector(undefined);\n\n this.setSignatureOfUserInfos(undefined);\n }", "function writePassword() {\n var passwordReqs = {};\n passwordReqs = passReqs(passwordReqs);\n var password = generatePassword(passwordReqs);\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password;\n}", "constructor(props) {\n super(props);\n Object.assign(this.state, {mode:null, editable:true, fields:{username:null, password:null, password2:null, email:null}});\n }", "function getPasswordAttributeName(){\r\n\treturn 'userPassword';\r\n}", "function User(jsonUser) {\n this.username = jsonUser.username;\n this.password = jsonUser.password;\n this.confirmPassword = jsonUser.confirmPassword;\n this.id = jsonUser.id;\n\n this.passwordsMatch = function () {\n return (this.password === this.confirmPassword);\n }\n\n this.toJSON = function () {\n return {\n \"username\": this.username,\n \"password\": this.password\n };\n }\n}", "static inbound (attributes) {\n let {\n password,\n salt = newSalt(),\n algorithm = DEFAULT_PASSWORD_ALGORITHM\n } = attributes\n if (password) {\n let passwordHash = digest(password, salt, algorithm)\n delete attributes.password\n Object.assign(attributes, { salt, passwordHash, algorithm })\n }\n return attributes\n }", "async create(attrs){\n\n attrs.id = this.randomId();\n\n // salt + hashing password\n const salt = crypto.randomBytes(8).toString('hex');\n const buf = await scrypt(attrs.password, salt, 64);\n\n\n const records = await this.getAll();\n const record = {\n ...attrs,\n password:`${buf.toString('hex')}.${salt}`\n }\n records.push(record);\n\n await this.writeAll(records);\n\n return record;\n\n }", "function getPassword() {\n\tIPCRenderer.sendToHost('config', {key: 'walletPassword'}, 'use-password');\n}", "constructor(props) {\n super(props);\n Object.assign(this.state, {editable:true, fields:{username:null, password:null}});\n }", "password(password) {\n\n\n if (password === \"\") {\n obj.error = \"field should not be empty\",\n obj.boolval = true\n }\n else if (password.length < 8) {\n obj.error = \"password length should be minimum 8 characters\",\n obj.boolval = true\n }\n else{\n obj.error = \"\",\n obj.boolval = false\n }\n\n return obj\n }", "constructor(userId, password) {\n if (undefined != data.id) {\n this.id = data.id;\n }\n else {\n this.id = parseInt(Math.floor(Math.random() * Math.floor(100000)));\n }\n\n this.userId = userId;\n this.password = password;\n\n }", "toJSON() {\n return {\n isLoggedIn: this.isLoggedIn,\n isGuest: this.isGuest,\n viaRemember: this.viaRemember,\n authenticationAttempted: this.authenticationAttempted,\n isAuthenticated: this.isAuthenticated,\n user: this.user,\n };\n }", "mapPropsToValues(/*Se pueden Utilizar los props de la linea 19*/) {\n return {\n email: \"\",\n password: \"\",\n };\n }", "toJSON() {\n return {\n id: this.toB58String(),\n privKey: toB64Opt(this.marshalPrivKey()),\n pubKey: toB64Opt(this.marshalPubKey())\n };\n }", "function writePassword() {\n var password = generatePassword();\n}", "function writePassword() {\n let newOptions = { ...options };\n setOptions(newOptions);\n var password = generatePassword(newOptions);\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password;\n}", "function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n }", "constructor(id, name, surname, email, password){\n this.id = id;this.name = name; this.surname = surname; \n this.email = email; this.password = password;\n }", "mapPropsToValues({ name, password }) {\n return {\n name: name || \"\",\n password: password || \"\",\n };\n }", "function writePassword() {\n \n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n \n passwordText.value = password;\n \n }", "constructor(props) {\n super(props);\n this.state = {\n email: \"\",\n password: \"\",\n errors: {},\n secureTextEntry: true\n };\n }", "constructor(props) {\n super(props);\n\n this.state = {\n value: \"\",\n lock: \"locked\"\n };\n\n this.submitPassword = this.submitPassword.bind(this);\n this.handleChange = this.handleChange.bind(this);\n this.showContents = this.showContents.bind(this);\n this.showPassword = this.showPassword.bind(this);\n }", "function writePassword() {\n var password = getPasswordOptions();\n var passwordText = document.querySelector('#password');\n \n passwordText.value = password;\n }" ]
[ "0.6969645", "0.6958941", "0.6932058", "0.6832797", "0.6495088", "0.64840424", "0.6396698", "0.6340693", "0.63017774", "0.6293822", "0.6247987", "0.62286043", "0.6185693", "0.61272347", "0.612679", "0.610655", "0.6045102", "0.60082656", "0.5996749", "0.5970258", "0.59666544", "0.59641933", "0.5941355", "0.5903749", "0.5894511", "0.58647394", "0.58463806", "0.58433723", "0.58433723", "0.58389497", "0.58332974", "0.58332974", "0.5828601", "0.57877076", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5768236", "0.5767431", "0.57518333", "0.573147", "0.5730053", "0.56919366", "0.56844693", "0.56715703", "0.5663545", "0.56190646", "0.5616728", "0.5607319", "0.55914915", "0.5584679", "0.55841553", "0.55754364", "0.5572421", "0.5565213", "0.5564365", "0.55641246", "0.5543164", "0.55236614", "0.5523303", "0.55209", "0.551677", "0.55130553", "0.5506282" ]
0.0
-1
static ballCount = 0;
constructor (position, speed, radius, color) { this.position = position; this.speed = speed; this.radius = radius; this.color = color; this.imgX = this.position.x - this.radius; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "initBallList()\r\n\t{\r\n\t\tlet iterations = 0;\r\n\t\twhile (iterations < this.MAX_BALLS) {\r\n\t\t \tlet digit = Math.floor(Math.random() * this.MAX_BALLS) + 1;\r\n\r\n\t\t\tif (this.drawnBalls.indexOf(digit) < 0) {\r\n\t\t\t\tthis.drawnBalls.push(\r\n\t\t\t\t\tnew Ball(\r\n\t\t\t\t\t\twindow.innerWidth / 2 - 120, \r\n\t\t\t\t\t\twindow.innerHeight / 4,\r\n\t\t\t\t\t\t0,\r\n\t\t\t\t\t\t0,\r\n\t\t\t\t\t\t120,\r\n\t\t\t\t\t\tdigit,\r\n\t\t\t\t\t\t255\r\n\t\t\t\t\t)\r\n\t\t\t\t);\r\n\t\t\t\titerations++;\r\n\t\t\t}\r\n\t\t}\r\n\t}", "function ballReset() {\n ballX = canvas.width / 2;\n ballY = canvas.height / 2;\n speedBallY = 3;\n}", "function ballReset() {\n winCheck();\n ballSpeedX = 5;\n ballSpeedY = 0;\n ballX = canvas.width/2;\n ballY = canvas.height/2;\n}", "function update(){\r\n var i;\r\n clearCanvas();\r\n for(i=0;i<count;i++){\r\n ball[i].update();\r\n }\r\n}", "function init(){\n\tballs = []\n\tparticles = []\n\tuselessBalls = []\n\tgenerateBall = true\n\ttimeInterval = 2000\n\ttimer = 0\n\tvelocityOfBall = 2.5\n\tscore = 0\n\tfillColor = '#fff'\n\n\tblueBall = new Ball(\n\t\tcanvas, ctx,\n\t\tcanvasWidth/2, canvasHeight/2 - separation,\n\t\tglobalRadius, colors[1], particles, 0, 0, true\n\t)\n\tredBall = new Ball(\n\t\tcanvas, ctx,\n\t\tcanvasWidth/2, canvasHeight/2 + separation,\n\t\tglobalRadius, colors[0], particles, 0, 0, true\n\t)\n\tballs.push(redBall, blueBall)\n\n\trandPoints = [\n\t\t{\n\t\t\tx: canvas.width / 2,\n\t\t\ty: -50\n\t\t},\n\t\t{\n\t\t\tx: canvas.width / 2,\n\t\t\ty: canvas.height + 50\n\t\t}\n\t]\n}", "function addBall(){\r\n if(count<100){\r\n var rndColor=Math.floor((Math.random() * 16) + 1); //velger tilfeldig farge\r\n var rndX=Math.floor((Math.random() * 5) + 1); //Bestemmer fart x-retning\r\n var rndY=Math.floor((Math.random() * 5) + 1); //Bestemmer fart y-retning\r\n ball[count]= new Ball(Math.floor((Math.random() * 490) + 1),\r\n Math.floor((Math.random() * 490)+1),Math.floor((Math.random() * 10) + 5),color[rndColor],rndX,rndY);\r\n count++;\r\n\r\n //utdata til meteor-teller\r\n document.getElementById(\"ballCount\").innerHTML = \"Meteors: \" + count;\r\n }\r\n}", "function ball1f() {\r\n\tbsel = 0;\r\n\tallballcustoms();\r\n}", "function ballReset() {\n ballSpeedX = -ballSpeedX;\n ballX = canvas.width / 2;\n ballY = canvas.height / 2;\n}", "function resetBall() {\n ball.x = cvs.width / 2;\n ball.y = paddle.y - BALL_RADIUS;\n ball.dx = 3 * (Math.random() * 2 - 1);\n ball.dy = -3;\n}", "checkBall() {\n this.ballPosition++;\n\n var disc = this.discs[ this.ballPosition ];\n\n if (disc && !disc.isSlotLinedUp()) {\n // ball bounces away\n this.ballPosition = -1;\n this.ballDropping = false;\n }\n }", "function gameReset(){\r\n ballArray = [];\r\n}", "function ballStart() \n {\n ball.xPos = 400;\n ball.yPos = 230;\n ball.speedY = 5 + 5 * Math.random();\n ball.speedX = 5 + 5 * Math.random();\n\n changedirection = true * Math.random;\n }", "function resetBall() {\n\tballX = startBallX;\n\tballY = startBallY;\n\tballSpeedX = 0;\n\tballSpeedY = 0;\n}", "function init()\t\t\t\t\t\t\t\t\t\t\t\t\r\n{\r\n\trandom_position();\r\n\tinit_ball();\r\n\ttimeleft=10;\r\n\tgoal_counter=0;\r\n\t\r\n}", "function ballReset(){\n if(player1Score >= WINNING_SCORE || player2Score >= WINNING_SCORE) {\n showingWinScreen = true;\n }\n\n ballX = canvas.width/2;\n ballY = canvas.height/2\n ballSpeedX = -ballSpeedX\n}", "function ballReset() {\n if (player1Score >= WINNING_SCORE ||\n player2Score >= WINNING_SCORE) {\n showingWinScreen = true;\n }\n\n ballSpeedX = -ballSpeedX;\n ballX = canvas.width / 2;\n ballY = canvas.height / 2;\n }", "function increaseBallSpeed()\n{\n\tballSpeed = ballSpeed + (2 / numBlocks);\n}", "_serveBall() {\r\n\r\n }", "function spawnBall(){\r\n if(gameState===\"play\") {\r\nif(frameCount %40===0){\r\n ball=createSprite(300,-10,101,19)\r\n ball.x = Math.round(random(0,1000));\r\n ball.addImage(ballImage);\r\n ball.scale = 0.2;\r\n ball.velocityY = +5;\r\n ballGroup.add(ball)\r\n ball.lifetime=200\r\n}\r\n\r\n}\r\n\r\n}", "function resetBall() {\r\n ball.x = canvas.width / 2;\r\n ball.y = canvas.height / 2;\r\n ball.velocityX = -ball.velocityX;\r\n ball.speed = 7;\r\n}", "function Start() {\n\t\n\tstartingPos = ball.position;\n}", "function draw(){\n if(game){\n updateScreen(); //Line 181\n //Updates score for survival by adding one as long as there's at least one ping pong ball in play\n if(type == \"survival\" && balls.length>0) score++;\n \n //Checks to see that the system clock aligns with either of the magic numbers\n //After a ball has been spawned, sets var another to true to prevent extra spawns\n if(second()%freq == magicSec && !another){ \n addBall(); //Line 274\n another = true;\n }if(second()%freq == magicSec+1) another = false;\n }\n}", "function ballReset() {\n if (playerOneScore >= winningScore || playerTwoScore >= winningScore) {\n showWinScreen = true;\n }\n //ball fires from the middle of the screen towards the winner of the last point\n ballX = canvas.width / 2;\n ballY = canvas.height / 2;\n ballSpeedX = -ballSpeedX;\n}", "function start_ball(){\n clearInterval(ball_interval);\n ball_interval=window.setInterval(move_ball,16);\n}", "function resetBall() {\n ball.x = canvas.width / 2\n ball.y = canvas.height - 50\n ball.dx = 1\n ball.dy = 1\n ball.speed = 1\n}", "function resetBall(){\n ball.x = canvas.width/2;\n ball.y = canvas.height/2;\n ball.vx = -ball.vx;\n ball.speed = 5;\n}", "function loop() {\n ctx.fillStyle = Screen;\n ctx.fillRect(0,0,width,height);\n\n CountNormal=0;\n CountSick=0;\n CountCured=0;\n CountDead=0;\n\n for(let i = 0; i < balls.length; i++) {\n balls[i].draw();\n // pour afficher les num de balle\n ctx.beginPath();\n // ctx.fillText(\"\", balls[i].x+10, balls[i].y);\n ctx.fill();\n\n balls[i].updatecolor();\n balls[i].update();\n balls[i].collisionDetect(i);\n\n if(balls[i].color==Normal) {\n CountNormal=CountNormal+1;\n }\n else if (balls[i].color==Sick){\n CountSick=CountSick+1;\n }\n else if (balls[i].color==Cured){\n CountCured=CountCured+1;\n }\n else if (balls[i].color==Dead){\n CountDead=CountDead+1;\n }\n\n }\n //Rnow = new date();\n Rnow = new Date();\n RnowT = Rnow.getTime();\n\n\n ctx.fillStyle = Dead;\n ctx.fillText(''.concat(\"Temps : \",Math.trunc((RnowT - BegTime)/1000)) , 10, 10);\n\n ctx.fillStyle=Normal;\n ctx.fillText(\"Sains : \" , 10, 30);\n ctx.fillText(CountNormal , 50, 30);\n ctx.fillStyle=Sick;\n ctx.fillText(\"Malades : \" , 10, 40);\n ctx.fillText(CountSick , 50, 40);\n ctx.fillStyle=Cured;\n ctx.fillText(\"Guéris : \" , 10, 50);\n ctx.fillText(CountCured , 50, 50);\n ctx.fillStyle=Dead;\n ctx.fillText(\"Décès : \" , 10, 60);\n ctx.fillText(CountDead , 50, 60);\n\n Scenario = document.getElementById('Scénario').value;\n if(Scenario!=OldScenario)\n {\n for(let i = 0; i < NumberBall; i++) {\n balls[i].reinit();\n }\n now = new Date();\n BegTime = now.getTime();\n\n }\n\n OldScenario = Scenario\n //ctx.fillText(Math.trunc(width * height/320000), 30, 20);\n\n //ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);\n ctx.fill();\n\n requestAnimationFrame(loop);\n}", "function resetBall(){\n ball.x = canvas.width/2;\n ball.y = canvas.height/2;\n ball.velocityX = -ball.velocityX;\n ball.speed = 7;\n}", "function resetBall(){\n ball.x = canvas.width/2;\n ball.y = canvas.height/2;\n ball.velocityX = -ball.velocityX;\n ball.speed = 7;\n}", "function ballMove() {\n ballX += speedBallX;\n ballY += speedBallY;\n\n if (ballX + ballRadius > canvas.width && speedBallX > 0) {\n speedBallX *= -1\n }\n if (ballX - ballRadius < 0 && speedBallX < 0) {\n speedBallX *= -1\n }\n if (ballY + ballRadius > canvas.height) {\n ballReset();\n brickReset();\n score = 0;\n }\n if (ballY - ballRadius < 0 && speedBallY < 0) {\n speedBallY *= -1\n }\n}", "function addBall(){\r\n let thisBall = {\r\n x: random(25, width - 25),\r\n y: random(25, height - 25),\r\n dx: random(1, 10),\r\n dy: 0,\r\n radius: 25,\r\n color: color(random(255), random(255), random(255)),\r\n };\r\n if(thisBall.x > mouseX){\r\n thisBall.dx = thisBall.dx * (-1);\r\n }\r\n thisBall.dy = (mouseY - thisBall.y)/(mouseX - thisBall.x)*thisBall.dx + GRAVITATIONAL_CONSTANT * (mouseX - thisBall.x)/thisBall.dx/2;\r\n ballArray.push(thisBall);\r\n if(gameRunning){\r\n score += 1;\r\n }\r\n}", "function bounce() {\n ball.body.velocity.x = 400;\n if (ball.body.velocity.y > 0) {\n ball.body.velocity.y = Math.random() * 750\n }\n else {\n ball.body.velocity.y = -Math.random() * 750\n }\n ball.body.velocity.x = ball.body.velocity.x + 10\n this.counter++;\n }", "function startGame() {\n luminousScore = 0;\n}", "function resetBalls() {\r\n positionArray = [];\r\n velocityArray = [];\r\n radiusArray = [];\r\n colorArray = [];\r\n}", "function init() {\n // Clear the scoreboard:\n score.innerText='Score: 0.0%';\n currentScore=0;\n\n // Reset the visual field:\n meme.style.display='none';\n theball.style.display='inline';\n toggleTrack();\n paddle.style.width=paddleWidthPercent.toString()+'%';\n document.body.style.cursor='none';\n var ball=actualball.getBoundingClientRect();\n ballpath.style.top=(ball.width/2).toString()+'px';\n\n lastKnownX=null;\n lastKnownY=null;\n pixelsMovedX=ball.width/2;\n pixelsMovedY=ball.height/2;\n\n // The number of horizontal icons is determined by the size and scale of\n // the icons, in relation to the width of the screen.\n bricksPerRow=Math.floor(window.innerWidth*0.35*iconScaling/iconSizeX);\n\n // Set the gameplay variables:\n ballDirection=-65;\n ballSpeed=1;\n temporaryImmunity=false;\n\n // Populate the icons:\n buildAnArmada(30);\n\n // Start moving the icon field:\n startTheArmada();\n\n // Start moving the ball:\n startBall(100*event.clientX/window.innerWidth, 100*(paddle.getBoundingClientRect().y-ball.height*1.5)/window.innerHeight, ballDirection, ballSpeed);\n\n // Reset and restart the interval timer that will check for collisions every 100 ms.\n if (theInterval) clearInterval(theInterval);\n theInterval = setInterval(didItCollide, intervalMilliseconds);\n\n // If you click anywhere now, the game stops.\n document.body.onclick=holdit;\n }", "function totalLoser(ball) {\n return ball >= canvasY;\n }", "checkBallCollision() {\n // Top Wall Check\n if (this.ball.Y - this.ball.R === 1) {\n this.ball.dy = 2;\n }\n // Bottom Wall Check\n if (this.ball.Y - this.ball.R === 641) {\n this.ball.dy = -2;\n /* If the ball hits the bottom wall then the user loses hence\n we reset the score and bricks */\n this.score = 0;\n this.initBricks();\n this.drawBricks();\n }\n // Right Wall Check\n if (this.ball.X - this.ball.R === 1092) {\n this.ball.dx = -2;\n }\n // Left Wall Check\n if (this.ball.X - this.ball.R === 2) {\n this.ball.dx = 2;\n }\n // Ball and Paddle collision check\n if (this.ball.Y === 631) {\n // If the ball is in the area of the paddle\n if (\n this.ball.X > this.paddle.X &&\n this.ball.X < this.paddle.X + this.paddle.W\n ) {\n this.ball.dy = -2;\n }\n }\n }", "function update(){\n frameCounter += 1;\n context.clearRect(0,0, canvas.width, canvas.height); //Erases Pixels in our Canvas\n drawScore();\n ball.draw(); //Re-draw the ball\n drawObstacles();\n\n isGameOver();\n\n\n if(isPressed.right){\n ball.x += ball.vx; //update x-coordinate\n }\n else if(isPressed.left){\n ball.x -= ball.vx; //update x-coordinate\n }\n if(isPressed.up){\n ball.y -= ball.vy; //update y-coordinate\n }\n else if(isPressed.down){\n ball.y += ball.vy; //update y-coordinate\n }\n\n}", "function bouncingBall(h,bounce,window) {\n var count = -1;\n if (bounce > 0 && bounce < 1) while (h > window) count+=2, h *= bounce;\n return count;\n}", "function timerTick() {\n \n console.log(ball.xpos+\",\"+ball.ypos); // debug\n\n // move the ball\n \n var currx = ball.xpos;\n var curry = ball.ypos;\n var padx = paddle.xpos;\n var pady = paddle.ypos;\n var lpadx = lpaddle.xpos;\n var lpady = lpaddle.ypos;\n\n // bounces off paddle and changes color of paddle and itself\n if ((currx <= padx) && (currx + ball.xspeed > padx) && (curry > pady - ball.size/2) && (curry < pady+paddle.height-ball.size/2)) {\n ball.xspeed *=- 1;\n paddle.setColor(getRandomColor());\n ball.setColor(getRandomColor());\n field.setColor(getRandomColor());\n score++;\n document.getElementById('scorebox').innerHTML = \"SCORE: \" + score;\n if (score > hiscore) {\n hiscore = score;\n document.getElementById('hiscorebox').innerHTML = \"BEST: \" + hiscore;\n }\n }\n \n if ((currx >= lpadx) && (currx + ball.xspeed < lpadx) && (curry > lpady - ball.size/2) && curry < lpady + paddle.height-ball.size/2)) {\n ball.xspeed *=- 1;\n lpaddle.setColor(getRandomColor());\n ball.setColor(getRandomColor());\n field.setColor(getRandomColor());\n score++;\n document.getElementById('scorebox').innerHTML = \"SCORE: \" + score;\n if (score > hiscore) {\n hiscore = score;\n document.getElementById('hiscorebox').innerHTML = \"BEST: \" + hiscore;\n }\n }\n\n // bounces off walls\n if (currx < 0 ) {\n gameOver();\n } \n if (currx > field.width - ball.size){\n gameOver();\n }\n if (curry < 0 ) {\n curry = 0; // bounce off top wall\n ball.yspeed *= -1;\n } \n if (curry > (field.height - ball.size)) {\n curry = field.height - ball.size; // bounce off bottom wall\n ball.yspeed *= -1;\n } \n\n currx += ball.xspeed;\n curry += ball.yspeed;\n \n ball.setPosition(currx, curry); \n \n\n // move the paddle\n if (pady < 0) {\n pady = 0;\n keyState = 0;\n }\n if (pady > (field.height - paddle.height)) {\n pady = field.height - paddle.height;\n keyState = 0;\n } \n pady += (paddle.speed * keyState);\n paddle.setPosition(padx, pady);\n\n if (lpady < 0) {\n lpady = 0;\n lkeyState = 0;\n }\n if (lpady > (field.height - paddle.height)) {\n lpady = field.height - paddle.height;\n lkeyState = 0;\n } \n lpady += (paddle.speed * lkeyState);\n lpaddle.setPosition(lpadx, lpady);\n\n\n // update timer\n if (count == 50) {\n time++;\n count = 0;\n var timer = document.getElementById('timer');\n if (time%60 < 10) {\n timer.innerHTML = Math.floor(time/60) + \":0\" + time%60;\n } else {\n timer.innerHTML = Math.floor(time/60) + \":\" + time%60;\n }\n }\n else {\n count ++;\n } \n}", "function tick(state) {\n \n let ball = state.canvas.selectAll('circle.ball').data(state.forceSim.nodes());\n\n\tball.exit().remove();\n\n\tball.merge(\n\t\tball.enter().append('circle')\n\t\t\t.classed('ball', true)\n\t\t\t.style('fill', function(d,idx) {\n if (idx == 0) {\n return INFECTED;\n } else {\n return HEALTHY;\n }\n })\n\t)\n\t\t.attr('r', d => d.r || BALL_RADIUS)\n\t\t.attr('cx', d => d.x)\n\t\t.attr('cy', d => d.y)\n .attr('id', (d, idx) => \"ball\"+idx.toString());\n \n\n // Generate live counter\n d3.select(\"span.healthy-count\").text(HEALTHY_COUNT.toString());\n d3.select(\"span.infected-count\").text(INFECTED_COUNT.toString());\n d3.select(\"span.recovered-count\").text(RECOVERED_COUNT.toString());\n d3.select(\"span.time-count\").text(time.toString());\n\n plusTime();\n tick_count++;\n}", "function resetBall() {\n\t//Win conditions\n\tif (player1Score >= WINNING_SCORE || player2Score >= WINNING_SCORE){\n\t\twinScreen = true;\n\t}\n\n\tballSpeedX = -ballSpeedX;\n\t//Gives horizontal center\n\tballX = canvas.width/2;\n\t//Gives vertical center\n\tballY = canvas.height/2;\n}", "function setBallVel() {\r\n audio.play();\r\n if (click === 0) {\r\n ball.vy = Math.min(canvas.height * 0.015, 9);\r\n click++;\r\n }\r\n else\r\n ball.vy = Math.min(canvas.height * 0.01, 4.25);\r\n}", "function updateBallPosition() {\n ball.x += ball.speedX;\n ball.y += ball.speedY;\n }", "static get BoneCount() {}", "function ballWallCollision(){\r\n if(ball.x+ball.radius>cvs.width || ball.x-ball.radius<0)\r\n {\r\n ball.dx =- ball.dx;\r\n WALL_HIT.play();\r\n }\r\n if(ball.y-ball.radius<0){\r\n WALL_HIT.play();\r\n ball.dy =- ball.dy;\r\n }\r\n if(ball.y +ball.radius >cvs.height){\r\n LIFE--; // Lose Life\r\n LIFE_LOST.play();\r\n resetBall();\r\n }\r\n}", "function setupBalls() {\n status_left = \"init\";\n status_right = \"init\";\n v_left = 0.0;\n v_right = 0.0;\n s_left = 0.0;\n s_right = 0.0;\n s0 = r_ball * sin(rightPhi0 / 2);\n redBall_x = redBall_x0;\n redBall_y = redBall_y0;\n x0R = x0_right;\n y0R = y0_right;\n x0L = x0_left;\n y0L = y0_left;\n}", "function ballWallCollision(){\r\n if(ball.x + ball.radius > cvs.width || ball.x - ball.radius < 0){\r\n ball.dx = - ball.dx;\r\n }\r\n \r\n if(ball.y - ball.radius < 0){\r\n ball.dy = -ball.dy;\r\n }\r\n \r\n if(ball.y + ball.radius > cvs.height){\r\n LIFE--; // LOSE LIFE\r\n resetBall();\r\n }\r\n}", "function ballWallCollision() {\n\n if (ball.x + ball.radius > canvas.width ||\n ball.x - ball.radius < 0) {\n\n WALL_HIT.play();\n ball.dx = -ball.dx;\n }\n\n if (ball.y - ball.radius < 0) {\n WALL_HIT.play();\n ball.dy = -ball.dy;\n }\n\n if (ball.y + ball.radius > canvas.height) {\n\n LIFE_LOST.play();\n LIFE--;\n resetBall();\n }\n}", "function bounceball()\n{\n /* Initialization */\n rightBorder = 1050;\n bottomBorder = 484;\n currentX = currentX + offsetX;\n currentY = currentY + offsetY;\n var boundryX = 0;\n var boundryY = -50;\n var flag = 0;\n \n // Offsetting the ball from the Top and Left for every iteration.\n document.getElementById(\"ball\").style.top = currentY+'px';\n document.getElementById(\"ball\").style.left = currentX+'px';\n \n var paddle = document.getElementById(\"paddle\");\n \n // Gets the rectangle coordinates of the html object.\n var paddlePosition = paddle.getBoundingClientRect();\n \n var ball = document.getElementById(\"ball\");\n \n // Gets the rectangle coordinates of the html object.\n var ballPosition = ball.getBoundingClientRect();\n \n //var co = document.getElementById(\"coordinate\");\n //co.innerHTML=ballPosition.bottom + \"--\" + paddlePosition.top;\n \n // Checking of the ball is crossing the paddle.\n if(ballPosition.right>=1085)\n {\n // Check if the ball is in contact with the paddle i.e. ball's coordinates are within the paddle coordinates.\n if(ballPosition.top> paddlePosition.top && ballPosition.top< paddlePosition.bottom)\n {\n rightBorder=1000;\n }\n else if(ballPosition.bottom> paddlePosition.top && ballPosition.top<paddlePosition.bottom)\n {\n rightBorder=1000;\n }\n else if(ballPosition.bottom == paddlePosition.top )\n {\n rightBorder=1002;\n //boundryY=parseInt(paddlePosition.top);\n bottomBorder=parseInt(ballPosition.bottom) - 140;\n }\n else if(ballPosition.top == paddlePosition.bottom)\n {\n rightBorder=1002;\n //bottomBorder=parseInt(ballPosition.bottom);\n boundryY=parseInt(ballPosition.top) - 140;\n }\n else\n {\n // xoffset = xoffset * (-1);\n // Restart the game as soon as the ball misses the paddle.\n restart();\n // Increment the score.\n scoreINT++;\n flag = 1;\n }\n \n }\n \n // Update the score.\n document.getElementById(\"score\").innerHTML = scoreINT;\n if(flag == 0)\n {\n var tempX = parseInt(currentX) + parseInt(offsetX);\n var tempY = parseInt(currentY) + parseInt(offsetY);\n \n /* Check if adding the offset value puts the ball outside the court. If it does, then rebound by setting negative offset.*/ \n if ((tempX >= rightBorder) || (tempX <= boundryX))\n {\n offsetX *=-1;\n }\n if ((tempY >= bottomBorder) || (tempY <= boundryY))\n {\n offsetY *=-1;\n }\n \n // Set timeout according to the ballspeed set.\n timeout = window.setTimeout('bounceball()',ballSpeed);\t\n }\n}", "function BallStartPosition()\n {\n var randomNum = Math.floor(Math.random()*2)\n if(randomNum == 0)\n {\n ball.speedX = -ball.speedX;\n ball.speedY = -ball.speedY;\n }\n if(randomNum == 1)\n {\n ball.speedX = Math.abs(ball.speedX);\n ball.speedY = Math.abs(ball.speedY);\n }\n console.log(randomNum);\n }", "function draw() {\n // put drawing code here\n background(20,20,20, 20);// back ground color\n paddle.run();\n mainBall.run();\n for(var i =0; i < balls.length; i++){\n balls[i].run();\n }\n}", "function ballCollision() {\n if (ballY + ballDY < ballRadius) {\n ballDY = -ballDY;\n }\n if (\n ballX + ballDX + ballRadius > canvas.width ||\n ballX + ballDX < ballRadius\n ) {\n ballDX = -ballDX;\n }\n\n if (\n ballX > paddleX &&\n ballX < paddleX + paddleWidth &&\n ballY + ballDY > paddleY - ballRadius\n ) {\n ballDY = -ballDY;\n }\n\n if (ballY + ballDY + ballRadius > canvas.height) {\n ballDY = 0;\n ballDX = 0;\n }\n}", "function moveBall() {\n ball.xPos += ball.dx;\n ball.yPos += ball.dy;\n\n // Detect Wall Collision (x-axis)\n if (ball.xPos + ball.radius > canvas.width || ball.xPos - ball.radius < 0) {\n ball.dx *= -1;\n }\n // Detect Wall Collision (y-axis)\n if (ball.yPos + ball.radius > canvas.height || ball.yPos - ball.radius < 0) {\n ball.dy *= -1;\n }\n // Detect Paddle Collision\n if (\n ball.xPos - ball.radius > paddle.xPos &&\n ball.xPos + ball.radius < paddle.xPos + paddle.width &&\n ball.yPos + ball.radius > paddle.yPos\n ) {\n ball.dy = -ball.speed;\n }\n // Detect Brick Collision\n bricks.forEach((column) => {\n column.forEach((brick) => {\n if (brick.visible) {\n if (\n ball.xPos - ball.radius > brick.x && // check left brick side\n ball.xPos + ball.radius < brick.x + brick.width && // check right brick side\n ball.yPos + ball.radius > brick.y && // check top brick side\n ball.yPos - ball.radius < brick.y + brick.height // check bottom brick side\n ) {\n ball.dy *= -1;\n brick.visible = false;\n increaseScore();\n }\n }\n });\n });\n // Lose Game If Hit The Bottom Wall\n if (ball.yPos + ball.radius > canvas.height) {\n showAllBricks();\n score = 0;\n }\n}", "function updateBall()\n{\n\tballLastX = ballX;\n\tballLastY = ballY;\n\tif (ballVelocityX > 0)\n\t{\n\t\tballX = ballX + ballSpeed + ballAngleMod;\n\t}\n\telse\n\t{\n\t\tballX = ballX - ballSpeed - ballAngleMod;\n\t}\n\tif (ballVelocityY > 0)\n\t{\n\t\tballY = ballY + ballSpeed;\n\t}\n\telse\n\t{\n\t\tballY = ballY - ballSpeed;\n\t}\n}", "function reload() {\n winProgress = 0;\n paddleX = paddleStartPos;\n gameStart = 0;\n x = canvas.width / 2;\n y = canvas.height / 2;\n dx = startdx;\n dy = 0;\n for (var X = 0; X < brickXCount; X++) { // Reset the existence of the bricks\n for (var Y = 0; Y < brickYCount; Y++) {\n brick[\"x\" + X + \" y\" + Y] = true;\n }\n }\n brickCount = 0;\n}", "function draw() {\n\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n drawBall();\n\n for (i = 0; i < ballArr.length; i++) {\n ballArr[i].xPos += ballArr[i].xVel;\n ballArr[i].yPos += ballArr[i].yVel;\n\n if (ballArr[i].xPos < 0 || ballArr[i].xPos > 640 ) {\n ballArr[i].xVel = -ballArr[i].xVel;\n }\n if (ballArr[i].yPos < 0) {\n ballArr[i].yVel = -ballArr[i].yVel;\n }\n if (ballArr[i].yPos > 480) {\n ballArr.splice(i, 1);\n // initBall(1);\n if (ballArr.length == 0) {\n if (playerLives == 0) {\n clearInterval(drawID);\n } else {\n initBall(2);\n playerLives -= 1;\n var temp = \"Lives: \" + playerLives;\n lives.textContent = temp;\n }\n }\n }\n }\n drawBox(); \n drawPaddle(); \n}", "function speedBall() {\n ball.speedBall();\n}", "function addBall() {\r\n var ball_x = randomInt(50, canvas.width - 50);\r\n var ball_y = randomInt(50, canvas.height - 50);\r\n var ball_dx = randomInt(-10, 10);\r\n var ball_color = colors[randomInt(0, colors.length)];\r\n var ball_radius = randomInt(30, 50);\r\n ballArray.push(new Ball(ball_x, ball_y, ball_dx, 0, ball_radius, ball_color));\r\n}", "function startGame(){\n var x = field.offsetWidth - 150;\n var y = field.offsetHeight - 150;\n\n var randX = Math.floor(Math.random(x) * x);\n var randY = Math.floor(Math.random(y) * y);\n\n var ballPositionX = randX;\n var ballPositionY = randY; \n var id = setInterval(frame, 10);\n\n function frame() {\n\n if (ballPositionX == field.offsetWidth-goal.offsetHeight || ballPositionY == field.offsetHeight-goal.offsetHeight) {\n clearInterval(id);\n } else if (currentPosition === ballPositionX || ballPositionY) {\n ballPositionX ++;\n ballPositionY ++;\n ball.style.top = ballPositionY + 'px';\n ball.style.left = ballPositionX + 'px';\n }\n paddleCollision();\n threeShots();\n }\n }", "function initPaddles()\n{\n // New paddle being created.\n gNumPaddlesCreated++;\n\n // ATI: Draw the paddle for player 1.\n drawPaddle(PADDLE_COLOR_PLAYER_1, START_POS_X_PLAYER_1, START_POS_Y_PLAYER_1, gNumPaddlesCreated);\n\n // New paddle being created.\n gNumPaddlesCreated++;\n\n // ATI: Draw the paddle for player 2.\n drawPaddle(PADDLE_COLOR_PLAYER_2, START_POS_X_PLAYER_2, START_POS_Y_PLAYER_2, gNumPaddlesCreated);\n}", "restart() {\n this.x = ballIni.xIni;\n this.hb.x = this.x + ballHitBox.plusX;\n this.y = ballIni.yIni;\n this.hb.y = this.y + ballHitBox.plusy;\n this.speedx = ballIni.speedX * randomPolarity();\n this.speedy = ballIni.speedY * randomPolarity();\n }", "countFrames() {\nreturn this.fCount;\n}", "function moveBall() {\n ball.x += ball.dx;\n ball.y += ball.dy;\n\n // Wall collision (x => right/left)\n if (ball.x + ball.size > canvas.width || ball.x - ball.size < 0) {\n ball.dx *= -1;\n }\n\n // Wall collison (y => top/bottom)\n if (ball.y + ball.size > canvas.height || ball.y - ball.size < 0) {\n ball.dy *= -1;\n }\n\n // Paddle collision\n if (\n ball.x - ball.size > paddle.x &&\n ball.x + ball.size < paddle.x + paddle.w &&\n ball.y + ball.size > paddle.y\n ) {\n ball.dy = -ball.speed;\n }\n\n // Brick collision\n bricks.forEach((column) => {\n column.forEach((brick) => {\n if (brick.visible) {\n if (\n ball.x - ball.size > brick.x && //left brick side check\n ball.x + ball.size < brick.x + brick.w && // right brick side check\n ball.y + ball.size > brick.y && // top brick side check\n ball.y - ball.size < brick.y + brick.h // bottom brick side check\n ) {\n ball.dy *= -1;\n brick.visible = false;\n\n increaseScore();\n }\n }\n });\n });\n\n // Hit bottom wall - Lose\n if (ball.y + ball.size > canvas.height) {\n showAllBricks();\n score = 0;\n }\n}", "function draw(){\n background(20, 20, 20, 6000);\n\n textSize(15);\n fill(0, 255, 0);\n text(score, 700, 50)\n if(score > 250000){\n fill(255)\n textSize(50);\n text(\"YOU WIN\", 100, 400)}\n // noStroke();\n //noStroke();\n //get rid of outlines\n // noStroke();\n paddle.run();\n for(var i = 0; i < Balls.length; i++){\n Balls[i].run();\n\t\n var altBalls = Balls[i];\n\n var distY = abs(altBalls.loc.y - 560)\n\n if((distY < 10) && (altBalls.loc.x > mouseX - 100) && (altBalls.loc.x < mouseX + 125) && (altBalls.vel.y > 0)){\n Balls.splice(i,1);\n \n // generous scoring, 1000 for every ball\n score = score + 1000;\n }\n\t\n\t\n if((distY < 10) && (altBalls.loc.x > mouseX - 100 ) && (altBalls.loc.x < mouseX + 100) && (altBalls.vel.y < 0)){\n //decides how many balls are going to be in the next \"reset\"\n var numBalls = Balls.length + 50;\n //resets the array (deleted all the current balls)\n Balls = []\n loadBalls(numBalls)\n for(var i = 0; i < Balls.length; i++){\n Balls[i].run;\n }\n }\n }\n}", "function startGame() {\n console.log(\"startGame\");\n score = 0;\n lives = 3;\n\n // function with an array\n for (var i=0; i<total; i++) {\n // every time value ball --> we add a new instance of the object\n balls[i] = new Ball(paddle);\n }\n\n // capital P to denote the name of the class\n // lowercase P to denote the instance of the class\n paddle = new Paddle();\n\n state = 1;\n}", "function init() {\nctx = $('#canvas')[0].getContext(\"2d\");\nreturn setInterval(draw, 50);\n //this tells my ball to be drawn, deleted and redrawn to make it look like its moving within 10 miliseconds\n}", "function NormalMultiplayermode() {\n clear();\n hideButtons();\n text(\"Normal multiplayer\", width / 2, height / 2)\n let r2 = 0;\n let b2 = 255;\n //let button;\n //balls=[]\n\n this.setup = function() {\n createCanvas(800, 400);\n\n ball = new Ball();\n left = new Paddle2(true);\n right = new Paddle2(false);\n\n\n\n this.draw = function() {\n background(0);\n r2 = map(right.y, 0, 400, 255, 0)\n b2 -= map(left.y, 400, 800, 0, 255)\n background(r2, 0, b2)\n\n\n ball.collideright(right);\n ball.collideleft(left);\n\n left.show();\n right.show();\n left.update();\n right.update();\n\n ball.update();\n ball.edges();\n ball.show();\n\n fill(255);\n textSize(32);\n text(Lscore, 32, 40);\n text(Rscore, width - 64, 40);\n\n }\n }\n\n\n\n}", "calculateGameObjectCount() {\n\t\tlet area = window.innerWidth * window.innerHeight;\n\t\tthis.gameObjectCount = Math.floor(area * this.resCoefficient);\n\t\tconsole.log('game object count: ' + this.gameObjectCount);\n\t}", "function run_ball_1() {\r\n id_movingBall(\"p0\", 0);\r\n setInterval(move_Ball_1, 10);\r\n}", "function ballMovement(){\n checkBricks();\n ball.move(dx,dy);\n checkWalls();\n\n}", "playBallAnimation() {\n\t\tthis.ballTimeDiff = new Date().getTime() - this.presentBallTime;\n\t\tif(this.ball.y < this.groundBoundary)\n\t\t\tthis.ballPathMovement();\n\t\telse \n\t\t\tthis.resetBowlingpositions();\n\t}", "createBall() {\n\n this.ball = this.ballsGroup.create(this.paddle.x, 500, 'ball').setCollideWorldBounds(true).setBounce(1);\n //this.ball = this.physics.add.image(this.paddle.x, 500, 'ball').setCollideWorldBounds(true).setBounce(1);\n this.ball.setData('onPaddle', true);\n\n this.physics.add.collider(this.ball, this.bricksGroup, this.hitBrick, null, this);\n this.physics.add.collider(this.ball, this.paddle, this.hitPaddle, null, this);\n }", "function gameLoop(event) {\n stats.begin(); //start counting per frame -\n stage.update(); // redraw/refresh stage every frame\n stats.end(); // - stop counting per frame\n}", "function initBall() {\r\n var velocityRange = 0.1;\r\n // init position array.\r\n positionArray.push(Math.random()*2.0-1.0);\r\n positionArray.push(Math.random()*0.5+0.5);\r\n positionArray.push(Math.random()*2.0-1.0);\r\n\r\n //init velocity array.\r\n var initSpeedX = (Math.random()-0.5)*velocityRange;\r\n var initSpeedY = (Math.random()-0.5)*velocityRange;\r\n var initSpeedZ = (Math.random()-0.5)*velocityRange;\r\n velocityArray.push(initSpeedX);\r\n velocityArray.push(initSpeedY);\r\n velocityArray.push(initSpeedZ);\r\n\r\n // init radius array.\r\n var randomRadius = Math.random()/3.0+0.2;\r\n radiusArray.push(randomRadius);\r\n radiusArray.push(randomRadius);\r\n radiusArray.push(randomRadius);\r\n\r\n // init color array.\r\n colorArray.push(Math.random());\r\n colorArray.push(Math.random());\r\n colorArray.push(Math.random());\r\n}", "function restart()\n{\n /* Reset values */\n rightBorder= 1050;\n bottomBorder = 500;\n //scoreINT = 0;\n currentX=2;\n currentY=Math.random()*400;\n offsetX = 5; \n offsetY = 5;\n var ball = document.getElementById(\"ball\");\n ball.style.top = currentY + 'px';\n ball.style.left = 0 + 'px';\n initialize(); \n}", "function reset() {\n drawBricks();\n ctx.clearRect(ball.x - ball.radius, ball.y - ball.radius, ball.radius*2, ball.radius*2);\n \n ball.x = canvas.width / 2;\n ball.y = canvas.height - 50;\n ball.speed = 5;\n ball.dx = 1;\n ball.dy = -1;\n paddle.x = 110;\n paddle.y = 135;\n drawPaddle();\n \n}", "function update() {\n// update velocity\n vy += gravity; // gravity\n \n // update position\n x += vx;\n y += vy; \n \n // handle bouncing\n if (y > canvas.height - radius){\n \n y = canvas.height - radius;\n vy *= -velRedFac;\n color = getRandomColor()\n };\n // wrap around\n if (x > canvas.width + radius){\n \n x = canvas.offsetLeft;\n };\n if (x < canvas.offsetLeft){\n\n x = canvas.width;\n };\n // update the ball\n drawBall();\n}", "function setupBall() {\n ball.x = width/2;\n ball.y = height/2;\n ball.vx = ball.speed;\n ball.vy = ball.speed;\n}", "function handleBallClick() {\n let answerIdx = generateRandomIdx(props.answers.length);\n let { msg, color } = props.answers[answerIdx];\n if (color === \"red\") {\n // setRedCounter(redCounter + 1);\n setCounterObj({\n redCounter: (counterObj.redCounter + 1),\n greenCounter: counterObj.greenCounter,\n goldenrodCounter: counterObj.goldenrodCounter\n });\n } else if (color === \"green\") {\n // setGreenCounter(greenCounter + 1);\n setCounterObj({redCounter: counterObj.redCounter, greenCounter: (counterObj.greenCounter + 1), goldenrodCounter: counterObj.goldenrodCounter});\n\n } else if (color === \"goldenrod\") {\n // setGoldenrodCounter(goldenrodCounter + 1);\n setCounterObj({redCounter: counterObj.redCounter, greenCounter: counterObj.greenCounter, goldenrodCounter: (counterObj.goldenrodCounter + 1)});\n\n }\n setMsg(msg);\n setColor(color);\n console.log(setCounterObj);\n }", "function newGame() {\n alert('New game'); //debug \n ballXSpeed = 3 * Math.random() + 5; // what is the initial velocity of the ball\n ballYSpeed = 4 * Math.random() + 2;\n keyState = 0; // current state of arrow keys\n count = 0; // tracks game time in 20 ms intervals\n time = 0; // tracks game time\n score = 0; // stores score for each game \n\n field.setColor(fieldColor); //reset field color\n paddle.setColor(paddleColor); // reset paddle color\n ball.setColor(ballColor); // reset ball color\n paddle.setPosition(paddleXPos,paddleYPos); //reset paddle position\n lpaddle.setPosition(lpaddleXPos,lpaddleYPos);\n ball.setPosition(ballXPos,ballYPos);\n\n document.getElementById('instructions').style.display='none';\n\n // alert(\"curr(\" + currx + \",\" + curry + \")\"); //debug\n console.log(\"ball(\" + ball.xpos + \",\" + ball.ypos + \")\"); //debug\n \n intTimeHandle = setInterval(function(){timerTick()},20);\n}", "function ballCollisionsCanvas(){\n if(ball.y + ball.radius > canvas_height){\n ball.ySpeed = -ball.ySpeed;\n }else if(ball.y - ball.radius < 0){\n ball.ySpeed = -ball.ySpeed;\n }\n if(ball.x + ball.radius >= canvas_width){\n ball.xSpeed = -ball.xSpeed;\n }else if(ball.x - ball.radius < 0)\n ball.xSpeed = -ball.xSpeed;\n}", "resetBowlingpositions(){\n\t\tthis.bowler.setPosition(config.width * 0.55, config.height * 0.39);\n\t\tthis.ball.setAlpha(0);\n\t\tthis.ball.setScale(0.2);\n\t\tthis.bowlingStarted = false;\n\t\tthis.ball.setPosition(this.startBowlPosX,this.startBowlPosY)\n\t\tthis.stadiumGroup.hideObj();\n\t\tthis.noOfBalls++;\n\t\tthis.startBallAnimation = false;\n\t\tif(this.noOfBalls < this.overCompleted ) {\n\t\tvar timer = this.time.addEvent({\n\t\t\tdelay: 10000, \n\t\t\tcallback: this.playBowlerAnimation(),\n\t\t\tcallbackScope: this,\n\t\t});\n\t\t} else {\n\t\t\tthis.ball.destroy();\n\t\t\tthis.stadiumGroup.destroyObj();\n\t\t}\n\t}", "function ballCollisionsCanvas() {\n if (ball.y + ball.radius > canvas_height) {\n ball.ySpeed = -ball.ySpeed;\n } else if (ball.y - ball.radius < 0) {\n ball.ySpeed = -ball.ySpeed;\n }\n if (ball.x + ball.radius >= canvas_width) {\n ball.xSpeed = -ball.xSpeed;\n } else if (ball.x - ball.radius < 0)\n ball.xSpeed = -ball.xSpeed;\n}", "function update() {\r\n canvas.clear();\r\n //loop for execute collision check with holes and finish\r\n for (i = 0; i < balls.length; i++) {\r\n if (ball.checkBallCollision(balls[i])) {\r\n if (balls[i].color == \"red\") {\r\n clearInterval(interval);\r\n alert(\"You Lost!!!\" + \"\\n\" + \"Your Time: \" + (Date.now() - ball.time) / 1000)\r\n }\r\n else if (balls[i].color == \"green\") {\r\n clearInterval(interval);\r\n alert(\"You Won!!!\" + \"\\n\" + \"Your Time: \" + (Date.now() - ball.time) / 1000)\r\n }\r\n }\r\n }\r\n ball.update();\r\n //drawing elements from balls list on canvas\r\n balls.forEach(element => {\r\n element.update();\r\n });\r\n\r\n}", "function whileSchleife() {\r\n if(y >= 0){\r\n\t\r\n\t\tdrawBall(zuPixel(x), canvas.height - zuPixel(y));\t\t// 0er Stelle\r\n \r\n vx_1 = vx + ((-1)*konstante/masse) * Math.sqrt(vx*vx + vy*vy) * vx * dt;\r\n vy_1 = vy + ((-1)*konstante/masse * Math.sqrt(vx*vx + vy*vy) * vy - g) * dt; \r\n \r\n x_1 = x + (vx * dt);\r\n y_1 = y + (vy * dt); \r\n \r\n if(ball) { \r\n ctx.clearRect(0, 0, canvas.width, canvas.height); // canvas resetten\r\n zeichneKoordinatenSystem(); // Koordinatensystem neu zeichnen\r\n //displayData(x_1, laufvariable*dt); // weite, Zeit usw LIVE anzeigen (nur im \"ball\" Modus möglich)\r\n }\r\n\t\t\r\n\t\tdisplayData(x_1, laufvariable*dt); // ALLE MODI MÖGLICH DA AUSLAGERUNG IN DIV BOX\r\n\t\t\r\n\t\tif(ball && y_1 < 0) {\r\n\t\t\tdrawBall(zuPixel(x_1), canvas.height - 10);\r\n\t\t} else {\r\n\t\t\tdrawBall(zuPixel(x_1), canvas.height - zuPixel(y_1));\r\n\t\t}\r\n \r\n // wenn aktuelle y größer als vorheriges y --> dann maximale Höhe erreicht\r\n if(y_1 >= y){\r\n maxHeight = (y_1).toFixed(2); // Höhe auf 2 Nachkommastellen runden\r\n }\r\n \r\n vx = vx_1;\r\n vy = vy_1;\r\n \r\n x = x_1;\r\n y = y_1;\r\n laufvariable++;\r\n \r\n } else {\r\n stop();\r\n\t\tdisplayData(x, laufvariable*dt);\r\n knopfEin();\r\n }\r\n}", "function addCount() {\n game.count++;\n $(\"#count\").text(game.count);\n $(\"#count\").addClass('animated bounce');\n setTimeout(() => {\n $('#count').removeClass('animated bounce');\n }, 800);\n newMove();\n }", "function newGame() {\n // Initialize the ball\n ball.x = level.x + (level.width - ball.width) / 2;\n ball.y = level.y + level.height - ball.height;\n ball.speed = 500;\n\n // Random direction\n ball.xdir = 0.4 + (Math.random())/2;\n ball.ydir = -1;\n\n // Random left or right\n if (Math.random() < 0.5) {\n ball.xdir *= -1;\n }\n\n // Normalize the direction\n var dirlen = Math.sqrt(ball.xdir*ball.xdir + ball.ydir*ball.ydir);\n ball.xdir /= dirlen;\n ball.ydir /= dirlen;\n\n score = 0;\n\n blocked = false;\n blockedtime = blockcooldown;\n gameover - trye;\n gameovertime = 0;\n}", "function addBall(){\n ball = new Circle (BALL_RADIUS);\n ball.setPosition(getWidth()/2, getHeight()/2);\n add(ball);\n}", "function update_ball_positions(){\r\n for (let b = 0; b < balls.length; b++){\r\n let ball = balls[b];\r\n ball.x += time_delta_s * ball.vx;\r\n ball.y += time_delta_s * ball.vy;\r\n }\r\n}", "function ball() {\r\n ctx.fillStyle = 'white';\r\n ctx.fillRect(ballX, ballY, ballSize, ballSize);\r\n // ruch pilki\r\n ballX += ballSpeedX;\r\n ballY += ballSpeedY;\r\n // przyspieszanie piłki gdy pilka odbija sie od paletek lub scianek\r\n if (ballY >= ch - ballSize || ballY <= 0) {\r\n ballSpeedY *= -1;\r\n speedUp();\r\n }\r\n if (ballX <= playerX + paddelWidth && ballX >= playerX && ballY >= playerY - ballSize && ballY <= playerY + paddelHeight) {\r\n ballSpeedX *= -1;\r\n speedUp();\r\n }\r\n if (ballX >= aiX - ballSize && ballY > aiY - ballSize && ballY < aiY + paddelHeight) {\r\n ballSpeedX *= -1;\r\n speedUp();\r\n }\r\n //zapisywanie wyniku\r\n if (ballX <= 0) {\r\n updateScore(ai);\r\n }\r\n\r\n if (ballX >= cw - ballSize) {\r\n updateScore(player);\r\n }\r\n}", "function addBall(){\n\tvar color = 'rgb(' + parseInt(Math.random() * 255) + ', ' +\n\t\tparseInt(Math.random() * 255) + ', ' +\n\t\tparseInt(Math.random() * 255) + ')';\n\tvar radius = 5 + Math.floor(Math.random() * 30);\n\t// when random = 1, x = canvas width - radius\n\t// when random = 0, x = radius. so all balls are within canvas\n\tvar x = radius + Math.random() * (canvas.width - 2 * radius);\n\tvar y = Math.random() * canvas.height / 4;\n \tvar ball = new Ball(x, y, radius, color);\n \tballArray.push(ball);\n}", "function init() { \n /* set the player paddle location */\n player.x = player.width;\n player.y = (HEIGHT - player.height) / 2;\n\n /* set the ai paddle location */\n ai.x = WIDTH - (player.width + ai.width);\n ai.y = (HEIGHT - ai.height) / 2;\n\n /* update score board */\n updateScoreBoard();\n\n /* serve the ball to start a round */\n ball.serve(1);\n}", "reset() {\n //spawns it at the middle of the sketch\n this.x = width / 2;\n this.y = height / 2;\n //allows the ball to pop up at a random speed and angle when it has been generated\n let angle = random(-PI / 4, PI / 4);\n this.ballvx = 5 * Math.cos(angle);\n this.ballvy = 5 * Math.sin(angle);\n\n if (random(1) < 0.5) {\n this.ballvx *= -1;\n }\n }", "function ballDrops(reset=false){\r\nif(ball1.yPos>480 || reset){\r\ndocument.getElementById('coinDrop').play()\r\nif(score>1 && score%5==0){carSpeed+=1};\r\nif(reset){score=0};\r\nreset=false;\r\nball1=new Ball(randomInt(40,400),screen,ballStartHeight,20,randomColor());\r\ndocument.getElementById('score').innerText=score;\r\n\tdocument.body.style.backgroundColor=randomColor();\t\r\n\r\n\t}\r\n}", "function main() {\n\t\t\t\tcanvas = document.getElementById(\"pong\");\n\t\t\t\tscore = 0;\n\t\t\t\tplaying = true;\n\t\t\t\tcanvasWidth = canvas.width;\n\t\t\t\tcanvasHeight = canvas.height;\n\t\t\t\tctx = canvas.getContext(\"2d\");\n\t\t\t\tball.init(canvasWidth/2,canvasHeight/2);\n\t\t\t\tplayer.init();\n\t\t\t\tcomputer.init(); \n\t\t\t\twindow.requestAnimationFrame(loop,canvas);\n\t\t\t}", "function startBall () {\n\tlet direction = 1; \n\ttopPositionOfBall = startTopPositionOfBall;\n\tleftPositionOfBall = startLeftPositionOfBall;\n\n\t//50% change of starting in either direction (right of left)\n\tif (Math.random() < 0.5){\n\t\tdirection = 1;\n\t} else {\n\t\tdirection = -1;\n\t}//else\n\n\n\ttopSpeedOfBall = Math.random() * 2 + 3; //3-4\n\tleftSpeedOfBall = direction * (Math.random() * 2 + 3); \n\n\toriginalTopSpeedOfBall = topSpeedOfBall;\n\toriginalLeftSpeedOfBall = leftSpeedOfBall;\n\n}//startBall", "function init() {\r\n bluePlayersCount = document.getElementById('bluePlayers').value;\r\n redPlayersCount = document.getElementById('redPlayers').value;\r\n fps = document.getElementById('fps').value;\r\n // set our config variables\r\n canvas = document.getElementById('mainCanvas')\r\n ctx = canvas.getContext('2d');\r\n\r\n ball = new Ball(600, 300, 0);\r\n\r\n blueTeam = new Team(teamColors.BLUE);\r\n redTeam = new Team(teamColors.RED);\r\n\r\n entities = [\r\n field = new Field(),\r\n BallManager,\r\n blueTeam,\r\n redTeam,\r\n ball\r\n ];\r\n\r\n animate();\r\n}", "function gameLoop() {\n stats.begin(); // Begin measuring\n field.update();\n player.update();\n ball.update();\n for (var cloud = 0; cloud < 3; cloud++) {\n clouds[cloud].update();\n collision.check(clouds[cloud]);\n }\n collision.check(ball);\n scoreboard.update();\n stage.update();\n stats.end(); // end measuring\n}", "function addBallIfy() {\n if (balls.length < 160) {\n balls.push(getRandomBall());\n }\n}", "function addBall() {\n\tvar rows = gBoard.length;\n\tvar colls = gBoard[0].length;\n\tvar i = getRandomIntInclusive(0, rows - 1);\n\tvar j = getRandomIntInclusive(0, colls - 1);\n\n\tvar randomCell = gBoard[i][j];\n\tif (randomCell.type === WALL) return;\n\telse if (randomCell.gameElement !== null) return;\n\telse if (gIsGameOn) {\n\t\tgBoard[i][j].gameElement = BALL\n\t\tgBallsToCollect++;\n\t}\n\n\trenderCell({ i, j }, BALL_IMG);\n}" ]
[ "0.68659145", "0.664891", "0.66295743", "0.6608874", "0.6597889", "0.6588052", "0.6557229", "0.65261436", "0.64753914", "0.6460155", "0.6428755", "0.64130485", "0.63775074", "0.63549125", "0.6314341", "0.62728345", "0.6265309", "0.62562776", "0.6252278", "0.623935", "0.62315315", "0.62308186", "0.62229264", "0.62067646", "0.61836743", "0.6134715", "0.61329305", "0.61287415", "0.61287415", "0.61268497", "0.6113959", "0.61082244", "0.6085304", "0.6081383", "0.6070075", "0.60698515", "0.6068908", "0.60670537", "0.6061539", "0.6053494", "0.6051777", "0.6039686", "0.6010878", "0.60054934", "0.6002047", "0.6001966", "0.59902036", "0.59646684", "0.5962884", "0.5953888", "0.59268606", "0.5926533", "0.5924342", "0.59200615", "0.59126365", "0.5912612", "0.5912079", "0.59082603", "0.59076476", "0.59026873", "0.59025365", "0.59024626", "0.59003526", "0.5899142", "0.58972627", "0.5893061", "0.5877358", "0.5870495", "0.5870346", "0.5868267", "0.5861846", "0.58504", "0.5848207", "0.584214", "0.58394104", "0.583542", "0.58344203", "0.5832997", "0.5826406", "0.5826094", "0.5825501", "0.58235997", "0.58233684", "0.582173", "0.5820776", "0.58155173", "0.5811501", "0.58018386", "0.5797184", "0.5795372", "0.5794752", "0.5792206", "0.57889986", "0.57867515", "0.5783052", "0.57807285", "0.5780219", "0.5779369", "0.57748127", "0.5773854", "0.57687306" ]
0.0
-1
draws a circle with correct position, color and radius
draw () { let context = canvas.getContext("2d"); context.beginPath(); context.arc( this.position.x, this.position.y, this.radius, 0, 2 * Math.PI ); context.fillStyle = this.color; context.fill(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function drawCircle(x,y,radius,color)\r\n{\r\n\tdrawArc(x, y, radius, 0, Math.PI * 2, color);\r\n}", "function drawCircle(center, radius, color) {\n context.beginPath();\n context.arc(center.x * 4800, center.y * 4800, 2 * .0025 * canvas.width, 2 * Math.PI, false);\n context.closePath();\n context.fillStyle = color;\n context.fill();\n }", "function draw_circle(x, y, radius, color){\r\n //color = ('0' + (x / cnvs.width) * 0xff).toString(16).substr(-2).repeat(3);\r\n ctx.beginPath();\r\n ctx.arc(x, y, radius, 0, Math.PI * 2);\r\n ctx.fillStyle = color;\r\n ctx.fill();\r\n}", "function drawCircle(radius, x, y) { svg.append(\"circle\").attr(\"fill\", \"red\").attr(\"r\", radius).attr(\"cx\", x).attr(\"cy\", y); }", "function drawCircle(pos, radius, ctx) {\n ctx.beginPath();\n ctx.arc(pos.x, pos.y, radius, 0, Math.PI*2, true); \n ctx.closePath();\n}", "function drawCircle(context, color, centerX, centerY, radius) {\n context.beginPath();\n context.fillStyle = color;\n context.arc(centerX, centerY, radius, 0, Math.PI * 2);\n context.closePath();\n context.fill();\n}", "function circle(x, y, r) {\n\tctx.beginPath();\n\tctx.arc(x, y, r, 0, 6.28);\n\tctx.closePath();\n\tctx.fillStyle = \"peru\"\n\tctx.fill();\n}", "function drawCircle(x,y,r,color){\r\n ctx.fillStyle=color;\r\n ctx.beginPath();\r\n ctx.arc(x,y,r,0,2*Math.PI,false);\r\n ctx.closePath();\r\n ctx.fill();\r\n}", "function drawCircle( center, radius, color ) {\n if (color === undefined) {\n color = black8;\n }\n ctx.beginPath();\n ctx.arc(\n center[0], // center x coordinate\n center[1], // center y coordinate\n radius, // radius\n 0, // starting angle\n 2 * Math.PI // ending angle\n );\n ctx.closePath();\n\n if ( radius < 40 ) {\n ctx.fillStyle = color;\n ctx.fill();\n } else {\n ctx.strokeStyle = color;\n ctx.stroke();\n }\n}", "function colorCircle(centerX, centerY, radius, drawColor){\n canvasContext.fillStyle = drawColor;\n canvasContext.beginPath();\n canvasContext.arc(centerX, centerY, radius, 0, Math.PI * 2, true);\n canvasContext.fill();\n}", "function drawCircle(ctx, x, y, r) {\n ctx.beginPath();\n ctx.arc(x, y, r, 0, 2*Math.PI);\n ctx.fill();\n}", "function circle(x,y,radius) { \n ctx.beginPath();\n ctx.arc(x, y, radius,0, 2*Math.PI);\n ctx.fill();\n ctx.stroke();\n}", "function drawCircle( x, y ) {\n ctx.beginPath();\n ctx.arc(x, y, radius, 0, Math.PI * 2);\n ctx.fillStyle = color;\n ctx.fill();\n}", "function circle(x, y, radius) {\n ctx.beginPath()\n ctx.arc(x, y, radius, 0, 2 * Math.PI)\n ctx.fill()\n}", "function drawCircle(_x, _y, _color) {\r\n //Circle\r\n crc2.beginPath();\r\n crc2.arc(_x, _y, 2, 0, 2 * Math.PI);\r\n crc2.fillStyle = _color;\r\n crc2.fill();\r\n }", "function drawCircle(myContext, color, x, y, radius){\n myContext.save();\n myContext.beginPath();\n myContext.fillStyle = color;\n myContext.arc(x, y, radius, 0, 2*Math.PI, false);\n myContext.fill();\n myContext.closePath();\n myContext.restore();\n}", "function drawCircle(x, y, radius, fill_color, stroke_color, stroke_size){\r\n\t\tcontext.beginPath();\r\n\t\tcontext.arc(x, y, radius, 0, 2 * Math.PI, false);\r\n\t\tcontext.closePath();\r\n\t\tif(fill_color != null){\r\n\t\t\tcontext.fillStyle = fill_color;\r\n\t\t\tcontext.fill();\r\n\t\t}\r\n\t\tif(stroke_color != null){\r\n\t\t\tcontext.lineWidth = stroke_size;\r\n\t\t\tcontext.strokeStyle = stroke_color;\r\n\t\t\tcontext.stroke();\r\n\t\t}\r\n\t}", "draw(ctx, colour = 'red', radius = 10){\n this.radius = radius;\n ctx.beginPath();\n ctx.fillStyle = colour;\n ctx.strokeStyle= 'white';\n ctx.arc(this.x, this.y, radius, 0, Math.PI * 2);\n ctx.fill();\n ctx.stroke();\n ctx.closePath();\n }", "function drawCircle( x, y ) {\n ctx2.beginPath();\n ctx2.arc(x, y, radius, 0, Math.PI * 2);\n ctx2.fillStyle = color;\n ctx2.fill();\n }", "function drawCircle(context,circle) {\n context.beginPath();\n context.arc(circle.x,circle.y,circle.r,0,Math.PI*2,true);\n context.closePath();\n context.stroke();\n }", "function drawCircle(){\n //ctx.beginPath();\n ctx.arc(100, 75, 50, 0, 2 * Math.PI);\n ctx.stroke();\n }", "function circle(ctx, x, y, r){\n\n\tctx.beginPath();\n\tctx.arc(x, y, r, 0, 2 * Math.PI);\n\tctx.fill();\n\t// draw border around circle\n\tctx.stroke();\n}", "function draw_circle(color, y, x) {\n\t\t\tvar radius = (parameters.size[1] >= parameters.size[0]) ? Math.floor(target.height / parameters.size[1]) / 3 \n\t\t\t: Math.floor(target.width / parameters.size[0]) / 3; \n\t\t\tcontext.beginPath();\n\t\t\tcontext.arc(y, x, radius,\n\t\t\t\t0 * Math.PI, 2 * Math.PI);\n\t\t\t\tcontext.fillStyle = color;\n\t\t\t\tcontext.fill();\n\t\t\t\tcontext.strokeStyle = \"black\";\n\t\t\t\tcontext.stroke();\n\t\t\t}", "function drawCircle() {\n ctx.beginPath();\n ctx.arc(\n x,\n y,\n ballRadius,\n 0,\n 360\n ); /* 360 == Math.PI, Documentation says last two params should be in radians, but degrees work the same ... */\n ctx.fillStyle = playerColor;\n ctx.fill();\n ctx.closePath();\n}", "function Circle(x, y, r, color){\n\tctx.beginPath();\n\t\n\tthis.color = color\n\tif(this.color != undefined){\n\t\tctx.fillStyle = this.color\n\t}else{\n\t\tctx.fillStyle=col;\n\t}\n\tctx.arc(x, y,r,0,2*Math.PI);\n\tctx.fill();\n}", "function drawCircle(){\nctx.fillStyle = 'green'\nctx.beginPath()\nctx.arc(canvas.width/2, canvas.height/2, canvas.height/4, 0, Math.Pi * 2, false)\nctx.fill()\n}", "function drawcircle()\n{\n\tctx.fillStyle='#0079B8';\n\tctx.beginPath();\n\tctx.arc(x1,y1,20,0,2*Math.PI);\n\tctx.fill();\n\tctx.strokeStyle=\"white\"\n\tctx.stroke();\n}", "function drawCircle(data) {\n circle.beginPath();\n circle.arc(data.x, data.y, data.r, 0, Math.PI * 2);\n circle.fillStyle = data.c;\n circle.fill();\n}", "function colourCircle(centerX, centerY, radius, colour) {\n\tcanvasContext.fillStyle = colour;\n\tcanvasContext.beginPath();\n\tcanvasContext.arc(centerX, centerY, radius, 0, Math.PI*2, true);\n\tcanvasContext.fill();\n}", "function Circle(radius, r, g, b, alpha, x, y){\n this.radius = radius;\n this.r = r;\n this.g = g;\n this.b = b;\n this.alpha = alpha;\n this.x = x;\n this.y = y;\n this.draw = function(){\n var c = color(this.r, this.g, this.b, this.alpha);\n fill(c);\n noStroke();\n ellipse(this.x, this.y, this.radius);\n } \n }", "drawCircle(x,y,r){\n ctx.beginPath();\n ctx.arc(x,y,r,0,2*Math.PI);\n ctx.lineWidth = 1;\n ctx.strokeStyle = colourButton.selectedColour;\n ctx.stroke();\n }", "function draw_circle_point(ctx, oldcenterX, oldCenterY, oldRadius, centerX, centerY, radius, vertice) \n{\n\td = (5 - radius * 4)/4;\n\tx = 0;\n\ty = radius;\n\n\tdo {\n\t\tdraw_pixel_selection(ctx,centerX + x, centerY + y, oldcenterX, oldCenterY, oldRadius, vertice);\n\t\tdraw_pixel_selection(ctx,centerX + x, centerY - y, oldcenterX, oldCenterY, oldRadius, vertice);\n\t\tdraw_pixel_selection(ctx,centerX - x, centerY + y, oldcenterX, oldCenterY, oldRadius, vertice);\n\t\tdraw_pixel_selection(ctx,centerX - x, centerY - y, oldcenterX, oldCenterY, oldRadius, vertice);\n\t\tdraw_pixel_selection(ctx,centerX + y, centerY + x, oldcenterX, oldCenterY, oldRadius, vertice);\n\t\tdraw_pixel_selection(ctx,centerX + y, centerY - x, oldcenterX, oldCenterY, oldRadius, vertice);\n\t\tdraw_pixel_selection(ctx,centerX - y, centerY + x, oldcenterX, oldCenterY, oldRadius, vertice);\n\t\tdraw_pixel_selection(ctx,centerX - y, centerY - x, oldcenterX, oldCenterY, oldRadius, vertice);\n\t\tif (d < 0) {\n\t\t\td += 2 * x + 1;\n\t\t} else {\n\t\t\td += 2 * (x - y) + 1;\n\t\t\ty--;\n\t\t}\n\t\tx = x + 1;\n\t} while (x <= y);\n}", "function drawCircle(idx, size, col){\n\t\t\tvar c = new Path.Circle(new Point(spaces[idx].pos_x,(spaces[idx].pos_y)),size).fillColor = col;\n\t\t\treturn c;\n\t\t}", "function drawCircle(x,y,r,f,s){\r\n ctx.beginPath()\r\n ctx.arc(x,y, r, 0, 2*Math.PI);\r\n if(f){\r\n ctx.fill();\r\n }\r\n if(s){\r\n ctx.stroke();\r\n }\r\n }", "function drawCircle(ctx, x, y, radius, type) {\n if (type == \"full\") {\n ctx.fillStyle = 'rgba(3, 179, 0, 1.0)';\n } else if (type == \"partial\") {\n ctx.fillStyle = 'rgba(181, 91, 0, 1.0)';\n } else if (type == \"empty\") {\n ctx.fillStyle = 'rgba(173, 0, 179, 1.0)';\n } else if (type == \"hint\") {\n ctx.lineWidth = 2;\n ctx.strokeStyle = \"rgba(0, 255, 255, 1.0)\";\n }\n\n ctx.beginPath();\n ctx.arc(x*iMult, y*iMult, radius/iMult, 0, Math.PI*2, true);\n ctx.stroke();\n if (type != \"hint\") {\n ctx.fill();\n } else {\n ctx.lineWidth = 1;\n ctx.strokeStyle = \"black\";\n }\n}", "function drawFancyCircle(x, y, radius, color){\r\n\t\tvar rgb = hexToRgb(color);\r\n\t\tvar light_rgb = [Math.round(Math.min(rgb[0]+100,255)), Math.round(Math.min(rgb[1]+100,255)), Math.round(Math.min(rgb[2]+100,255))];\r\n\t\tvar ambient_rgb = [Math.round(rgb[0]/4.0), Math.round(rgb[1]/4.0), Math.round(rgb[2]/4.0)];\r\n\t\tvar light_x = x-radius*(x/theCanvas.width-.5)*1.5;\r\n\t\tvar light_y = y-radius*(y/theCanvas.height-.5)*1.5;\r\n\t\tdrawLitCircle(x,y,radius,color, light_x, light_y, rgbToHex2(light_rgb), rgbToHex2(ambient_rgb),rgbToHex2(light_rgb), 1);\r\n\t}", "function drawCircle( c ) {\n \n context.beginPath(); \n context.arc( c.x, c.y, c.size/2, 0, Math.PI * 2 );\n context.fillStyle = c.color;\n context.fill(); \t\t\t\n context.closePath(); \n \n } //drawCircle() ", "function drawCircle(cX, cY, cSize, cColor) {\n\tellipseMode(CORNER);\n\tstrokeWeight(6);\n\tstroke(135, 206, 250);\n\tfill(cColor);\n\tellipse(cX, cY, cSize, cSize);\n}", "function drawCircle(ctx, center, r, sc, lw, fc, mousePos, withPoints){\n\t\tif(!center) return;\n\t\tvar x = center.x, y = center.y;\n\t\tctx.strokeStyle = sc || ctx.strokeStyle;\n\t\tctx.lineWidth = lw || ctx.lineWidth;\n\t\tctx.fillStyle = fc || ctx.fillStyle;\n\t\t\n\t\t//if the r parameter is null, it means that we are constructing a circle, so we determine the radius based on the mouse position\n\t\tif(!r){\n\t\t\tr = Math.sqrt((mousePos['x'] - x)*(mousePos['x'] - x) + (mousePos['y'] - y)*(mousePos['y'] - y));\n\t\t\t\n\t\t\t//also, we connect the center point with the pouse position, drawing a radius\n\t\t\tdrawLine(ctx, center, mousePos, sc, lw);\n\t\t}\n\t\tctx.beginPath();\n\t\tctx.arc(x, y, r, 0, 2 * Math.PI, false);\n\t\tctx.fill();\n\t\tctx.closePath();\n\t\tctx.stroke();\n\t\t\n\t\t//if we are in the edit mode and this circle is selected\n\t\tif(withPoints){\n\t\t\tsetPoint(ctx, center, M.radius, M.curColor, M.lineWidth, M.curColor);\n\t\t\tdrawLine(ctx, center, {x:center.x + r, y:center.y}, sc, lw);\n\t\t\tsetPoint(ctx, {x:center.x + r, y:center.y}, 4, M.curColor, M.lineWidth, M.curColor);\n\t\t\tdrawLine(ctx, center, {x:center.x - r, y:center.y}, sc, lw);\n\t\t\tsetPoint(ctx, {x:center.x - r, y:center.y}, 4, M.curColor, M.lineWidth, M.curColor);\n\t\t\tdrawLine(ctx, center, {x:center.x, y:center.y + r}, sc, lw);\n\t\t\tsetPoint(ctx, {x:center.x, y:center.y + r}, 4, M.curColor, M.lineWidth, M.curColor);\n\t\t\tdrawLine(ctx, center, {x:center.x, y:center.y - r}, sc, lw);\n\t\t\tsetPoint(ctx, {x:center.x, y:center.y - r}, 4, M.curColor, M.lineWidth, M.curColor);\n\t\t}\n\t}", "function drawCircle(x, y, radius, start=0, end=2 * Math.PI){\n ctx.beginPath();\n ctx.arc(x, y, radius, start, end);\n ctx.fillStyle = \"red\";\n ctx.strokeStyle = \"blue\";\n ctx.fill();\n}", "function createFilledCircle(x,y,radius,color){\n let circle = GOval(x - radius,y - radius,2 * radius,2 * radius);\n circle.setColor(color);\n circle.setFilled(true);\n return circle;\n }", "function drawACircle(canvasObject, x, y, radius, color){\n var curCtx = document.getElementById(canvasObject.canvasId).getContext(\"2d\");\n curCtx.beginPath();\n curCtx.arc(x, y, radius, 0, 2 * Math.PI, false);\n curCtx.fillStyle = color; \n curCtx.fill(); \n}", "function circle(x,y,r) {\n ctx.fillStyle= \"#00BFFF\";\n //this colours my circle blue\n ctx.beginPath();\n ctx.arc(x, y, r, 0, Math.PI*2, true);\n ctx.closePath();\n ctx.fill();\n \n}", "function Circle(ctx, x, y) {\n\tvar r = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 8;\n\tvar color = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : '#ff0000';\n\n\tctx.beginPath();\n\tctx.arc(x, y, r, 0, 2 * PI, false);\n\tctx.fillStyle = color;\n\tctx.fill();\n}", "drawCircle () {\n const context = this.canvas.getContext('2d')\n const [x, y] = this.center\n const radius = this.size / 2\n\n for (let angle = 0; angle <= 360; angle++) {\n const startAngle = (angle - 2) * Math.PI / 180\n const endAngle = angle * Math.PI / 180\n context.beginPath()\n context.moveTo(x, y)\n context.arc(x, y, radius, startAngle, endAngle)\n context.closePath()\n context.fillStyle = 'hsl(' + angle + ', 100%, 50%)'\n context.fill()\n }\n }", "function Circle(x, y, r, color)\n{\n //parameters\n this.x = x;\n this.y = y;\n this.r = r;\n this.color = color;\n\n //methods\n //draw circle on canvas\n this.draw = function()\n {\n context.beginPath();\n\n //-------------Circle drawing-------------\n //circle at top\n context.arc(this.x, this.y, this.r, 0, Math.PI * 2, true);\n context.fillStyle = this.color;\n context.fill();\n context.strokeStyle = this.color;\n context.stroke();\n context.closePath();\n };\n}", "function drawUnitCircle(color) {\n context.fillStyle = color;\n context.beginPath();\n context.arc(0,0,1,0,2*Math.PI);\n context.fill();\n}", "function Circle(x,y,r, color) { //circle object\r\n this.x = x;\r\n this.y = y;\r\n this.r = r;\r\n this.color = color;\r\n}", "draw() {\n\t\tnoStroke();\n\t\tfill(\"rgba(255, 255, 255, 0.1)\");\n\t\tcircle(this.pos.x, this.pos.y, this.size);\n\t}", "function circlePattern(radius, color) {\n var radius = radius;\n context.fillStyle = color;\n //begin drawing the circle\n context.beginPath();\n context.arc(centerX, centerY, radius, 0, 2 * Math.PI);\n context.fill();\n context.closePath();\n }", "function drawCircle(r, lon, lat) {\n var circle = d3.geoCircle().radius(r).center([lon, lat]);\n circles = [circle()];\n context.beginPath(),\n path({type: \"GeometryCollection\",\n geometries: circles}),\n context.fillStyle = \"rgba(255, 0, 0, .75)\",\n context.fill();\n}", "function drawDot(center, radius, color) {\n ctx.beginPath();\n ctx.arc(center.x, center.y, radius, 0 , 2 * Math.PI);\n ctx.fillStyle = color;\n ctx.fill();\n}", "function drawCircle(x, y) {\n canvasObject.beginPath();\n canvasObject.arc(x, y, 5, 0, Math.PI * 2);\n canvasObject.fillStyle = 'red';\n canvasObject.fill();\n canvasObject.stroke();\n}", "draw() {\n\t\tnoStroke();\n\t\tfill('rgba(255,255,255,0.5)');\n\t\tcircle(this.pos.x, this.pos.y, this.size);\n\t}", "function drawCircle(context, x, y, r, color, fill){\n context.beginPath();\n context.arc(x, y, r, 0, 2 * Math.PI, true);\n context.closePath();\n if(fill){\n context.fillStyle = color;\n context.fill(); \n }else{\n context.strokeStyle = color;\n context.stroke();\n }\n}", "function circle(args) {\n\t\tvar ctx = args[0];\n\t\tvar circeCenterX = args[1];\t// Centro del cerchio, coordinata X\n\t\tvar circeCenterY = args[2];\t// Centro del cerchio, coordinata Y\n\t\t\n\t\tvar colorCircle = args[3];\t// Colore del cerchio\n\t ctx.fillStyle = colorCircle;\n\t \n\t\tctx.beginPath();\n\t /*\n\t Parametri funzione .arc(x, y, r, sAngle, eAngle):\n\t - x: coordinata X del centro del cerchio\n\t - y: coordinata X del centro del cerchio;\n\t - r: raggio;\n\t - sAngle: angolo di inizio in radianti\n\t - eAngle: angolo di fine in radianti\n\t */\n\t ctx.arc(circeCenterX, circeCenterY, 2, 0, 2 * Math.PI);\n\t ctx.stroke();\n\t ctx.fill();\n\t}", "draw() {\n ctx.beginPath();\n ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2, false); //creates a circle\n ctx.fillStyle = '#ffffff';\n ctx.fill();\n }", "function drawCircle(circle, color, line_w = 2) {\n\n context.beginPath();\n context.arc(circle.x, circle.y, circle.r, 0, Math.PI * 2);\n context.closePath();\n if (line_w == 0) {\n context.fillStyle = color;\n context.fill();\n } else {\n context.strokeStyle = color;\n context.lineWidth = line_w;\n context.stroke();\n }\n\n}", "function Circle() {var _this6;var centerX = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0.0;var centerY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0.0;var radius = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1.0;var style = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : DefaultStyle.clone();var tessSegments = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 20;_classCallCheck(this, Circle);\n _this6 = _possibleConstructorReturn(this, _getPrototypeOf(Circle).call(this, style));\n\n _this6.polygon = new Polygon([], style);\n\n // Force polygon.id to be the same, so that its geometry is associated with this Circle.\n // This is a bit hacky, but can be removed as soon as we use native arcs for circle rendering.\n _this6.polygon.id = _this6.id;\n\n _this6.centerX = centerX;\n _this6.centerY = centerY;\n _this6.radius = radius;\n _this6.tessSegments = tessSegments;\n\n _this6.needsUpdate = true;return _this6;\n }", "function draw(){\n console.log(\"I am going to draw!\");\n ctx.beginPath();\n ctx.arc(x, y, radius, 0, 2*Math.PI);\n ctx.fill();\n}", "function ksfCanvas_drawCircle(cx, cy, px, py)\n{\n\tthis.clear();\n\tvar r;\n\talpha = 1;\n\tcontext.beginPath();\n\tcontext.fillStyle = \"rgba(255, 0, 0, \"+(alpha/2)+\")\";\n\tcontext.arc(cx, cy, 5, 0, Math.PI*2);\n\tcontext.arc(px, py, 5, 0, Math.PI*2);\n\tcontext.closePath();\n\tcontext.fill();\n\tcontext.save();\n\tr = Math.sqrt(Math.pow(px-cx,2)+Math.pow(py-cy,2));\n\tcontext.beginPath();\n\tcontext.arc(cx, cy, r, 0, Math.PI*2);\n\tcontext.closePath();\n\tcontext.restore();\n\tcontext.stroke();\n}", "function Circle (x, y, dx, dy, radius) {\n this.x = x;\n this.y = y;\n this.dx = dx;\n this.dy = dy;\n this.radius = radius;\n\n // Create a nameless function\n this.draw = function() {\n context.beginPath();\n // arc(x, y, radius: Int, startAngle: float, endAngle: float, drawCounterClockwise: bool)\n context.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);\n context.strokeStyle = ' #000000';\n //context.strokeStyle = '#'+Math.floor(Math.random()*16777215).toString(16);\n context. stroke();\n }\n\n this.update = function() {\n if( this.x + this.radius > innerWidth || this.x - this.radius < 0 ) {\n this.dx = -this.dx;\n }\n \n if( this.y + this.radius > innerHeight || this.y - this.radius < 0 ) {\n this.dy = -this.dy;\n }\n \n this.x += this.dx;\n this.y += this.dy;\n\n this.draw();\n }\n}", "function drawCircle() {\n var radius = canvas.width / 2;\n var image = ctx.createImageData(2 * radius, 2 * radius);\n var data = image.data;\n\n for (var x = -radius; x < radius; x++) {\n for (var y = -radius; y < radius; y++) {\n var _xy2polar = xy2polar(x, y),\n _xy2polar2 = _slicedToArray(_xy2polar, 2),\n r = _xy2polar2[0],\n phi = _xy2polar2[1];\n\n if (r > radius) {\n // skip all (x,y) coordinates that are outside of the circle\n continue;\n }\n\n var deg = rad2deg(phi);\n\n // Figure out the starting index of this pixel in the image data array.\n var rowLength = 2 * radius;\n var adjustedX = x + radius; // convert x from [-50, 50] to [0, 100] (the coordinates of the image data array)\n var adjustedY = y + radius; // convert y from [-50, 50] to [0, 100] (the coordinates of the image data array)\n var pixelWidth = 4; // each pixel requires 4 slots in the data array\n var index = (adjustedX + adjustedY * rowLength) * pixelWidth;\n\n // This adjusts what values are being shown\n var hue = deg;\n var saturation = r / (radius / 1);\n var value = 1.0;\n\n var _hsv2rgb = hsv2rgb(hue, saturation, value),\n _hsv2rgb2 = _slicedToArray(_hsv2rgb, 3),\n red = _hsv2rgb2[0],\n green = _hsv2rgb2[1],\n blue = _hsv2rgb2[2];\n\n var alpha = 255;\n\n data[index] = red;\n data[index + 1] = green;\n data[index + 2] = blue;\n data[index + 3] = alpha;\n }\n\n }\n\n ctx.putImageData(image, 0, 0);\n }", "function DrawCircle(xc, yc, r){\n /**@todo */\n let x = 0;\n let y = r;\n let d = 3 - 2 * r;\n DrawEightPoints(xc,x,yc,y);\n while(y >= x) //While we're only looking at degrees from 45-90\n {\n x++;\n if(d > 0){\n y--;\n d += 4 * (x-y) + 10;\n }\n else{\n d += 4 * x + 6;\n }\n DrawEightPoints(xc,x,yc,y);\n }\n}", "function drawCircle(X, Y, radius, strokeweight, customRgb) {\r\n if (!(customRgb && Array.isArray(customRgb) && customRgb.length == 3)) {\r\n customRgb = defaultCircleRgb;\r\n }\r\n if (!strokeweight) {\r\n strokeweight = defaultCircleStrokeWeight;\r\n }\r\n if (X && Y && radius) {\r\n processing.fill(customRgb[0], customRgb[1], customRgb[2]);\r\n processing.strokeWeight(strokeweight);\r\n processing.stroke(customRgb[0], customRgb[1], customRgb[2]);\r\n processing.ellipse(X, Y, radius*2, radius*2);\r\n }\r\n }", "function circlePoint(x, y, r, type, force, exceptions) {\n elipsePoint(x, y, r, r, type, force, exceptions);\n }", "function drawCircle(context, oX, oY){\n\t\t\t\n\t\t//center values for the circle for reference\n\t\tvar cX = oX + (this.properties.width/2),\n\t\t cY = oY + (this.properties.height/2);\n\t\t \n\t\t//circle shape draw routine\n\t\tcanvas.context.beginPath();\n\t\tcanvas.context.fillStyle = this.properties.color || 'black';\n\t\tcanvas.context.arc(cX, cY, this.properties.radius, this.properties.startAngle, this.properties.endAngle, false);\n\t\tcanvas.context.fill();\n\t}", "function drawCircle(ctx, size) {\n ctx.beginPath();\n ctx.arc(size / 2, size / 2, size / 2, 0, Math.PI * 2, true);\n ctx.closePath();\n}", "drawColoredCircle(color, ctx, canvas_w, canvas_h) {\n ctx.strokeStyle = color;\n ctx.beginPath();\n ctx.arc(this.x, this.y, 5, 0, 2 * Math.PI);\n ctx.stroke();\n ctx.fillRect(0, 0, canvas_w, canvas_h);\n }", "function redrawCircle(circle) {\n\tcontext.beginPath();\n\tcontext.arc(circle[1], circle[2], circleRadius, 0, 2*Math.PI);\n\tcontext.stroke();\n\tcontext.beginPath();\n}", "function drawCircle(x, y, radius, width, color)\n{\n var canvas = document.getElementById(\"myCanvas\");\n var ctx = canvas.getContext(\"2d\")\n ctx.lineWidth = width;\n ctx.strokeStyle = color;\n ctx.beginPath();\n ctx.arc(x, y, radius, 0, Math.PI * 2, false);\n ctx.stroke();\n}", "drawCircle( x1, y1, radius, r = 0, g = 0, b = 0, a = 1 ) {\n\t\tlet x = radius - 1;\n\t\tlet y = 0;\n\t\tlet dx = 1;\n\t\tlet dy = 1;\n\t\tlet err = dx - ( radius << 1 );\n\n\t\twhile ( x >= y ) {\n\t\t\tthis.setPixel( x1 + x, y1 + y, r, g, b, a );\n\t\t\tthis.setPixel( x1 + y, y1 + x, r, g, b, a );\n\t\t\tthis.setPixel( x1 - y, y1 + x, r, g, b, a );\n\t\t\tthis.setPixel( x1 - x, y1 + y, r, g, b, a );\n\t\t\tthis.setPixel( x1 - x, y1 - y, r, g, b, a );\n\t\t\tthis.setPixel( x1 - y, y1 - x, r, g, b, a );\n\t\t\tthis.setPixel( x1 + y, y1 - x, r, g, b, a );\n\t\t\tthis.setPixel( x1 + x, y1 - y, r, g, b, a );\n\n\t\t\tif ( err <= 0 ) {\n\t\t\t\ty++;\n\t\t\t\terr += dy;\n\t\t\t\tdy += 2;\n\t\t\t}\n\n\t\t\tif ( err > 0 ) {\n\t\t\t\tx--;\n\t\t\t\tdx += 2;\n\t\t\t\terr += dx - ( radius << 1 );\n\t\t\t}\n\t\t}\n\t}", "circ(x0, y0, r, c) {\n // evaluate runtime errors\n this.colorRangeError(c);\n // draw filled circle\n let x = 0;\n let y = r;\n let p = 3 - 2 * r;\n this.circPixGroup(x0, y0, x, y, c);\n while (x < y) {\n x++;\n if (p < 0) {\n p = p + 4 * x + 6;\n }\n else {\n y--;\n p = p + 4 * (x - y) + 10;\n }\n this.circPixGroup(x0, y0, x, y, c);\n }\n }", "draw(){\r\n // acctually, i didnt understood how it works, but it works\r\n ctx.beginPath();\r\n ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2); //circle\r\n ctx.fillStyle = D_color;\r\n ctx.fill();\r\n ctx.closePath();\r\n }", "function drawCircle(x, y, size, color, alpha = 1) {\n ctx.beginPath();\n ctx.globalAlpha = alpha\n ctx.arc(x, y, size, 0, Math.PI*2);\n ctx.fillStyle = color;\n ctx.fill();\n ctx.closePath();\n}", "function ball (x, y, radius, color) {\n ctx.fillStyle = color;\n ctx.beginPath();\n ctx.arc(x, y, radius, 0, Math.PI*2);\n ctx.fill();\n }", "function createCircle(radius){\n return{\n radius,\n draw (){\n console.log('draw');\n }\n };\n\n }", "function drawCircle(context, elem, xp, yp, radiusp) {\n let radius = pc(radiusp, elem.width)\n let y = pc(yp, elem.height);\n let x = pc(xp, elem.width); \n context.arc(x, y, radius, 0 * Math.PI, 2 * Math.PI);\n context.closePath();\n}", "function circle(x, y, px, py) {\n //this is the speed part making the size be determined by speed of mouse\n var distance = abs(x-px) + abs(y-py);\n stroke(r, g, b);\n strokeWeight(2);\n //first set of variables for bigger circle\n r = random(255);\n g = random(255);\n b = random(255);\n\n//second set of colours so the inner circle is different colour or else it is the same\n r2 = random(255);\n g2 = random(255);\n b2 = random(255);\n //this is the big circle\n fill(r, g, b);\n ellipse(x, y, distance, distance);\n //this is the smaller inner circle\n fill(r2, g2, b2);\n ellipse(x, y, distance/2, distance/2);\n}", "function Circle(x, y, dx, dy, radius, r, g, b) {\n this.x = x;\n this.y = y;\n this.dx = dx;\n this.dy = dy;\n this.radius = radius;\n this.minRadius = radius;\n this.r = r;\n this.g = g;\n this.b = b;\n this.color = colorArray[Math.floor(Math.random() * colorArray.length)]\n\n this.draw = function () {\n c.beginPath();\n c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);\n // c.strokeStyle = `rgb(${r}, ${g}, ${b})`;\n // c.fillStyle = `rgb(${r}, ${g}, ${b})`;\n c.fillStyle = this.color\n // c.stroke();\n c.fill();\n }\n this.update = function () {\n if (this.x + this.radius > innerWidth || this.x - this.radius < 0) {\n this.dx = -this.dx;\n }\n if (this.y + this.radius > innerHeight || this.y - this.radius < 0) {\n this.dy = -this.dy;\n }\n this.x += this.dx;\n this.y += this.dy;\n\n\n //INTERACTIVITY portion\n if (mouse.x - this.x < 50 \n && mouse.x - this.x > -50\n && mouse.y - this.y < 50 \n && mouse.y - this.y > -50) {\n if (this.radius < maxRadius) {\n this.radius += 1;\n }\n } else if (this.radius > this.minRadius) {\n this.radius -= 1;\n }\n\n this.draw();\n }\n}", "function drawCircle(x, y, d, fillColor) {\r\n\t\tctx.fillRect(x, y, d, d);\r\n\t\tctx.fillStyle = fillColor;\r\n\t}", "function drawCircle(canvas, context, color) {\n\tvar radius = Math.floor(Math.random() * 40);\n\tvar x = Math.floor(Math.random() * canvas.width);\n\tvar y = Math.floor(Math.random() * canvas.height);\n\n\tcontext.beginPath();\n\tcontext.arc(x, y, radius, 0, degreesToRadians(360), true);\n\n\tcontext.fillStyle = color;\n\tcontext.fill();\n}", "drawPoint() {\n this.ctx.fillStyle = this.color;\n this.ctx.beginPath();\n this.ctx.arc( this.x, this.y, this.pointRadius, 0, 2*Math.PI );\n this.ctx.fill();\n this.ctx.closePath();\n }", "function drawCircle(context){\r\n\tconsole.log(\"drawing circles\");\r\n\tfor(i = 0; i < circles.length; i++){\r\n\t\tcontext.beginPath();\r\n\t\tvar x = circles[i].xCenter;\r\n\t\tvar y = circles[i].yCenter;\r\n\t\tvar radius = circles[i].radius;\r\n\t\tconsole.log(\"drawing a circle at (\" + x + \", \" + y + \") with radius\" + radius);\r\n\t\tcontext.arc(x, y, radius, 0, 2*Math.PI);\r\n\t\tcontext.stroke();\r\n\t}\r\n}", "function circle(x, y, r, ctx) {\n let w = ctx.canvas.width;\n let h = ctx.canvas.height;\n\n //let thickness = 10;\n for (let dy = -r; dy <= r; ++dy) {\n for (let dx = -r; dx <= r; ++dx) {\n const ny = y + dy;\n const nx = x + dx;\n\n if (dy*dy + dx*dx > r*r) continue;\n //if (dy*dy + dx*dx < (r - thickness)*(r - thickness)) continue;\n if (ny <= 0 || ny >= h - 1) continue;\n if (nx <= 0 || nx >= w - 1) continue;\n\n buffer1.data[ny*w*4 + nx*4 + 3] = 255;\n }\n }\n}", "function Circle(x, y, dx, dy, radius) {\n this.x = x;\n this.y = y;\n this.dx = dx;\n this.dy = dy;\n this.radius = radius;\n\n this.draw = function() {\n c.beginPath();\n c.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);\n c.fillStyle = randomHue;\n c.fill();\n c.strokeStyle = randomHue;\n c.stroke();\n }\n\n this.update = function() {\n if (this.x + this.radius > innerWidth || this.x - this.radius < 0) {\n this.dx = -this.dx;\n }\n if (this.y + this.radius > innerHeight || this.y - this.radius < 0) {\n this.dy = -this.dy;\n }\n this.x += this.dx;\n this.y += this.dy;\n\n this.draw();\n }\n}", "function drawCircle(size) {\n\t// Only once\n\tif(myCircle && myMap) {\n\t\tmyCircle.setRadius(parseInt(size));\n\t\tmyCircle.setCenter(mapLocation);\n\t\tif(myCircle.getMap() == null) myCircle.setMap(myMap);\n\t} else {\n\t\tmyCircle = new google.maps.Circle({\n\t\t\tcenter : mapLocation,\n\t\t\tclickable : false,\n\t\t\tmap: myMap,\n\t\t\tstrokeOpacity: 0.8,\n\t\t\tstrokeWeight: 1,\n\t\t\tfillOpacity : 0.3,\n\t\t\tfillColor : \"#000000\",\n\t\t\tradius : parseInt(size)\n\t\t});\n\t}\n}", "function drawInterface(ctx, radius) {\n ctx.beginPath();\n ctx.arc(0, 0, radius, 0, 2 * Math.PI);\n ctx.fillStyle = 'white';\n ctx.fill();\n ctx.lineWidth = radius * 0.001;\n ctx.stroke();\n ctx.beginPath();\n ctx.arc(0, 0, radius * 0.025, 0, 2 * Math.PI);\n ctx.fillStyle = '#333';\n ctx.fill();\n}", "function drawCircles() {\n\t\tvar i;\n\t\tvar x;\n\t\tvar y;\n\t\tvar rad;\n\t\tvar color;\n\t\t\n\t\tcontext.fillStyle = bgColor;\n\t\tcontext.fillRect(0,0,canvas.width,canvas.height);\t\t\n\t\t\n\t\tfor (i=0; i < circleCount; i++) {\n\t\t\trad = circles[i].rad;\n\t\t\tx = circles[i].x;\n\t\t\ty = circles[i].y;\n\t\t\tcolor=circles[i].color;\n\t\t\tcontext.beginPath();\n\t\t\tcontext.arc(x, y, rad, 0, 2*Math.PI, false);\n\t\t\tcontext.closePath();\n\t\t\tcontext.fillStyle = color;\n\t\t\tcontext.fill();\n\t\t}\t\t\n\t}", "function drawCircle(ctx, circle) {\n ctx.beginPath();\n ctx.globalAlpha = Math.max(.16 - circle.t * timeAlphaScale, 0);\n ctx.fillStyle = circleColor;\n ctx.arc(circle.x, circle.y, circle.radius, 0, twoPi, false);\n ctx.fill();\n ctx.closePath();\n circle.t++;\n}", "function draw (x,y) {\n ctx.beginPath();\n ctx.arc(x,y,radius,0,2 * Math.PI);\n \n ctx.fill();\n}", "function Circle(x, y, dx, dy, radius) {\n this.x = x;\n this.y = y;\n // Step 4\n this.dx = dx;\n this.dy = dy;\n this.radius = radius;\n // Step 8 Add Color\n this.colors = [\"#16a085\", \"#e74c3c\", \"#34495e\"];\n\n // Step 3 Add Draw Function\n this.draw = function() {\n c.beginPath();\n c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);\n // Step 8 Add Color\n c.strokeStyle = \"blue\";\n // c.strokeStyle = this.colors[Math.floor(Math.random() * 3)];\n c.stroke();\n // c.fillStyle = this.colors[Math.floor(Math.random() * 3)];\n };\n\n // Step 4 Update / Create Animation\n // Add dx, dy, radius\n this.update = function() {\n if (this.x + this.radius > innerWidth || this.x - this.radius < 0) {\n this.dx = -this.dx;\n }\n\n if (this.y + this.radius > innerHeight || this.y - this.radius < 0) {\n this.dy = -this.dy;\n }\n\n this.x += this.dx;\n this.y += this.dy;\n\n // Step 5 add draw\n this.draw();\n };\n}", "_drawCircleFilledOctants( centerX, centerY, x, y, paletteId ) {\n this.drawLine( centerX - x, centerY + y, centerX + x, centerY + y, paletteId );\n this.drawLine( centerX - x, centerY - y, centerX + x, centerY - y, paletteId );\n this.drawLine( centerX - y, centerY + x, centerX + y, centerY + x, paletteId );\n this.drawLine( centerX - y, centerY - x, centerX + y, centerY - x, paletteId );\n }", "function redrawCircle() {\n\n r = 0;\n x = random(100, windowWidth);\n y = random(100, windowHeight);\n fillColor = color(random(0, 255), random(0, 255), random(0, 255));\n currentTime = 0;\n}", "function drawCircle(x,y){\n var c = document.getElementById('board');\n var ctx = c.getContext('2d');\n ctx.beginPath();\n ctx.arc(x,y,CELL_SIZE/5,0,2*Math.PI);\n ctx.strokeStyle = 'red';\n ctx.lineWidth = 4; \n ctx.stroke();\n }", "function drawCircle(context, element) {\n context.strokeStyle = element.strokeStyle;\n context.fillStyle = element.fillStyle;\n context.globalAlpha = 0.5;\n context.beginPath();\n context.arc(element.x, element.y, element.r, 0, 2 * Math.PI);\n context.stroke();\n context.fill();\n }", "function drawRedCircle(context, posX, posY, hex) {\n\tcontext.save();\n\tcontext.beginPath();\n\tcontext.arc(posX, posY, 25, 0, 2*Math.PI, false);\n\tcontext.fillStyle = \"#800033\";\n\tcontext.fill();\n\tcontext.font = \"20px sans-serrif\";\n\tcontext.beginPath();\n\tcontext.fillStyle = \"#ffffff\";\n\tcontext.fillText(hex, posX-15, posY+5);\n\tcontext.fill();\n\tcontext.restore();\n}", "function Circle(x, y, radius, strokeStyle, fillStyle)\r\n{\r\n this.x = x;\r\n this.y = y;\r\n this.radius = radius;\r\n this.strokeStyle = strokeStyle;\r\n this.fillStyle = fillStyle;\r\n \r\n this.draw = function()\r\n {\r\n ctx.beginPath();\r\n ctx.arc(this.x,this.y,this.radius,0,Math.PI * 2);\r\n ctx.strokeStyle = this.strokeStyle;\r\n ctx.stroke();\r\n ctx.fillStyle = this.fillStyle;\r\n ctx.fill();\r\n }\r\n}", "show(){\n fill(255);\n circle(this.x, this.y, this.r);\n }", "function Circle(x, y, dx, dy, radius, color) {\n this.x = x;\n this.y = y;\n this.dx = dx;\n this.dy = dy;\n this.radius = radius;\n this.color = color;\n\n\n this.draw = function(){\n c.beginPath();\n c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);\n c.fillStyle = this.color;\n c.fill();\n c.closePath();\n }\n\n\n//****movement and edges\n this.update = function(){\n if (this.x + this.radius > innerWidth || this.x - this.radius < 0){\n this.dx = -this.dx;\n }\n if (this.y + this.radius > innerHeight || this.y - this.radius < 0){\n this.dy = -this.dy;\n }\n this.x += this.dx;\n this.y += this.dy;\n\n this.draw();\n }\n}" ]
[ "0.85059416", "0.8297965", "0.82682586", "0.8167714", "0.81101", "0.7985849", "0.79795027", "0.7961323", "0.7936154", "0.79239553", "0.78811926", "0.7826837", "0.781301", "0.7810477", "0.77944493", "0.7764531", "0.7756918", "0.77124274", "0.76867104", "0.7683053", "0.7678049", "0.7677342", "0.7669143", "0.7657797", "0.76281", "0.7620003", "0.75762314", "0.7571039", "0.7562773", "0.75603515", "0.7558258", "0.7556864", "0.754912", "0.75418806", "0.7534066", "0.75172585", "0.7516088", "0.7514002", "0.75104725", "0.74963385", "0.74917275", "0.74803185", "0.74642205", "0.7458829", "0.743548", "0.7433741", "0.7432026", "0.7425756", "0.74189466", "0.74148464", "0.7411124", "0.74099517", "0.73893243", "0.7385706", "0.73745584", "0.7368357", "0.7364102", "0.73560774", "0.7342311", "0.73380107", "0.7329725", "0.73273736", "0.73260915", "0.7318067", "0.7317318", "0.73172027", "0.7298673", "0.7280709", "0.72801244", "0.7276484", "0.72704756", "0.725735", "0.7253981", "0.7251923", "0.72474676", "0.72220916", "0.72205305", "0.7214726", "0.72125375", "0.72119254", "0.72092474", "0.7205513", "0.7177138", "0.71717465", "0.7163869", "0.71632767", "0.71613175", "0.7153485", "0.7151887", "0.7150911", "0.71484965", "0.71355206", "0.71215856", "0.7109515", "0.71053815", "0.7100948", "0.70959836", "0.70891505", "0.7085691", "0.7082306" ]
0.7573548
27
move circle and reverse direction if circle collides with border
move () { this.position.x += this.speed.x; this.position.y += this.speed.y; if( this.position.x + this.radius > canvas.width || this.position.x - this.radius < 0 ) this.speed.x *= -1; if( this.position.y + this.radius > canvas.height || this.position.y - this.radius < 0 ) this.speed.y *= -1; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function adjustPosition(circle) {\n if (circle.x + circle.radius + circle.velocityX > cWidth\n || circle.x - circle.radius + circle.velocityX < 0) {\n circle.velocityX = -circle.velocityX;\n }\n\n if (circle.y + circle.radius + circle.velocityY > cHeight\n || circle.y - circle.radius + circle.velocityY < 0) {\n circle.velocityY = -circle.velocityY;\n }\n\n circle.x += circle.velocityX;\n circle.y += circle.velocityY;\n}", "function moveCircle( c ) {\n\n c.x += c.moveX;\n c.y += c.moveY;\n \n \n if (c.x >= canvasWidth - (circleSize/2)){\n c.moveX *= -1; \n }\n \n if (c.y >= canvasHieght - (circleSize/2)){\n writeLoser();\n drawExplosion();\n c.moveX *= 0;\n c.moveY *= 0; \n playing=false;\n \n }\n \n if (c.x <= (circleSize/2)){\n c.moveX *= -1; \n }\n \n if (c.y <= (circleSize/2)){\n c.moveY *= -1;\n }\n\n }", "bonanza() {\n while (!this.collides(0, 1, this.shape)) {\n this.moveDown()\n }\n }", "function direction(currentx,currenty){\n //if circle is getting close to border\n if (currentx >= screenW-50 || currenty >= screenH-50 || currentx <= 50 || currenty <= 50){\n //change direction\n angle -= 180;\n newCoords(angle)\n }\n //console.log(millis())\n if (lastTime <= millis() - 2500){\n angle -= 70;\n newCoords(angle)\n lastTime = millis(); //update last time \n }\n newCoords(angle)\n}", "move (circles) {\n circles.forEach((circle) => {\n if (circle !== this) {\n // detect collision with another circle\n if (calculateDistance(circle, this) <= circle.radius + this.radius) {\n this.changeDirectionX()\n this.changeDirectionY()\n }\n\n // draw the link between circles if in range\n if (calculateDistance(circle, this) <= circle.radius + this.radius + linkDistance) {\n drawLink(this, circle)\n }\n }\n })\n\n if (this.x + this.direction.dirX + this.radius >= width ||\n (this.x + this.direction.dirX) - this.radius <= 0) {\n this.changeDirectionX()\n }\n\n if (this.y + this.direction.dirY + this.radius >= height ||\n (this.y + this.direction.dirY) - this.radius <= 0) {\n this.changeDirectionY()\n }\n\n this.x += this.direction.dirX\n this.y += this.direction.dirY\n\n ctx.lineWidth = 3\n this.render(canvas, ctx)\n ctx.fill()\n }", "function animate() {\n requestAnimationFrame(animate);\n // this is going to allow me to clearing the canvas during the animation\n c.clearRect(0, 0, innerWidth, innerHeight)\n\n c.beginPath();\n c.arc(x, y, radius, 0, Math.PI * 2, false);\n c.strokeStyle = '#f54538';\n c.lineWidth = 10;\n c.stroke();\n\n // if the circle hits left of the screen reverse the action, if the circle hits the right then reverse\n if (x + radius > canvas.width || x - radius < 0) {\n dx = -dx;\n }\n\n // if the circle hits the top of the screen the reverse the action, if circle hits bottom of the screen reverse\n if (y + radius > canvas.height || y - radius < 0) {\n dy = -dy;\n }\n\n x += dx; //this is the velocity going from left to right\n y += dy;\n}", "function moveCircle(x, y) {\n\t\n\t// select corresponding rover circle // see filter or direct selection https://d3indepth.com/selections/ && https://stackoverflow.com/questions/20414980/d3-select-by-attribute-value\n\tvar selectedCircle = d3.select( \"#vehicule\" + currentVehicule._id ); \n\tselectedCircle.transition()\n\t\t.duration(250)\n\t\t.attr(\"cx\", x * r)\n\t\t.attr(\"cy\", y * r)\n\t\t.ease(\"easebounce\");\n\n\t// move related text\n\tvar selectedText = d3.select( \"#label\" + currentVehicule._id ); \n\tselectedText.transition()\n\t\t.duration(250)\n\t\t.attr(\"x\", x * r - r) \n\t\t.attr(\"y\", y * r + r + 10)\n\t\t.ease(\"easebounce\");\n\t\t\n\t// check if rover position equals an obstacle on each move \n\t// TODO add zone area sensitivity to handle bigger obstacles\n\tobstacles.forEach(function (element) {\n\t\tif ((x == (element.x / r)) && (y == (element.y / r))) {\n\n\t\t\tvar destroyedCircle = d3.select( \"#vehicule\" + currentVehicule._id );\n\t\t\tvar destroyedText = d3.select( \"#label\" + currentVehicule._id );\n\n\t\t\t// remove and disable circle and vehicule\n\t\t\tdestroyedCircle.remove();\n\t\t\tdestroyedText.remove();\n\t\t\tdestroyVehicule();\n\n\t\t}\n\t});\n}", "function circleCollide(x1, y1, r1, x2, y2, r2) {\r\n var dx = x1 - x2;\r\n var dy = y1 - y2;\r\n return ((dx * dx + dy * dy) < (r1 + r2)*(r1+r2)); \r\n }", "move() {\n if (this._y - Ball_Radius <= 0) {\n this._reverseY();\n } else if (this._x - Ball_Radius <= 0 || this._x + Ball_Radius >= Scene_Width) {\n this._reverseX();\n }\n this._x = this._x + this._dx;\n this._y = this._y + this._dy;\n }", "_updatePosition() {\n // Check walls\n if (this.x + this.curRadius > this.canvas.width || this.x - this.curRadius < 0) {\n // Switch directions\n this.dx = -this.dx;\n }\n if (this.y + this.curRadius > this.canvas.height || this.y - this.curRadius < 0) {\n this.dy = -this.dy;\n }\n\n this.x += this.dx;\n this.y += this.dy;\n }", "move(){\n console.log('circle move')\n }", "function shapeShift(){\n if(myCenter.shape === rect){\n myCenter.shape = ellipse;\n for(var i=0; i<myDots.length; i++){\n myDots[i].shape = ellipse;\n }\n }\n else{\n myCenter.shape = rect;\n for(var i=0; i<myDots.length; i++){\n myDots[i].shape = rect;\n }\n }\n}", "function move() {\r\n let circles = document.querySelectorAll(\".circle\");\r\n let index = -1;\r\n if (circles.length && move_flag) {\r\n let div_height = document.querySelector(\"#container\").clientHeight;\r\n let div_width = document.querySelector('#container').clientWidth;\r\n circles.forEach(circle => {\r\n index = ball_list.findIndex(ball => ball.get_id === circle.id);\r\n ball_list[index].calcUpdate(div_width, div_height);\r\n circle.style.left = ball_list[index].update.x.toString() + \"px\";\r\n circle.style.top = ball_list[index].update.y.toString() + \"px\";\r\n }); \r\n }\r\n}", "function upBorderCollision(x, y, r, canvasHeight, bottomJaw, topJaw, ctx, colour)\n{\n //If pacmans x co-ordinate plus radius equals 0 (top)\n if((y - r) <= 0)\n {\n //just draw pacman and return y, dont de-increment it\n ctx.beginPath();\n ctx.arc(x, y, r, bottomJaw * Math.PI, 0.75 * Math.PI);\n ctx.fillStyle = colour;\n ctx.fill();\n ctx.beginPath();\n ctx.arc(x, y, r, 0.25 * Math.PI, topJaw * Math.PI);\n ctx.fill();\n ctx.beginPath();\n return y;\n }\n else//otherwise\n {\n //draw pacman, de-increment y, and return it.\n ctx.beginPath();\n ctx.arc(x, y, r, bottomJaw * Math.PI, 0.75 * Math.PI);\n ctx.fillStyle = colour;\n ctx.fill();\n ctx.beginPath();\n ctx.arc(x, y, r, 0.25 * Math.PI, topJaw * Math.PI);\n ctx.fill();\n ctx.beginPath();\n y -= 7;\n return y;\n }\n}", "function moveCircles() {\n circlesArray.forEach(function(element){\n element.ballObject.style.left = element.positionX + 'px';\n element.ballObject.style.top = element.positionY + 'px';\n if(element.positionX < Xmax && element.flagX) {\n element.positionX = element.positionX + element.velocityX;\n if(element.positionX >= Xmax){\n element.flagX = false;\n colorRandom(element.ballObject);\n }\n }\n else {\n element.positionX = element.positionX - element.velocityX;\n if(element.positionX <= Xmin) {\n element.flagX = true;\n colorRandom(element.ballObject);\n }\n }\n \n if(element.positionY < Ymax && element.flagY) {\n element.positionY = element.positionY + element.velocityY;\n if(element.positionY >= Ymax){\n element.flagY = false;\n colorRandom(element.ballObject);\n }\n }\n else {\n element.positionY = element.positionY - element.velocityY;\n if(element.positionY <= Ymin) {\n element.flagY = true;\n colorRandom(element.ballObject);\n }\n }\n }\n );\n}", "function Circle(color, radius,x,y, velo, width, height){\n Board.call(this)\n this.x = x ? x : 50;\n this.y = y ? y : 150;\n this.width = width ? width : 0;\n this.height = height ? height : 0;\n this.radius = radius ? radius : 1;\n this.color = color ? color : \"green\";\n this.isMoving = true;\n this.toUp = false;\n this.toLeft = false;\n //this.velo = velo ? velo : 3;\n \n this.getDistance = function(circle){\n var xD = this.x-circle.x;\n var yD = this.y-circle.y;\n return Math.sqrt(Math.pow(xD,2) + Math.pow(yD,2));\n \n \n }\n //funcion de toque\n this.isTouching = function(circle){\n return this.getDistance(circle) < this.radius + circle.radius;\n }\n \n //suma movimiento a los circulos\n this.move = function(){\n if(!this.isMoving) return;\n var rX = this.x + this.radius;\n var rY = this.y + this.radius;\n //arriba y abajo\n if(this.toUp){\n this.y-=velo ? velo : vel;\n }else{\n this.y+=velo ? velo : vel;\n }\n //izq derecha\n if(this.toLeft){\n this.x-=velo ? velo: vel;\n }else{\n this.x+=velo ? velo : vel;\n }\n \n //techo y pis\n if(rY > canvas.height){\n this.toUp = true;\n this.color = \"yellow\";\n \n //circles.pop(circle)\n\n }else if(rY < 0 + this.radius * 2 ){\n this.toUp = false;\n //circle2.color = \"yellow\";\n }\n\n \n\n\n\n //paredes\n if(rX > canvas.width){\n this.toLeft = true;\n }else if(rX < 0 + this.radius * 2){\n this.toLeft = false;\n }\n }\n \n//\n this.draw = function(){\n this.move();\n ctx.beginPath();\n ctx.arc(this.x,this.y,this.radius,0,Math.PI*2);\n //ctx.fillStyle = this.color;\n ctx.stroke();\n //ctx.fill();\n ctx.closePath();\n }\n}", "function Circle(x, y, dx, dy, radius) {\n this.x = x;\n this.y = y;\n this.dx = dx;\n this.dy = dy;\n this.radius = radius;\n \n // FUNCTION FOR DRAWING NEW CIRCLE\n this.draw = function() {\n context.beginPath();\n context.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);\n context.fillStyle = circleBodyColor;\n context.strokeStyle = circleLineColor;\n context.stroke();\n context.fill();\n }\n\n // FUNCTION WITH LOGIC FOR MOVEMENT OF THE CIRCLES\n this.update = function() {\n // MOVING CIRCLES LEFT AND RIGHT\n if (this.x + this.radius + 1 > innerWidth || this.x - this.radius < 0 ) {\n this.dx = -this.dx;\n }\n\n // MOVING CIRCLE UP AND DOWN\n if (this.y + this.radius + 1 > innerHeight || this.y - this.radius < 0) {\n this.dy = -this.dy;\n }\n this.x += this.dx;\n this.y += this.dy;\n \n // AFTER MOVEMENT IS UPDATED, DRAW EVERYTHING AGAIN\n this.draw();\n }\n}", "function onFrame(event) {\n\t//console.log(circle.position.x);\n\n\t// if the circle's x coordinate is less than 300 than move \n\t// to the right \n\tif(circle.position.x < 300) {\n\t\tcircle.position.x += circle.bounds.width / 20;\n\t\t\t\n\t}\n\t// otherwise \n\telse if (circle.position.y < 500) {\n\t\tcircle.position.y += circle.bounds.height / 20;\n\t} \n\t\n\n\tpath.rotate(1.5);\n\t\n\t\n}", "function circleMove() {\n //moving \n charY = charY + charSpeed; // speed= dY / dX\n charSpeed = charSpeed + charGravity; //simulating effect of acceleration due to gravity, gravity= d2Y / dX2\n if (charY > 440) {\n charSpeed = charSpeed * -0.80; //simulates bounce, flip operation of charSpeed. 0.8 instead of 1 to simulate dampening effect of bounce\n }\n}", "function moveRight() {\n removeShape();\n currentShape.x++;\n if (collides(grid, currentShape)) {\n currentShape.x--;\n }\n applyShape();\n}", "function animate() {\n requestAnimationFrame(animate);\n c.clearRect(0, 0, innerWidth, innerHeight);\n\n circle.update();\n circle1.update();\n circle3.update();\n\n // c.beginPath(); \n // c.arc(x, y, radius, 0, 2 * Math.PI, false);\n // c.fill();\n // c.strokeStyle = randomHue;\n // c.stroke();\n\n if (x + radius > innerWidth || x - radius < 0) {\n dx = -dx;\n }\n if (y + radius > innerHeight || y - radius < 0) {\n dy = -dy;\n }\n x += dx;\n y += dy;\n}", "collideWithWall(){\n this.x -= this.prevX;\n this.y -= this.prevY;\n }", "function Circle(x, y, dx, dy, radius, color) {\n this.x = x;\n this.y = y;\n this.dx = dx;\n this.dy = dy;\n this.radius = radius;\n this.color = color;\n\n\n this.draw = function(){\n c.beginPath();\n c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);\n c.fillStyle = this.color;\n c.fill();\n c.closePath();\n }\n\n\n//****movement and edges\n this.update = function(){\n if (this.x + this.radius > innerWidth || this.x - this.radius < 0){\n this.dx = -this.dx;\n }\n if (this.y + this.radius > innerHeight || this.y - this.radius < 0){\n this.dy = -this.dy;\n }\n this.x += this.dx;\n this.y += this.dy;\n\n this.draw();\n }\n}", "function moveObject(direction : Vector2, layerMask : LayerMask, objectTransform : Transform, circleRadius : float, speed : float)\n\t{\n\t\tif(direction == Vector2.zero)\n\t\t\treturn;\n\t\tvar walkTo : Vector2 = direction * Time.deltaTime * speed;\t\n\t\tfacingDirection = animationManager.updateWalkAnimation(walkTo.normalized);\n\t\t//casts a circleCast with radius of the furthest away Y point. \n\t\t//We also apply a position offset in the circle to make it so that it detects more to the top than to the bottom\n\t\tvar pos : Vector3 = objectTransform.position;\n\t\tpos.y += 0.1;\n\t\t\n\t\tvar rayHit : RaycastHit2D = Physics2D.CircleCast(pos,circleRadius,direction,2,layerMask);\n\t\tif(rayHit.collider != null)\n\t\t{\n\t\t\tif(rayHit.distance > walkTo.magnitude)\n\t\t\t\tobjectTransform.Translate(walkTo);\t\n\t\t\telse\n\t\t\t{\t\t\t\n\t\t\t\t//changes direction if we're in a dead end and checks if we can move in that new direction\n\t\t\t\tdirection = (rayHit.normal+direction).normalized;\t\n\t\t\t\trayHit = Physics2D.CircleCast(pos,circleRadius,direction,2,layerMask);\n\t\t\t\twalkTo = direction*Time.deltaTime*speed;\n\t\t\t\tif(rayHit.collider == null)\n\t\t\t\t{\n\t\t\t\t\tobjectTransform.Translate(walkTo);\n\t\t\t\t\treturn 0; // return 0 for knockback, only place that needs to know\n\t\t\t\t}\n\t\t\t\telse if(rayHit.distance > walkTo.magnitude)\t\t\t\t\n\t\t\t\t\tobjectTransform.Translate(walkTo);\t\t\t\n\t\t\t\telse\t\t\t\t\n\t\t\t\t\tobjectTransform.Translate(rayHit.normal*Time.deltaTime*0.3);\n\t\t\t\t\t//this still needs to exist because by using Translate to move our object, sometimes it will move inside a collider and would be locked without this\n\t\t\t}\t\t\n\t\t}\n\t\telse\n\t\t\tobjectTransform.Translate(walkTo);\n\t\treturn 1;\n\t}", "function doCollide(obj1, obj2) {\n \n obj1.leftX = obj1.X;\n obj1.topY = obj1.Y;\n obj1.rightX = obj1.X + 50;\n obj1.bottomY = obj1.Y + 200;\n \n obj2.leftX = obj2.X;\n obj2.topY = obj2.Y;\n obj2.rightX = obj2.X + 30;\n obj2.bottomY = obj2.Y + 30;\n \n\tif (obj1.rightX > obj2.leftX &&\n obj1.leftX < obj2.rightX &&\n obj1.bottomY > obj2.topY &&\n obj1.topY < obj2.bottomY) {\n \n obj2.speedX = -obj2.speedX;\n \n }\n\t\t\n}", "movingCircleCollision(c1, c2, global = false) {\n //Add collision properties\n if (!c1._bumpPropertiesAdded)\n this.addCollisionProperties(c1);\n if (!c2._bumpPropertiesAdded)\n this.addCollisionProperties(c2);\n let combinedRadii, overlap, xSide, ySide, \n //`s` refers to the distance vector between the circles\n s = {\n vx: undefined,\n vy: undefined,\n lx: undefined,\n ly: undefined,\n magnitude: undefined,\n dx: undefined,\n dy: undefined,\n vxHalf: undefined,\n vyHalf: undefined\n }, p1A = { x: undefined, y: undefined }, p1B = { x: undefined, y: undefined }, p2A = { x: undefined, y: undefined }, p2B = { x: undefined, y: undefined }, hit = false;\n //Apply mass, if the circles have mass properties\n c1.mass = c1.mass || 1;\n c2.mass = c2.mass || 1;\n //Calculate the vector between the circles’ center points\n if (global) {\n //Use global coordinates\n s.vx = (c2.gx + c2.radius - c2.xAnchorOffset) - (c1.gx + c1.radius - c1.xAnchorOffset);\n s.vy = (c2.gy + c2.radius - c2.yAnchorOffset) - (c1.gy + c1.radius - c1.yAnchorOffset);\n }\n else {\n //Use local coordinates\n s.vx = (c2.x + c2.radius - c2.xAnchorOffset) - (c1.x + c1.radius - c1.xAnchorOffset);\n s.vy = (c2.y + c2.radius - c2.yAnchorOffset) - (c1.y + c1.radius - c1.yAnchorOffset);\n }\n //Find the distance between the circles by calculating\n //the vector's magnitude (how long the vector is)\n s.magnitude = Math.sqrt(s.vx * s.vx + s.vy * s.vy);\n //Add together the circles' combined half-widths\n combinedRadii = c1.radius + c2.radius;\n //Figure out if there's a collision\n if (s.magnitude < combinedRadii) {\n //Yes, a collision is happening\n hit = true;\n //Find the amount of overlap between the circles\n overlap = combinedRadii - s.magnitude;\n //Add some \"quantum padding\" to the overlap\n overlap += 0.3;\n //Normalize the vector.\n //These numbers tell us the direction of the collision\n s.dx = s.vx / s.magnitude;\n s.dy = s.vy / s.magnitude;\n //Find the collision vector.\n //Divide it in half to share between the circles, and make it absolute\n s.vxHalf = Math.abs(s.dx * overlap / 2);\n s.vyHalf = Math.abs(s.dy * overlap / 2);\n //Find the side that the collision is occurring on\n (c1.x > c2.x) ? xSide = 1 : xSide = -1;\n (c1.y > c2.y) ? ySide = 1 : ySide = -1;\n //Move c1 out of the collision by multiplying\n //the overlap with the normalized vector and adding it to\n //the circles' positions\n c1.x = c1.x + (s.vxHalf * xSide);\n c1.y = c1.y + (s.vyHalf * ySide);\n //Move c2 out of the collision\n c2.x = c2.x + (s.vxHalf * -xSide);\n c2.y = c2.y + (s.vyHalf * -ySide);\n //1. Calculate the collision surface's properties\n //Find the surface vector's left normal\n s.lx = s.vy;\n s.ly = -s.vx;\n //2. Bounce c1 off the surface (s)\n //Find the dot product between c1 and the surface\n let dp1 = c1.vx * s.dx + c1.vy * s.dy;\n //Project c1's velocity onto the collision surface\n p1A.x = dp1 * s.dx;\n p1A.y = dp1 * s.dy;\n //Find the dot product of c1 and the surface's left normal (s.lx and s.ly)\n let dp2 = c1.vx * (s.lx / s.magnitude) + c1.vy * (s.ly / s.magnitude);\n //Project the c1's velocity onto the surface's left normal\n p1B.x = dp2 * (s.lx / s.magnitude);\n p1B.y = dp2 * (s.ly / s.magnitude);\n //3. Bounce c2 off the surface (s)\n //Find the dot product between c2 and the surface\n let dp3 = c2.vx * s.dx + c2.vy * s.dy;\n //Project c2's velocity onto the collision surface\n p2A.x = dp3 * s.dx;\n p2A.y = dp3 * s.dy;\n //Find the dot product of c2 and the surface's left normal (s.lx and s.ly)\n let dp4 = c2.vx * (s.lx / s.magnitude) + c2.vy * (s.ly / s.magnitude);\n //Project c2's velocity onto the surface's left normal\n p2B.x = dp4 * (s.lx / s.magnitude);\n p2B.y = dp4 * (s.ly / s.magnitude);\n //4. Calculate the bounce vectors\n //Bounce c1\n //using p1B and p2A\n c1.bounce = {};\n c1.bounce.x = p1B.x + p2A.x;\n c1.bounce.y = p1B.y + p2A.y;\n //Bounce c2\n //using p1A and p2B\n c2.bounce = {};\n c2.bounce.x = p1A.x + p2B.x;\n c2.bounce.y = p1A.y + p2B.y;\n //Add the bounce vector to the circles' velocity\n //and add mass if the circle has a mass property\n c1.vx = c1.bounce.x / c1.mass;\n c1.vy = c1.bounce.y / c1.mass;\n c2.vx = c2.bounce.x / c2.mass;\n c2.vy = c2.bounce.y / c2.mass;\n }\n return hit;\n }", "boxCollision() {\r\n if ((this.x - this.radius) <= 0)\r\n this.x = 0 + this.radius;\r\n if ((this.x + this.radius) >= canvas.src.width)\r\n this.x = canvas.src.width - this.radius;\r\n if ((this.y - this.radius) <= 0)\r\n this.y = this.radius;\r\n if ((this.y + this.radius) >= canvas.src.height)\r\n this.y = canvas.src.height - this.radius;\r\n }", "function draw() {\n clear();\n circle(x, y, 10);\n \n//if x + dx is greater than width or x + dx is less than 0, then x=-dx which means the ball is moving in a negtive width direction, left\n if (x + dx > WIDTH || x + dx < 0)\n dx = -dx;\n//if y + dy is greather than height or y + dy is less than zero then the ball is moving in a negative height direction causing the bounce\n if (y + dy > HEIGHT || y + dy < 0)\n dy = -dy;\n \n x += dx;\n y += dy;\n}", "function draw() {\n background(0);\n\n move(); /// moves the circle\n wrap(); /// wraps the cicle (makes it start at the beginning of the screen)\n display(); //displays the circle\n\n}", "function createCircularMovement(radius, toX, toY, overMS) {\n\treturn (entity) => {\n\t\tlet fromX = entity.handle.x;\n\t\tlet fromY = entity.handle.y;\n\t\tlet startTime = getTimeNow();\n\t\tlet event = (entity) => {\n\t\t\tlet diff = getTimeNow() - startTime;\n\t\t\tlet theta = 2 * Math.PI * (diff / overMS);\n\t\t\tif (diff >= overMS) {\n\t\t\t\tentity.handle.x = toX + radius * Math.cos(theta);\n\t\t\t\tentity.handle.y = toY + radius * Math.sin(theta);\n\t\t\t\treturn REMOVE_EVENT;\n\t\t\t}\n\t\t\tentity.handle.x = fromX + radius * Math.cos(theta) + toX * (diff / overMS);\n\t\t\tentity.handle.y = fromY + radius * Math.sin(theta) + toY * (diff / overMS);\n\t\t\treturn 10;\n\t\t}\n\t\tentity.mutateEvent(event);\n\t\treturn event(entity);\n\t}\n}", "moveRight() {\n if (!this.collides(1, 0, this.shape)) this.pos.x++\n }", "function moveCircleRight (){\n\nxpos = xpos + 30;\n\n}", "wallCollision() {\n const hitLeft = this.x - this.radius <= 0;\n const hitRight = this.x + this.radius >= this.boardWidth;\n const hitTop = this.y - this.radius <= 0;\n const hitBottom = this.y + this.radius >= this.boardHeight;\n\n if (hitLeft || hitRight) {\n this.vx = -this.vx;\n \n } else if (hitTop || hitBottom) {\n this.vy = -this.vy;\n \n }\n\n }", "function Circle(x, y, dx, dy, radius, pulse, dpulse, colorBorder, colorFill){\n this.x = x;\n this.y = y;\n this.dx = dx;\n this.dy = dy;\n this.originalDX = dx;\n this.originalDY = dy;\n this.colorBorder = colorBorder;\n this.colorFill = colorFill;\n this.opacity = Math.random();\n this.radius = radius;\n this.pulseRadius = radius;\n this.minPulseRadius = 2;\n this.pulse = pulse;\n this.dpulse = dpulse;\n this.accelUp = .2;\n this.accelDown = 0.02;\n this.touched = false;\n\n this.updateSpace = function(){\n // reverse velocity when the circles radius hits the edge of the screen\n if (this.x + this.radius > innerWidth || this.x - this.radius < 0){\n this.dx = -this.dx;\n }\n \n if(this.y + this.radius > innerHeight || this.y - this.radius < 0){\n this.dy = -this.dy;\n }\n\n // define new position variables\n this.x += this.dx;\n this.y += this.dy;\n\n // interactions\n if (mouse.x - this.x < 30 && mouse.x - this.x > -30\n && mouse.y - this.y < 30 && mouse.y - this.y > -30) {\n this.touched = true;\n this.dx += Math.sign(this.dx) * this.accelUp;\n this.dy += Math.sign(this.dy) * this.accelUp;\n }\n else if(this.touched == true && Math.abs(this.dx) > Math.abs(this.originalDX)){\n this.dx -= Math.sign(this.dx) * this.accelUp;\n }\n else if(this.touched == true && Math.abs(this.dy) > Math.abs(this.originalDY)){\n this.dy -= Math.sign(this.dy) * this.accelUp\n }\n else if(Math.abs(this.dx) < Math.abs(this.originalDX) + this.accelUp || Math.abs(this.dx) > Math.abs(this.originalDX) - this.accelUp){\n this.touched = false;\n }\n\n \n this.updateRadius();\n this.draw();\n };\n\n this.updateRadius = function(){\n // reverse pulse velocity when it gets too big or too small\n if (this.pulseRadius > this.radius + this.pulse || this.pulseRadius < this.radius - this.pulse || this.pulseRadius < this.minPulseRadius){\n this.dpulse = -this.dpulse;\n }\n\n // define new radius\n this.pulseRadius += this.dpulse; \n };\n\n this.draw = function(){\n c.beginPath();\n c.arc(this.x, this.y, this.pulseRadius, 0, Math.PI * 2, false);\n c.strokeStyle = this.colorBorder;\n c.fillStyle = this.colorFill\n c.globalAlpha = this.opacity;\n c.fill();\n c.stroke();\n };\n}", "function downBorderCollision(x, y, r, canvasHeight, bottomJaw, topJaw, ctx, colour)\n{\n //If pacmans x co-ordinate plus radius equals the height (bottom)\n if((y + r) >= canvasHeight)\n {\n //just draw pacman and return y, dont increment it\n ctx.beginPath();\n ctx.arc(x, y, r, 1.25 * Math.PI, bottomJaw * Math.PI);\n ctx.fillStyle = colour;\n ctx.fill();\n ctx.beginPath();\n ctx.arc(x, y, r, topJaw * Math.PI, 1.75 * Math.PI);\n ctx.fill();\n ctx.beginPath();\n return y;\n }\n else//otherwise\n {\n //draw pacman, increment y, and return it.\n ctx.beginPath();\n ctx.arc(x, y, r, 1.25 * Math.PI, bottomJaw * Math.PI);\n ctx.fillStyle = colour;\n ctx.fill();\n ctx.beginPath();\n ctx.arc(x, y, r, topJaw * Math.PI, 1.75 * Math.PI);\n ctx.fill();\n ctx.beginPath();\n y += 7;\n return y;\n }\n}", "function detectCollisionForCircles(obj1,obj2){\n\t\n\tvar xmov1 = obj1.move_x;\n\tvar ymov1 = obj1.move_z;\n\tvar xmov2 = obj2.move_x;\n\tvar ymov2 = obj2.move_z;\n\t\n\tvar xl1=obj1.position.x;\n var yl1=obj1.position.z;\n\tvar xl2=obj2.position.x;\n\tvar yl2=obj2.position.z;\n\tvar R = obj1.radius + obj2.radius;\n\tvar a =-2*xmov1*xmov2+xmov1*xmov1+xmov2*xmov2;\n\tvar b =-2*xl1*xmov2-2*xl2*xmov1+2*xl1*xmov1+2*xl2*xmov2;\n\tvar c =-2*xl1*xl2+xl1*xl1+xl2*xl2;\n\tvar d =-2*ymov1*ymov2+ymov1*ymov1+ymov2*ymov2;\n\tvar e =-2*yl1*ymov2-2*yl2*ymov1+2*yl1*ymov1+2*yl2*ymov2;\n\tvar f =-2*yl1*yl2+yl1*yl1+yl2*yl2;\n\tvar g =a+d;\n\tvar h =b+e;\n\tvar k =c+f-R*R;\n\t\t\t\n\tvar sqRoot =Math.sqrt(h*h-4*g*k);\n\tvar t1 =(-h+sqRoot)/(2*g);\n\tvar t2 =(-h-sqRoot)/(2*g);\n\t\n\t /* if (t1>0 &&t1<=1){\n\t\t var whatTime =t1;\n\t\t\tvar ballsCollided =true;\n\t\t\talert(\"t1=\"+whatTime);\n\t } */\n\t\tif (t2>0 &&t2<=1){\n\t\t if (whatTime ==0 ||t2<t1){\n \t\tvar\twhatTime =t2;\n\t\t\t\tvar\tballsCollided =true;\n\t\t }\n\t\t}\n\t\tif (ballsCollided){\n\t\t\t\n\t\t\tball2BallReaction(obj1,obj2,xl1,xl2,yl1,yl2,whatTime)\n\t\t\t\tballsCollided=false;\n\t\t\t\twhatTime=0;\n\t\t\t}\n\t\t\t\t\n}", "function moveShape(x, y) {\r\n\tvar shape = previousSelectedShape;\r\n\tif (shape instanceof Circle || shape instanceof Rectangle) {\r\n\t\tshape.x1 = x - offsetX;\r\n\t\tshape.y1 = y - offsetY;\r\n\t} else {\r\n\t\tvar diffX = shape.x2 - shape.x1;\r\n\t\tvar diffY = shape.y2 - shape.y1;\r\n\t\tshape.x1 = x - offsetX;\r\n\t\tshape.y1 = y - offsetY;\r\n\t\tshape.x2 = shape.x1 + diffX;\r\n\t\tshape.y2 = shape.y1 + diffY;\r\n\t}\r\n\tdrawShapes();\t\t\r\n}", "function anotherDetectCollisionForCircles(obj1,obj2){\nvar distX=obj1.position.x-obj2.position.x;\nvar distZ=obj1.position.z-obj2.position.z;\nvar distance=Math.sqrt(distX*distX+distZ*distZ);\nvar rad = obj1.radius+obj2.radius;\nif(distance<rad){\n\tball2BallReaction(obj1,obj2,obj1.position.x,\n\t\t\tobj2.position.x,obj1.position.z,\n\t\t\tobj2.position.z);\n\t\t}\n}", "calculateCircleEdgePoint(currPosition, prevPosition, r, r_diff) {\n r = r + r_diff\n var a = (prevPosition.y - currPosition.y) / (prevPosition.x - currPosition.x);\n\n var x_diff = Math.sqrt((r * r) / (1 + a * a));\n var y_diff = Math.sqrt((a * a * r * r) / (1 + a * a));\n\n if (currPosition.x < prevPosition.x && currPosition.y < prevPosition.y) {\n return {\n new_x: -Math.sqrt((r * r) / (1 + a * a)),\n new_y: -Math.sqrt((a * a * r * r) / (1 + a * a))\n }\n } else if (currPosition.x < prevPosition.x && currPosition.y > prevPosition.y) {\n return {\n new_x: -Math.sqrt((r * r) / (1 + a * a)),\n new_y: Math.sqrt((a * a * r * r) / (1 + a * a))\n }\n }\n if (currPosition.x > prevPosition.x && currPosition.y < prevPosition.y) {\n return {\n new_x: Math.sqrt((r * r) / (1 + a * a)),\n new_y: -Math.sqrt((a * a * r * r) / (1 + a * a))\n }\n } else if (currPosition.x > prevPosition.x && currPosition.y > prevPosition.y) {\n return {\n new_x: Math.sqrt((r * r) / (1 + a * a)),\n new_y: Math.sqrt((a * a * r * r) / (1 + a * a))\n }\n } else if (currPosition.x == prevPosition.x && currPosition.y < prevPosition.y) {\n return {\n new_x: 0,\n new_y: -r\n }\n } else if (currPosition.x == prevPosition.x && currPosition.y > prevPosition.y) {\n return {\n new_x: 0,\n new_y: r\n }\n } else if (currPosition.x < prevPosition.x && currPosition.y == prevPosition.y) {\n return {\n new_x: -r,\n new_y: 0\n }\n } else if (currPosition.x > prevPosition.x && currPosition.y == prevPosition.y) {\n return {\n new_x: r,\n new_y: 0\n }\n }\n\n\n return {\n new_x: 0,\n new_y: 0\n }\n\n }", "function circlesColliding(ball1, ball2, dt)\n{\n\t//compare the distance to combined radii\n\tvar dx = ball2.pos.x - ball1.pos.x;\n\tvar dy = ball2.pos.y - ball1.pos.y;\n\tvar radii = ball1.rad + ball2.rad;\n\n\tif ((dx * dx) + (dy * dy) <= radii * radii) {\n\n\t\tvar distance = Math.sqrt(((ball1.pos.x - ball2.pos.x)*(ball1.pos.x - ball2.pos.x)) + \n\t\t\t\t\t\t\t\t((ball1.pos.y - ball2.pos.y)*(ball1.pos.y - ball2.pos.y)));\n\n\t\tvar overLap = 0.5 * (distance - ball1.rad - ball2.rad);\n\t\tball1.pos.x -= (overLap * (ball1.pos.x - ball2.pos.x) / distance);\n\t\tball1.pos.y -= (overLap * (ball1.pos.y - ball2.pos.y) / distance);\n\n\t\tball2.pos.x += (overLap * (ball1.pos.x - ball2.pos.x) / distance);\n\t\tball2.pos.y += (overLap * (ball1.pos.y - ball2.pos.y) / distance);\n\n\t\t\n\t\t// dynamic collision\n\t\tdistance = Math.sqrt(((ball1.pos.x - ball2.pos.x)*(ball1.pos.x - ball2.pos.x)) + \n\t\t\t\t\t\t\t\t((ball1.pos.y - ball2.pos.y)*(ball1.pos.y - ball2.pos.y)));\n\n\t\tvar nx = (ball1.pos.x - ball2.pos.x) / distance;\n\t\tvar ny = (ball1.pos.y - ball2.pos.y) / distance;\n\n\t\tvar tx = -ny;\n\t\tvar ty = nx;\n\n\t\tvar tan1 = ball1.vel.x * tx + ball1.vel.y * ty;\n\t\tvar tan2 = ball2.vel.x * tx + ball2.vel.y * ty;\n\n\t\tvar dpNorm1 = ball1.vel.x * nx + ball1.vel.y * ny;\n\t\tvar dpNorm2 = ball2.vel.x * nx + ball2.vel.y * ny;\n\n\n\t\tvar m1 = (dpNorm1 * (ball1.mass - ball2.mass) + 2 * ball2.mass * dpNorm2)/ (ball1.mass + ball2.mass);\n\t\tvar m2 = (dpNorm2 * (ball2.mass - ball1.mass) + 2 * ball1.mass * dpNorm1)/ (ball1.mass + ball2.mass);\n\n\n\t\tball1.vel.x = tx * tan1 + nx * m1;\n\t\tball1.vel.y = ty * tan1 + ny * m1;\n\t\tball2.vel.x = tx * tan2 + nx * m2;\n\t\tball2.vel.y = ty * tan2 + ny * m2;\n\n\t}\n}", "function CollideEdgeCircle(manifold, edgeA, xfA, circleB, xfB) {\n manifold.pointCount = 0;\n // Compute circle in frame of edge\n var Q = Transform.mulT(xfA, Transform.mul(xfB, circleB.m_p));\n var A = edgeA.m_vertex1;\n var B = edgeA.m_vertex2;\n var e = Vec2.sub(B, A);\n // Barycentric coordinates\n var u = Vec2.dot(e, Vec2.sub(B, Q));\n var v = Vec2.dot(e, Vec2.sub(Q, A));\n var radius = edgeA.m_radius + circleB.m_radius;\n // Region A\n if (v <= 0) {\n var P = Vec2.clone(A);\n var d = Vec2.sub(Q, P);\n var dd = Vec2.dot(d, d);\n if (dd > radius * radius) {\n return;\n }\n // Is there an edge connected to A?\n if (edgeA.m_hasVertex0) {\n var A1 = edgeA.m_vertex0;\n var B1 = A;\n var e1 = Vec2.sub(B1, A1);\n var u1 = Vec2.dot(e1, Vec2.sub(B1, Q));\n // Is the circle in Region AB of the previous edge?\n if (u1 > 0) {\n return;\n }\n }\n manifold.type = Manifold.e_circles;\n manifold.localNormal.setZero();\n manifold.localPoint.set(P);\n manifold.pointCount = 1;\n manifold.points[0].localPoint.set(circleB.m_p);\n manifold.points[0].id.key = 0;\n manifold.points[0].id.cf.indexA = 0;\n manifold.points[0].id.cf.typeA = Manifold.e_vertex;\n manifold.points[0].id.cf.indexB = 0;\n manifold.points[0].id.cf.typeB = Manifold.e_vertex;\n return;\n }\n // Region B\n if (u <= 0) {\n var P = Vec2.clone(B);\n var d = Vec2.sub(Q, P);\n var dd = Vec2.dot(d, d);\n if (dd > radius * radius) {\n return;\n }\n // Is there an edge connected to B?\n if (edgeA.m_hasVertex3) {\n var B2 = edgeA.m_vertex3;\n var A2 = B;\n var e2 = Vec2.sub(B2, A2);\n var v2 = Vec2.dot(e2, Vec2.sub(Q, A2));\n // Is the circle in Region AB of the next edge?\n if (v2 > 0) {\n return;\n }\n }\n manifold.type = Manifold.e_circles;\n manifold.localNormal.setZero();\n manifold.localPoint.set(P);\n manifold.pointCount = 1;\n manifold.points[0].localPoint.set(circleB.m_p);\n manifold.points[0].id.key = 0;\n manifold.points[0].id.cf.indexA = 1;\n manifold.points[0].id.cf.typeA = Manifold.e_vertex;\n manifold.points[0].id.cf.indexB = 0;\n manifold.points[0].id.cf.typeB = Manifold.e_vertex;\n return;\n }\n // Region AB\n var den = Vec2.dot(e, e);\n ASSERT && common.assert(den > 0);\n var P = Vec2.wAdd(u / den, A, v / den, B);\n var d = Vec2.sub(Q, P);\n var dd = Vec2.dot(d, d);\n if (dd > radius * radius) {\n return;\n }\n var n = Vec2.neo(-e.y, e.x);\n if (Vec2.dot(n, Vec2.sub(Q, A)) < 0) {\n n.set(-n.x, -n.y);\n }\n n.normalize();\n manifold.type = Manifold.e_faceA;\n manifold.localNormal = n;\n manifold.localPoint.set(A);\n manifold.pointCount = 1;\n manifold.points[0].localPoint.set(circleB.m_p);\n manifold.points[0].id.key = 0;\n manifold.points[0].id.cf.indexA = 0;\n manifold.points[0].id.cf.typeA = Manifold.e_face;\n manifold.points[0].id.cf.indexB = 0;\n manifold.points[0].id.cf.typeB = Manifold.e_vertex;\n}", "function _circleRebound(object, barrier, axis) {\n const factor = object[axis] > barrier[axis] ? 1 : -1;\n const otherAxis = axis === 'x' ? 'y' : 'x';\n return (\n Math.sqrt(\n Math.pow(object.width / 2 + barrier.width / 2 + 0.000002, 2) -\n Math.pow(object[otherAxis] - barrier[otherAxis], 2)\n ) *\n factor +\n barrier[axis]\n ); // Inverse of distance formula where d = r1 + r2\n}", "function Circle(x,y,dx,dy,radius){\n //independent x&y values\n this.x = x;\n this.y = y;\n this.dx = dx;\n this.dy = dy;\n this.radius = radius;\n\n//creating a method within an object to create a circle every time this function is called anonymous function\n this.draw = function() {\n //console.log('hello there');\n //arc //circle\n c.beginPath();\n c.arc(this.x, this.y, this.radius, 0, Math.PI*2, false);\n c.strokeStyle = 'pink';\n c.stroke();\n c.fill();\n}\n\nthis.update = function() {\n //moving circle by 1px --> x += 1;\n\n if(this.x + this.radius > innerWidth ||\n this.x - this.radius < 0){\n this. dx = -this.dx;\n }\n if(this.y + this.radius > innerHeight ||\n this.y - this.radius < 0){\n this.dy = -this.dy;\n }\n this.x += this.dx; \n this.y += this.dy;\n\n this.draw();\n }\n}", "function move() {\n // context.fillStyle = \"black\";\n // context.fillRect(0,0,canvas.width, canvas.height);\n\n angle += 3 * Math.PI / 180;\n\n var newX = x + radius * Math.cos(angle);\n var newY = y + radius * Math.sin(angle);\n\n context.clearRect(0,0,500,500);\n context.beginPath();\n context.fillStyle = \"#00ff00\";\n context.arc(newX, newY, 10, 0, Math.PI*2);\n //context.closePath();\n context.fill();\n requestAnimationFrame(move);\n console.log('tick');\n }", "function rightBorderCollision(x, y, r, canvasWidth, bottomJaw, topJaw, ctx, colour)\n{\n //If pacmans x co-ordinate plus radius equals the width(right side)\n if((x + r) >= canvasWidth)\n {\n //just draw pacman and return x, dont increment it\n ctx.beginPath();\n ctx.arc(x, y, r, bottomJaw * Math.PI, 1.25 * Math.PI);\n ctx.fillStyle = colour;\n ctx.fill();\n ctx.beginPath();\n ctx.arc(x, y, r, 0.75 * Math.PI, topJaw * Math.PI);\n ctx.fill();\n ctx.beginPath();\n return x;\n }\n else //otherwise\n {\n //draw pacman, increment x, and return it.\n ctx.beginPath();\n ctx.arc(x, y, r, bottomJaw * Math.PI, 1.25 * Math.PI);\n ctx.fillStyle = colour; \n ctx.fill();\n ctx.beginPath();\n ctx.arc(x, y, r, 0.75 * Math.PI, topJaw * Math.PI);\n ctx.fill();\n ctx.beginPath(); \n x += 7;\n return x;\n }\n}", "function CheckIfBoundary ()\r\n{\r\n\r\n\t// If we are moving to the right\r\n\tif (isRight)\r\n\t{\r\n\t\t\r\n\t\t// translate the DeLorean so that it is pushed to left (blocked)\r\n\t\t// left = 0.1 to the left \r\n\t\ttransform.Translate (Vector3 (-0.1f, 0f, 0f));\r\n\t\t\r\n\t}\r\n\t// If we are moving to the right\r\n\telse if (isLeft)\r\n\t{\r\n\t\t\r\n\t\t// translate the DeLorean so that it is pushed to right (blocked)\r\n\t\t// right = 0.1 to the right (-0.1)\r\n\t\ttransform.Translate (Vector3 (0.1f, 0f, 0f));\r\n\t\t\t\r\n\t}\r\n\t// IF we are moving upwards\r\n\telse if (isUp)\r\n\t{\r\n\t\t\r\n\t\t// translate the DeLorean so that it is pushed down (blocked)\r\n\t\t// down = 0.1 downwards (0.1)\r\n\t\ttransform.Translate (Vector3 (0f, -0.1f, 0f));\r\n\t\t\r\n\t}\r\n\t// If we are moving downwards\r\n\telse if (isDown)\r\n\t{\r\n\t\t\t\r\n\t\t// translate the DeLorean so that it is pushed to up (blocked)\r\n\t\t// up = 0.1 upwards\r\n\t\ttransform.Translate (Vector3 (0f, 0.1f, 0f));\r\n\t\t\r\n\t}\r\n\r\n}", "move() {\n // Calculate the distance to ball\n let vectorToBall = new Soccer.Vector(Soccer.ball.position.x - this.position.x, Soccer.ball.position.y - this.position.y); // Differenzvektor\n let distanceToBall = vectorToBall.length;\n // Check, if the distance is smaller than the perceptioradius of the player \n // and make sure, that he will not come closer than the distance of 100\n // --> the referee moves to ball \n if (distanceToBall < this.perceptionRadius && distanceToBall > 100) {\n let scale = 1 / distanceToBall; // Evenly\n vectorToBall.scale(scale);\n this.position.add(vectorToBall);\n }\n }", "function leftBorderCollision(x, y, r, canvasWidth, bottomJaw, topJaw, ctx, colour)\n{\n //If pacmans x co-ordinate plus radius equals the 0 (left side of canvas)\n if((x - r) <= 0)\n {\n //just draw pacman and return x, dont de-increment it\n ctx.beginPath();\n ctx.arc(x, y, r, bottomJaw * Math.PI, 0.25 * Math.PI);\n ctx.fillStyle = colour;\n ctx.fill();\n ctx.beginPath();\n ctx.arc(x, y, r, 1.75 * Math.PI, topJaw * Math.PI);\n ctx.fill();\n ctx.beginPath();\n return x;\n }\n else//otherwise\n {\n //draw pacman, de-increment x, and return it.\n ctx.beginPath();\n ctx.arc(x, y, r, bottomJaw * Math.PI, 0.25 * Math.PI);\n ctx.fillStyle = colour;\n ctx.fill();\n ctx.beginPath();\n ctx.arc(x, y, r, 1.75 * Math.PI, topJaw * Math.PI);\n ctx.fill();\n ctx.beginPath(); \n x -= 7;\n return x;\n }\n}", "function ballCollision() {\n if (ballY + ballDY < ballRadius) {\n ballDY = -ballDY;\n }\n if (\n ballX + ballDX + ballRadius > canvas.width ||\n ballX + ballDX < ballRadius\n ) {\n ballDX = -ballDX;\n }\n\n if (\n ballX > paddleX &&\n ballX < paddleX + paddleWidth &&\n ballY + ballDY > paddleY - ballRadius\n ) {\n ballDY = -ballDY;\n }\n\n if (ballY + ballDY + ballRadius > canvas.height) {\n ballDY = 0;\n ballDX = 0;\n }\n}", "function criminalCollision() {\r\n\r\n for (i = 0; i < bullet.length; i++) {\r\n var distXCrime = Math.abs(bullet[i].x - eX - 45 / 2);\r\n var distYCrime = Math.abs(bullet[i].y - eY - 45 / 2);\r\n\r\n //no collision\r\n if (distXCrime > (25 / 2 + 20)) {\r\n continue;\r\n }\r\n if (distYCrime > (25 / 2 + 20)) {\r\n continue;\r\n }\r\n\r\n //collision\r\n if (distXCrime <= (25 / 2)) {\r\n return true;\r\n }\r\n if (distYCrime <= (25 / 2)) {\r\n return true;\r\n }\r\n\r\n //Initially was a colision algrothim for circle-rectangle, this part still worked though so kept\r\n var dx=distXCrime-25/2;\r\n var dy=distYCrime-25/2;\r\n if (dx*dx+dy*dy<=(20*20)){\r\n return true;\r\n }\r\n }\r\n}", "function draw() {\nbackground(0);\n\nlet dx = circle.x - mouseX;\nlet dy = circle.y - mouseY;\n\nif (dx < 0) {\n circle.vx = circle.speed;\n}\nelse if (dx > 0) {\n circle.vx = -circle.speed;\n}\nif (dy < 0) {\n circle.vy = circle.speed;\n}\nelse if (dy > 0) {\n circle.vy = -circle.speed;\n}\n\ncircle.x += circle.vx;\ncircle.y += circle.vy;\n\nellipse(circle.x, circle.y, circle.size);\n}", "function ballCollisionsCanvas() {\n if (ball.y + ball.radius > canvas_height) {\n ball.ySpeed = -ball.ySpeed;\n } else if (ball.y - ball.radius < 0) {\n ball.ySpeed = -ball.ySpeed;\n }\n if (ball.x + ball.radius >= canvas_width) {\n ball.xSpeed = -ball.xSpeed;\n } else if (ball.x - ball.radius < 0)\n ball.xSpeed = -ball.xSpeed;\n}", "function ballWallCollision(){\r\n if(ball.x + ball.radius > cvs.width || ball.x - ball.radius < 0){\r\n ball.dx = - ball.dx;\r\n }\r\n \r\n if(ball.y - ball.radius < 0){\r\n ball.dy = -ball.dy;\r\n }\r\n \r\n if(ball.y + ball.radius > cvs.height){\r\n LIFE--; // LOSE LIFE\r\n resetBall();\r\n }\r\n}", "handleCollision(climber) {\n\n // distance\n //\n // to calculate the distance between the avalanche and climber\n let d = dist(this.x, this.y, climber.x, climber.y);\n\n // dist()\n //\n // To keep track of the avalanche and the avatar are in contact\n if (d < this.width / 2 + climber.width / 2) {\n // this is to push the climber down\n climber.vy += 2;\n\n }\n }", "function mouseDragged() {\n\tif (circle.active) {\n\t\tcircle.x = constrain(circle.x + (mouseX - circle.x) * 0.1, 80, 600)\n\n\t\tcircle.y = constrain(circle.y + (mouseY - circle.y) * 0.1, 450, 450)\n\n\t}\n\treturn false;\n}", "function checkForCollisionWithWall(dt, c, g, cor) {\n\t\tif (x < 0) {\n\t\t\txSpeed = Math.abs(xSpeed);\n\t\t} else if (x + (radius * 2) > c.canvas.width) {\n\t\t\txSpeed = -1 * Math.abs(xSpeed);\n\t\t}\n\n\t\t/*unused collision check for ceiling, circles can fly above the ceiling\n\t\tif (y < 0) {\n\t\t\tySpeed = Math.abs(ySpeed);\n\t\t}\n\t\t*/\n\n\t\tif (y + (radius * 2) > c.canvas.height) {\n\t\t\tySpeed = -1 * Math.abs(ySpeed) * cor;\n\n\t\t\t/*\n\t\t\tStop circle oscillation if ySpeed is low enough.\n\t\t\tMake it look nicer, instead of seeming to\n\t\t\tvibrate at low speeds along the ground.\n\t\t\t*/\n\t\t\tif (Math.abs(ySpeed) < (1 * 60)) {\n\t\t\t\t//ySpeed = 0;\n\t\t\t\ty = c.canvas.height - (radius * 2);\n\t\t\t}\n\t\t\t/*\n\t\t\tDepending on whether g is added to ySpeed before of after floor collisions,\n\t\t\tcircles gain/lose speed when hitting the floor unless next line is included.\n\t\t\tPotentially remove this for Funsics? could be the source of random speed\n\t\t\t*/\n\t\t\t//ySpeed -= (g * dt);\n\t\t}\n\t}", "function Circle(x, y, dx, dy, radius, r, g, b) {\n this.x = x;\n this.y = y;\n this.dx = dx;\n this.dy = dy;\n this.radius = radius;\n this.minRadius = radius;\n this.r = r;\n this.g = g;\n this.b = b;\n this.color = colorArray[Math.floor(Math.random() * colorArray.length)]\n\n this.draw = function () {\n c.beginPath();\n c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);\n // c.strokeStyle = `rgb(${r}, ${g}, ${b})`;\n // c.fillStyle = `rgb(${r}, ${g}, ${b})`;\n c.fillStyle = this.color\n // c.stroke();\n c.fill();\n }\n this.update = function () {\n if (this.x + this.radius > innerWidth || this.x - this.radius < 0) {\n this.dx = -this.dx;\n }\n if (this.y + this.radius > innerHeight || this.y - this.radius < 0) {\n this.dy = -this.dy;\n }\n this.x += this.dx;\n this.y += this.dy;\n\n\n //INTERACTIVITY portion\n if (mouse.x - this.x < 50 \n && mouse.x - this.x > -50\n && mouse.y - this.y < 50 \n && mouse.y - this.y > -50) {\n if (this.radius < maxRadius) {\n this.radius += 1;\n }\n } else if (this.radius > this.minRadius) {\n this.radius -= 1;\n }\n\n this.draw();\n }\n}", "move() {\n this.center.x += this.speed.x;\n this.center.y += this.speed.y;\n \n wrapAround(this.center);\n }", "function draw() {\n\n background(bg.r, bg.g, bg.b);\n bg.r = map (circleA.size, 350, 500, 0, 200);\n bg.g += 1;\n bg.g = constrain(bg.g, 0, 88);\n bg.b += 1;\n bg.b = constrain(bg.g, 0, 38);\n\n\n// Draw a square in the centre of the canvas\n rectMode(CENTER);\n fill(229, 160, 225, 200);\n rect(width/2, height/2, 1050, 550);\n\n//Draw moving circle A\n circleA.x +=circleA.speed;\n circleA.x = constrain (circleA.x, 0, width/2);\n circleA.size +=circleA.growthRate;\n circleA.size = constrain (circleA.size, 0, 550);\n fill(circleA.fill, circleA.alpha);\n ellipse(circleA.x,circleA.y,circleA.size);\n\n\n//Draw moving circle B\n//Add negative 1 to x!\n circleB.x +=circleB.speed;\n circleB.x = constrain (circleB.x, width/2, width);\n circleB.size =circleA.size * circleB.sizeRatio;\n fill(circleB.fill, circleB.alpha);\n ellipse(circleB.x,circleB.y,circleB.size);\n}", "checkCollision(){\n\n if(this.radius > 0){\n if(this.x + this.radius > game.getWidth() || this.x - this.radius < 0){\n this.xVel *= -1;\n }\n\n if(this.y + this.radius > game.getHeight() || this.y - this.radius < 0){\n this.yVel *= -1;\n }\n } \n \n }", "function generated_object(color)\n{\n //coordinates\n this.posX=0;\n this.posY=-100;\n\n //colour of obstacle\n if(color==\"red\") this.color=\"#FE3E67\";\n else this.color=\"#05A8C4\";\n\n //decide shape randomly\n\n if(random_value()) this.shape=\"circle\";\n else this.shape=\"rect\";\n\n //decide position randomly\n\n if(random_value()) this.update_pos=\"left\";\n else this.update_pos=\"right\";\n\n //decide width of object\n\n if(this.shape == \"circle\") this.posX = width/2 - 150;\n else this.posX = width/2 - 162.5;\n \n //update co-ordinate for object for respective lane\n\n if(this.update_pos == \"left\") this.posX += 100;\n if(color == \"red\") this.posX += 200;\n\n //draw circles and rectangles acc to random guessed as above\n\n // it will remain 1 until it collides with car and after collision it becomes zero and draw function doesn't execute\n var status=1;\n //rectnagle disappear after travelling whole screen height\n var status_r=1; \n if(draw_again_status){\n this.draw = function () \n {\n if(this.shape == \"rect\")\n {\n if(status_r==1) //if not travelled whole screen\n {\n draw_rect(this.posX,this.posY,this.color);\n }\n } \n else if(status==1) //before collision \n {\n draw_circles(this.posX,this.posY,this.color);\n }\n \n \n };\n}\n\n this.update = function () \n {\n this.posY += 10;\n\n console.log( Math.floor( Math.sqrt( Math.pow(this.posX - redone.x , 2) + Math.pow(this.posY - redone.y,2) ) ) || Math.sqrt( Math.floor( Math.sqrt( Math.pow(this.posX - blueone.x,2) + Math.pow(this.posY - blueone.y,2)) ) < 40 ) ) //to get the value of collision logic\n\n if(this.shape==\"rect\" && (Math.sqrt( Math.floor( Math.sqrt( Math.pow(this.posX - redone.x,2) + Math.pow(this.posY - redone.y,2)) ) < 40 ) || Math.sqrt( Math.floor( Math.sqrt( Math.pow(this.posX - blueone.x,2) + Math.pow(this.posY - blueone.y,2)) ) < 40 )))\n {\n bgsound.muted=true;\n draw_again_status=0;\n if(f==1) collision_sound.play();\n f=0;\n collision(); //call for collision func\n }\n else if(this.posY ==height) \n {\n //for disappearing rect obj \n status_r=0;\n }\n if(this.shape==\"circle\" && (Math.sqrt( Math.floor( Math.sqrt( Math.pow(this.posX - redone.x,2) + Math.pow(this.posY - redone.y,2)) ) < 40 ) || Math.sqrt( Math.floor( Math.sqrt( Math.pow(this.posX - blueone.x,2) + Math.pow(this.posY - blueone.y,2)) ) <40 )))\n {\n circlesound.pause();\n if(status==1)\n {score++; }\n status=0; //disappearing circle after collision\n //score updated after each collision \n if(score % 20 == 0 && speed_counter > 20){\n console.log(\"speed Increased\");\n speed_counter--;\n }\n circlesound.play();\n document.getElementById(\"score\").innerHTML = score; }//calling func to print score\n /*this is a special condition*/\n /* if circle and car collison doesnt occur game is over */\n else if(this.shape==\"circle\" && this.posY >=750 && status==1)\n {\n status=0;\n f=0;\n bgsound.muted=true;\n draw_again_status=0;\n if(f==1) collision_sound.play();\n collision(); \n \n }\n \n \n \n }\n}", "checkCollision (obj) {\n if (this.x < obj.x + obj.width\n && this.x + this.width > obj.x\n && this.y < obj.y + obj.height\n && this.y + this.height > obj.y) {\n obj.resetPosition();\n }\n }", "move(angle) {\n if (this.quarantine == false) {\n // border right\n if (this.x > (this.plane.width() - 17)) {\n this.angle = this.direction(90, 270)\n }\n // border left\n else if (this.x < 0) {\n this.angle = this.direction(0, 90)\n }\n // border top\n else if (this.y > (this.plane.height() - 17)) {\n this.angle = this.direction(0, 180)\n }\n // border bottom\n else if (this.y < 0) {\n this.angle = this.direction(180, 360)\n }\n\n //what pixel to go to\n let rads = angle * Math.PI / 180\n let vx = Math.cos(rads)\n let vy = Math.sin(rads)\n this.x += vx\n this.y -= vy\n\n //change the position in css\n $(\"#\" + this.id).css({\n bottom: Math.floor(this.y),\n left: Math.floor(this.x)\n })\n }\n }", "function moveCircleDown (){\n\nypos = ypos + 30;\n\n}", "function BoxCollision() {\n\tif(BallX+BallDisplacementX >1130 || BallX+ BallDisplacementX < BallRadius) {\n\t\tBallDisplacementX = -1.05*BallDisplacementX;\n\t\tBallDisplacementY = 1.05*BallDisplacementY;\n\t}\n\n\tif (BallY + BallDisplacementY - BallRadius < 0) {\n\t\tBallDisplacementY = -1.05*BallDisplacementY;\n\t}\n\n}", "function ballCollisionsCanvas(){\n if(ball.y + ball.radius > canvas_height){\n ball.ySpeed = -ball.ySpeed;\n }else if(ball.y - ball.radius < 0){\n ball.ySpeed = -ball.ySpeed;\n }\n if(ball.x + ball.radius >= canvas_width){\n ball.xSpeed = -ball.xSpeed;\n }else if(ball.x - ball.radius < 0)\n ball.xSpeed = -ball.xSpeed;\n}", "function drawAnimatedCircle(){\n\tif(moving && clickedTile_X >= 0 && clickedTile_Y >= 0){\n\t\tdrawACircle(newCircle_X, newCircle_Y, squareSize / 2 - innerBorder * 2, isPlayer1 ? 1 : 2, player1Color, player2Color, true);\n\t\tdrawACircle(newCircle_X, newCircle_Y, squareSize / 3 - innerBorder * 2, isPlayer1 ? 1 : 2, player1ColorDark, player2ColorDark, true);\n\t\tnewCircle_Y = Math.min(target_Y,newCircle_Y + animationSpeed * desiredFPS);\n\t\tif(newCircle_Y == target_Y){\n\t\t\tmoving = false;\n\t\t\tif(isPlayer1){\n\t\t\t\tboardArray[clickedTile_X + columns * clickedTile_Y] = 1;\n\t\t\t} else {\n\t\t\t\tboardArray[clickedTile_X + columns * clickedTile_Y] = 2;\n\t\t\t}\n\t\t\tif(checkWinCondition(clickedTile_X,clickedTile_Y)){\n\t\t\t\tcanvas.onclick = null;\n\t\t\t} else {\n\t\t\t\tisPlayer1 = !isPlayer1;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tmoving = false;\n\t}\n}", "function draw(){\r\n//put drawing code here\r\nbackground(0,255,178);\r\nfill(255,87,51);\r\nellipse(x,y,50,50);\r\n\r\n//how the circle moves \r\nif (keyIsDown(LEFT_ARROW)){\r\nx-=50;\r\n}\r\n\r\nif (keyIsDown(RIGHT_ARROW)){\r\n x+=50;\r\n}\r\n\r\nif (keyIsDown(UP_ARROW)){\r\ny-=50;\r\n}\r\n\r\nif (keyIsDown(DOWN_ARROW)){\r\ny+=50; }\r\n\r\n}", "function moveUpR() {\n if (objectLine2.transform[1] >= 0.9) {\n return;\n }\n objectLine2.transform[1] += 0.02;\n drawObjects();\n}", "function ballWallCollision(ball, canvas) {\n\n if (ball.x + ball.dx + ball.radius > canvas.width || ball.x + ball.dx - ball.radius < 0) {\n ball.dx = -ball.dx\n console.log(ball.dx);\n\n }\n if (ball.y + ball.dy - ball.radius < 0) {\n ball.dy = -ball.dy\n }\n if (ball.y + ball.radius > canvas.height) {\n resetBall(ball, canvas)\n }\n}", "function circleClicked(e){\n if(e.target.getCircleType()!=Circle.TYPE_DOT){\n e.target.setCircleType(Circle.TYPE_SELECTED);\n point = point+1;\n\n document.getElementById(\"points\").innerHTML = point;\n }else{\n return;\n }\n\n if(currentDot.indexX==0||currentDot.indexX==8||currentDot.indexY==0||currentDot.indexY==8){\n alert(\"Game Over! You have failed to trap the blue dot, Plz refresh the page and try it again\");\n return;\n }\n //direction, we hav 6 directions Basic Ideas\n //var leftCircle = circleArr[currentCat.indexX-1][currentCat.indexY];\n //var rightCircle = circleArr[currentCat.indexX+1][currentCat.indexY];\n //var leftTopCircle = circleArr[currentCat.indexX-1][currentCat.indexY-1];\n //var rightTopCircle = circleArr[currentCat.indexX][currentCat.indexY-1];\n //var leftbotCircle = circleArr[currentCat.indexX-1][currentCat.indexY+1];\n //var rightbotCircle = circleArr[currentCat.indexX][currentCat.indexY+1];\n //if(leftCircle.getCircleType()==1){\n // leftCircle.setCircleType(3);\n // currentCat.setCircleType(1);\n // currentCat = leftCircle;\n //\n //}else if(rightCircle.getCircleType()==1){\n // rightCircle.setCircleType(3);\n // currentCat.setCircleType(1);\n // currentCat = rightCircle;\n //\n //}else if(leftTopCircle.getCircleType()==1){\n // leftTopCircle.setCircleType(3);\n // currentCat.setCircleType(1);\n // currentCat = leftTopCircle;\n //\n //}else if(rightTopCircle.getCircleType()==1){\n // rightTopCircle.setCircleType(3);\n // currentCat.setCircleType(1);\n // currentCat = rightTopCircle;\n //\n //}else if(leftbotCircle.getCircleType()==1){\n // leftbotCircle.setCircleType(3);\n // currentCat.setCircleType(1);\n // currentCat = leftbotCircle;\n //\n //}else if(rightbotCircle.getCircleType()==1){\n // rightbotCircle.setCircleType(3);\n // currentCat.setCircleType(1);\n // currentCat = rightbotCircle;\n //\n //}else{\n // alert(\"Gratz u win! your point: \"+ point);\n //}\n\n var dir = getMoveDir(currentDot);\n switch (dir){\n case MOVE_LEFT:\n currentDot.setCircleType(Circle.TYPE_UNSELECTED);\n currentDot = circleArr[currentDot.indexX-1][currentDot.indexY];\n currentDot.setCircleType(Circle.TYPE_DOT);\n break;\n case MOVE_UP_LEFT:\n currentDot.setCircleType(Circle.TYPE_UNSELECTED);\n currentDot = circleArr[currentDot.indexY%2?currentDot.indexX:currentDot.indexX-1][currentDot.indexY-1];\n currentDot.setCircleType(Circle.TYPE_DOT);\n break;\n case MOVE_UP_RIGHT:\n currentDot.setCircleType(Circle.TYPE_UNSELECTED);\n currentDot = circleArr[currentDot.indexY%2?currentDot.indexX+1:currentDot.indexX][currentDot.indexY-1];\n currentDot.setCircleType(Circle.TYPE_DOT);\n break;\n case MOVE_RIGHT:\n currentDot.setCircleType(Circle.TYPE_UNSELECTED);\n currentDot = circleArr[currentDot.indexX+1][currentDot.indexY];\n currentDot.setCircleType(Circle.TYPE_DOT);\n break;\n\n case MOVE_DOWN_RIGHT:\n currentDot.setCircleType(Circle.TYPE_UNSELECTED);\n currentDot = circleArr[currentDot.indexY%2?currentDot.indexX+1:currentDot.indexX][currentDot.indexY+1];\n currentDot.setCircleType(Circle.TYPE_DOT);\n break;\n case MOVE_DOWN_LEFT:\n currentDot.setCircleType(Circle.TYPE_UNSELECTED);\n currentDot = circleArr[currentDot.indexY%2?currentDot.indexX:currentDot.indexX-1][currentDot.indexY+1];\n currentDot.setCircleType(Circle.TYPE_DOT);\n break;\n default :\n alert(\"Gratz! You have used: \"+point+\" steps to trap the BLUE DOT!\");\n }\n\n}", "function didCollideWithBowl(r, x, y, dx, dy){\n //calculate dist between bowl and object\n var distBetweenBowl = computeDistanceBetweenCircles(r, x, y, bowlRadius, 0, 0);\n //calculate dist between bowl and where object will be next update\n var futuredDistBetweenBowl = computeDistanceBetweenCircles(r, x + dx, y + dy, bowlRadius, 0, 0);\n //if collides with main bowl return 1\n if( (futuredDistBetweenBowl > bowlRadius - r && distBetweenBowl < bowlRadius && y + dy < bowlMaxY) || (futuredDistBetweenBowl < bowlRadius + r && distBetweenBowl > bowlRadius && y + dy < bowlMaxY)){\n return 1;\n }else{\n var futuredDistBetweenLidLeft = computeDistanceBetweenCircles(r, x + dx, y + dy, lidRad, getCircleXFromY(bowlMaxY, 0, 0, bowlRadius) + lidRad, bowlMaxY);\n var futuredDistBetweenLidRight = computeDistanceBetweenCircles(r, x + dx, y + dy, lidRad, -getCircleXFromY(bowlMaxY, 0, 0, bowlRadius) - lidRad, bowlMaxY);\n //if collides with left lid circle return 2\n if(futuredDistBetweenLidLeft < lidRad + r){\n return 2;\n //if collides with right lid circle return 3\n }else if(futuredDistBetweenLidRight < lidRad + r){\n return 3;\n }\n }\n //else no collision\n return 0;\n}", "function MoveToLeftMost(){\n\t//var movePixel = 8 - circles[pointedCircle].guiTexture.pixelInset.x;\n\n\tvar amount = circles.length;\n\tfor (var i = pointedCircle; i < amount; i++)\n\t{\n\t\tcircles[i].transform.position = Vector3.MoveTowards(circles[i].transform.position, Vector3(tarPosX[i], 0.91, 0), Time.deltaTime);\n\t}\n}", "function togglePinning( circleBody ) \n{\n if ( !circleBody.isStatic )\n circleBody.render.fillStyle = PINNED_CIRCLE_FILL_COLOR;\n else\n circleBody.render.fillStyle = CIRCLE_FILL_COLOR;\n circleBody.isStatic = !circleBody.isStatic;\n}", "function copCollision() {\r\n\r\n for (i = 0; i < bullet.length; i++) {\r\n var distXCop = Math.abs(bullet[i].x - pX - 45 / 2);\r\n var distYCop = Math.abs(bullet[i].y - pY - 45 / 2);\r\n\r\n //no collision\r\n if (distXCop > (25 / 2 + 20)) {\r\n continue;\r\n }\r\n if (distYCop > (25 / 2 + 20)) {\r\n continue;\r\n }\r\n\r\n //collision\r\n if (distXCop <= (25 / 2)) {\r\n return true;\r\n }\r\n if (distYCop <= (25 / 2)) {\r\n return true;\r\n }\r\n\r\n //Initially was a colision algrothim for circle-rectangle, this part still worked though so kept\r\n var dx = distXCop - 25 / 2;\r\n var dy = distYCop - 25 / 2;\r\n if (dx * dx + dy * dy <= (20 * 20)) {\r\n return true;\r\n }\r\n }\r\n}", "moveAndHandleCollision(ball) {\n const movedBall = ball.move()\n const collider = this.getCollider(movedBall)\n if (collider) {\n const direction = Direction.fromAngle(collider.angle)\n if (collider.ball) {\n this.startMovingBall(collider.ball, direction, ball.speed)\n }\n return ball.update({ direction: direction.invert() })\n }\n return movedBall\n }", "check_border() {\n\n\t\t// prevents the bubble to go over to the left of the canvas\n\t\tif(this.x < this.radius) {\n\t\t\tthis.x = this.radius;\n\t\t}\n\n\t\t// prevents the bubble to go over to the right of the canvas\n\t\tif(this.x > canvas.width - this.radius) {\n\t\t\tthis.x = canvas.width - this.radius;\n\t\t}\n\n\t\t// prevents the bubble to go over the top of the canvas\n\t\tif(this.y < this.radius) {\n\t\t\tthis.y = this.radius;\n\t\t}\n\n\t\t// prevents the bubble to go over the bottom of the canvas\n\t\tif(this.y > canvas.height - this.radius) {\n\t\t\tthis.y = canvas.height - this.radius;\n\t\t}\n\n\t}", "function draw() {\n background(70);\n diffCircle.update();\n if (mouseIsPressed) {\n diffCircle = diffCircle - 300 ;\n } else {\n diffCircle = diffCircle + 300;\n }\n }", "function moveCircleUp (){\n\nypos = ypos - 30;\n\n}", "circle() {\n const context = GameState.current;\n\n Helper.strewnSprite(\n Helper.getMember(GroupPool.circle().members),\n { y: context.game.stage.height },\n { y: 2 },\n (sprite) => {\n this._tweenOfCircle(context, sprite);\n }\n );\n }", "function moveShapeRight()\n {\n undrawShape();\n\n // check to see if the shape is at the edge of the grid\n // this is to prevent the shape going out and appear from the other side of the grid\n const isAtRightEdge = currentShape.some(\n (index) => (currentPosition + index) % GRID_WIDTH === GRID_WIDTH -1);\n\n \n if(!isAtRightEdge)\n {\n currentPosition +=1;\n canRotate = true;\n }\n else if(isAtRightEdge)\n {\n canRotate = false;\n }\n\n\n let isCollisionSquare = currentShape.some(\n (index) => squares[currentPosition + index].classList.contains(\"taken\"))\n \n \n if(isCollisionSquare)\n {\n currentPosition-=1 // dont move the shape to the Right \n }\n\n drawShape();\n\n }", "paddleCollision(paddle1, paddle2) {\n\n \n // if moving toward the right end ================================\n if (this.vx > 0) {\n let paddle = paddle2.coordinates(paddle2.x, paddle2.y, paddle2.width, paddle2.height);\n let [leftX, rightX, topY, bottomY] = paddle;\n // right edge of the ball is >= left edge of the paddle\n if(\n (this.x + this.radius >= leftX) && \n (this.x + this.radius <= rightX) &&\n (this.y >= topY && this.y <= bottomY)\n ){\n this.vx = -this.vx;\n this.ping.play();\n }\n }\n else {\n\n // if moving toward the right end ============================\n let paddle = paddle1.coordinates(paddle1.x, paddle1.y, paddle1.width, paddle1.height);\n let [leftX, rightX, topY, bottomY] = paddle;\n // right edge of the ball is <= left edge of the paddle\n if(\n (this.x - this.radius <= rightX) && \n (this.x - this.radius >= leftX) &&\n (this.y >= topY && this.y <= bottomY)\n ){\n this.vx = -this.vx;\n this.ping.play();\n }\n }\n \n }", "function moveBall() {\n balls.forEach((element) => {\n if (\n element.xPos + element.radius > canvas.width ||\n element.xPos - element.radius < 0\n ) {\n element.xVel = -element.xVel;\n }\n if (\n element.yPos + element.radius > canvas.height ||\n element.yPos - element.radius < 0\n ) {\n element.yVel = -element.yVel;\n }\n\n element.xPos += element.xVel;\n element.yPos += element.yVel;\n });\n}", "doBounce (target, collisionCorrection) {\n if (\n this.movable && this.solid\n && !target.movable && target.solid\n ) {\n if (\n this.shape === SHAPES.CIRCLE && target.shape === SHAPES.CIRCLE\n ) {\n \n // For circle + circle collisions, the collision correction already\n // tells us the bounce direction.\n const angle = Math.atan2(collisionCorrection.y - this.y, collisionCorrection.x - this.x)\n const speed = Math.sqrt(this.pushX * this.pushX + this.pushY * this.pushY)\n\n this.pushX = Math.cos(angle) * speed\n this.pushY = Math.sin(angle) * speed\n\n } else if (\n this.shape === SHAPES.CIRCLE\n && (target.shape === SHAPES.SQUARE || target.shape === SHAPES.POLYGON)\n ) {\n \n // For circle + polygon collisions, we need to know...\n // - the original angle this circle was moving towards (or rather, its\n // reverse, because we want a bounce)\n // - the normal vector (of the edge) of the polygon this circle collided\n // into (which we can get from the collision correction)\n // - the angle between them\n const reverseOriginalAngle = Math.atan2(-this.pushY, -this.pushX)\n const normalAngle = Math.atan2(collisionCorrection.y - this.y, collisionCorrection.x - this.x)\n const angleBetween = normalAngle - reverseOriginalAngle\n const angle = reverseOriginalAngle + 2 * angleBetween\n\n const speed = Math.sqrt(this.pushX * this.pushX + this.pushY * this.pushY)\n\n this.pushX = Math.cos(angle) * speed\n this.pushY = Math.sin(angle) * speed\n \n } else {\n // For the moment, we're not too concerned about polygons bumping into each other\n }\n } else if (\n this.movable && this.solid\n && target.movable && target.solid\n && collisionCorrection.pushX !== undefined\n && collisionCorrection.pushY !== undefined\n ) {\n this.pushX = collisionCorrection.pushX\n this.pushY = collisionCorrection.pushY\n }\n }", "function handleCollision() {\n ballTop = ballY - BALL_SIZE;\n ballBottom = ballY + BALL_SIZE;\n\n // Handle collision with the walls\n if (ballTop + ballDY < 0 || ballBottom > canvas.height) {\n ballDY = -ballDY;\n }\n}", "function moveCircleLeft (){\n\nxpos = xpos - 30;\n\n}", "function CollisionCalculatorC2C(o1,o2) {\n //console.log(o1,o2);\n var dist = Math.sqrt( Math.pow((o2.x-o1.x),2)+Math.pow((o2.y-o1.y),2));\n var totalR = o2.r + o1.r;\n if(dist>totalR){\n return false;\n }\n /*\n var colPoint = new Point( o2.x + (o1.position.x-o2.position.x)*o2.r/(o2.r+o1.r),o2.y + (o1.position.y-o2.position.y)*o2.r/(o2.r+o1.r);\n */\n\n var region = \"\";\n if (o1.y < o2.y - Math.abs(o2.height/2)) {\n\n //If it is, we need to check whether it's in the\n //top left, top center or top right\n if (o1.x < o2.x - 1 - Math.abs(o2.width/2)) {\n region = \"topLeft\";\n } else if (o1.x > o2.x + 1 + Math.abs(o2.width/2)) {\n region = \"topRight\";\n } else {\n region = \"topMiddle\";\n }\n }\n\n else if ((o1.y > o2.y + Math.abs(o2.height/2))) {\n\n //If it is, we need to check whether it's in the bottom left,\n //bottom center, or bottom right\n if (o1.x < o2.x - 1 - Math.abs(o2.width/2)) {\n region = \"bottomLeft\";\n } else if (o1.x > o2.x + 1 + Math.abs(o2.width/2)) {\n region = \"bottomRight\";\n } else {\n region = \"bottomMiddle\";\n }\n } \n else {\n if (o1.x < o2.x - Math.abs(o2.width/2)) {\n region = \"leftMiddle\";\n } else {\n region = \"rightMiddle\";\n }\n }\n\n //return true;\n return [true,region];\n}", "move2_to_3() {\n this.toMovevertically = true;\n this._centpt.y -= 1;\n // console.log(\" Y : \"+this._centpt.y);\n if (this._centpt.y <= 80) {\n this.toMovevertically = false;\n }\n }", "function draw() {\n \n // Colouring the background\n background(220);\n\n // Changing the x and the y position\n xPosition = xPosition + xSpeed * xDirection;\n yPosition = yPosition + ySpeed * yDirection;\n\n // Changing the x direction so that it bounces off\n if (xPosition > width - radius || xPosition < radius) {\n xSpeed *= -1;\n }\n\n // Changing the y direction so that it bounces off\n if (yPosition > height - radius || yPosition < radius) {\n ySpeed *= -1;\n }\n\n // Creating the ellipse\n ellipse(xPosition, yPosition, radius, radius);\n\n}", "function myMove(eball)\n{\n //Set the position 0 initially\n var pos = 0;\n //Ref 8 based on stackoverflow defined in licenses.txt\n //Answer Link:https://stackoverflow.com/questions/25352760/how-to-make-object-move-in-js\n\n //Set a interval sa as to make the ball finish its desired path in a fixed time limit\n var id = setInterval(frame, 10);\n //Function that has the moving logic\n function frame()\n {\n //Clear the element if it reaches below a certain pixel range\n if (pos == 1024)//setting of the finish line\n {\n clearInterval(id);\n eball.remove();\n }\n //Continue to move till the finish line hits.\n else\n {\n pos++;//Add the position\n eball.style.top = pos + 'px';//Continuosly keep on adding the position value to account for the movement\n }\n }\n}", "function moveBubble() {\n bubble.x += bubble.vx;\n bubble.y += bubble.vy;\n}", "function colisionan(a, b) {\n var dx = a.x - b.x;\n var dy = a.y - b.y;\n var distance = Math.sqrt(dx * dx + dy * dy);\n\n if (distance < a.r + b.r) {\n a.x -= a.velX;\n a.y -= a.velY;\n b.x -= b.velX;\n b.y -= b.velY;\n\n a.velX *= -1;\n a.velY *= -1;\n b.velX *= -1;\n b.velY *= -1;\n }\n\n}", "function collide(node) {\n// var r1 = 2 + (radtype ? node.pr_rad : node.evc_rad)\n var r1 = 1 + node.radius\n var nx1 = node.x - r1\n var nx2 = node.x + r1\n var ny1 = node.y - r1\n var ny2 = node.y + r1\n return function(quad, x1, y1, x2, y2) {\n if (quad.point && (quad.point !== node)) {\n var x = node.x - quad.point.x\n var y = node.y - quad.point.y\n var l = Math.sqrt(x * x + y * y)\n// var r = radtype ? (node.pr_rad + quad.point.pr_rad) : (node.evc_rad + quad.point.evc_rad)\n var r = node.radius + quad.point.radius\n if (l < r) {\n l = (l - r) / l * 0.5\n node.x -= x *= l\n node.y -= y *= l\n quad.point.x += x\n quad.point.y += y\n }\n }\n return x1 > nx2\n || x2 < nx1\n || y1 > ny2\n || y2 < ny1\n }\n}", "function update() {\n// update velocity\n vy += gravity; // gravity\n \n // update position\n x += vx;\n y += vy; \n \n // handle bouncing\n if (y > canvas.height - radius){\n \n y = canvas.height - radius;\n vy *= -velRedFac;\n color = getRandomColor()\n };\n // wrap around\n if (x > canvas.width + radius){\n \n x = canvas.offsetLeft;\n };\n if (x < canvas.offsetLeft){\n\n x = canvas.width;\n };\n // update the ball\n drawBall();\n}", "circleRectangleCollision(c1, r1, bounce = false, global = false) {\n //Add collision properties\n if (!r1._bumpPropertiesAdded)\n this.addCollisionProperties(r1);\n if (!c1._bumpPropertiesAdded)\n this.addCollisionProperties(c1);\n let region, collision, c1x, c1y, r1x, r1y;\n //Use either the global or local coordinates\n if (global) {\n c1x = c1.gx;\n c1y = c1.gy;\n r1x = r1.gx;\n r1y = r1.gy;\n }\n else {\n c1x = c1.x;\n c1y = c1.y;\n r1x = r1.x;\n r1y = r1.y;\n }\n //Is the circle above the rectangle's top edge?\n if (c1y - c1.yAnchorOffset < r1y - Math.abs(r1.halfHeight) - r1.yAnchorOffset) {\n //If it is, we need to check whether it's in the\n //top left, top center or top right\n if (c1x - c1.xAnchorOffset < r1x - 1 - Math.abs(r1.halfWidth) - r1.xAnchorOffset) {\n region = \"topLeft\";\n }\n else if (c1x - c1.xAnchorOffset > r1x + 1 + Math.abs(r1.halfWidth) - r1.xAnchorOffset) {\n region = \"topRight\";\n }\n else {\n region = \"topMiddle\";\n }\n }\n else if (c1y - c1.yAnchorOffset > r1y + Math.abs(r1.halfHeight) - r1.yAnchorOffset) {\n //If it is, we need to check whether it's in the bottom left,\n //bottom center, or bottom right\n if (c1x - c1.xAnchorOffset < r1x - 1 - Math.abs(r1.halfWidth) - r1.xAnchorOffset) {\n region = \"bottomLeft\";\n }\n else if (c1x - c1.xAnchorOffset > r1x + 1 + Math.abs(r1.halfWidth) - r1.xAnchorOffset) {\n region = \"bottomRight\";\n }\n else {\n region = \"bottomMiddle\";\n }\n }\n else {\n if (c1x - c1.xAnchorOffset < r1x - Math.abs(r1.halfWidth) - r1.xAnchorOffset) {\n region = \"leftMiddle\";\n }\n else {\n region = \"rightMiddle\";\n }\n }\n //Is this the circle touching the flat sides\n //of the rectangle?\n if (region === \"topMiddle\" || region === \"bottomMiddle\" || region === \"leftMiddle\" || region === \"rightMiddle\") {\n //Yes, it is, so do a standard rectangle vs. rectangle collision test\n collision = this.rectangleCollision(c1, r1, bounce, global);\n }\n else {\n let point = { x: undefined, y: undefined };\n switch (region) {\n case \"topLeft\":\n point.x = r1x - r1.xAnchorOffset;\n point.y = r1y - r1.yAnchorOffset;\n break;\n case \"topRight\":\n point.x = r1x + r1.width - r1.xAnchorOffset;\n point.y = r1y - r1.yAnchorOffset;\n break;\n case \"bottomLeft\":\n point.x = r1x - r1.xAnchorOffset;\n point.y = r1y + r1.height - r1.yAnchorOffset;\n break;\n case \"bottomRight\":\n point.x = r1x + r1.width - r1.xAnchorOffset;\n point.y = r1y + r1.height - r1.yAnchorOffset;\n }\n //Check for a collision between the circle and the point\n collision = this.circlePointCollision(c1, point, bounce, global);\n }\n if (collision) {\n return region;\n }\n else {\n return collision;\n }\n }", "function circleLessRed(){\n r = r - 40;\n}", "function collide(node) {\n var nodeID = +d3.select(node).attr('id')\n var dx = +d3.select(node).attr('cx')\n var dy = +d3.select(node).attr('cy')\n var r = +d3.select(node).attr('r'),\n nx1 = dx - r,\n nx2 = dx + r,\n ny1 = dy - r,\n ny2 = dy + r\n var colliding = false\n d3.selectAll('g').each(function(point, i) {\n var pointID = +d3.select(this).attr('id')\n var pr = +d3.select(this).attr('r')\n var px = +d3.select(this).attr('cx')\n var py = +d3.select(this).attr('cy')\n var x1 = px - pr,\n y1 = py - pr,\n x2 = px + pr,\n y2 = py + pr\n var x = dx - px,\n y = dy - py,\n l = Math.sqrt(x * x + y * y),\n rad = r + pr\n if (l < rad) {\n l = (l - rad) / l * .5\n\n if (!isFinite(l)) {\n l = 0\n }\n x *= l\n y *= l\n dx -= x\n dy -= y\n px += x\n py += y\n\n if (d3.select(this).classed('ended') && d3.select(this).attr('T') == 1) {\n d3.select(node).attr('cx', Math.max(r, Math.min(w - r, dx)))\n d3.select(this).attr('cx', Math.max(pr, Math.min(w - pr, px)))\n\n } else if (d3.select(node).classed('ended') && d3.select(node).attr('T') == 1) {\n d3.select(node).attr('cx', Math.max(r, Math.min(w - r, dx)))\n d3.select(this).attr('cx', Math.max(pr, Math.min(w - pr, px)))\n } else {\n d3.select(node).attr('cx', Math.max(r, Math.min(w - r, dx)))\n d3.select(node).attr('cy', Math.max(r, Math.min(h - r, dy)))\n d3.select(this).attr('cx', Math.max(pr, Math.min(w - pr, px)))\n d3.select(this).attr('cy', Math.max(py, Math.min(h - pr, py)))\n }\n\n\n\n }\n if (!(nx1 > x2 || nx2 < x1 || ny1 > y2 || ny2 < y1) && pointID != nodeID)\n colliding = true\n })\n return colliding\n}", "moveBall() {\n if (!this.firstCollision) {\n this.ball.Y += this.ball.dy;\n } else {\n this.ball.X += this.ball.dx;\n this.ball.Y += this.ball.dy;\n }\n }", "function Element(x, y, rad, col){\n var pos;\n var vel;\n var dir;\n var r;\n var color;\n\n\n this.pos = new p5.Vector(x, y);\n this.vel = new p5.Vector(random(-1, 1), random(-1, 1));\n this.dir = this.vel.copy();\n this.r = rad;\n this.color = col;\n\n // Define movement: every Element moves on a straight line;\n\n this.move = function(){\n var mag = this.vel.mag(); //Keep track of the velocity;\n \n this.vel.x += (this.dir.x - this.vel.x) * 0.01; //Slowly change the velocity vector\n this.vel.y += (this.dir.y - this.vel.y) * 0.01; //to agree with the new direction;\n this.vel.normalize();\n this.vel.mult(mag); //Each element will move with the same initial velocity;\n\n this.pos.add(this.vel);\n\n }\n\n //Define behaviour when the circles overlap\n \n this.onOverlap = function(other){\n var d = (this.pos.x - other.pos.x) * (this.pos.x - other.pos.x) + (this.pos.y - other.pos.y) * (this.pos.y - other.pos.y); \n\n //If touching, we change their direction\n \n if (d == (this.r + other.r) * (this.r + other.r)){\n this.dir.rotate(0.01 * 2 * PI);\n other.dir.rotate(0.01 * 2 * PI);\n }\n \n // If overlapping, they will move away from their centers;\n if (d < (this.r + other.r) * (this.r + other.r)){\n \n \n this.dir.x = this.pos.x - other.pos.x;\n this.dir.y = this.pos.y - other.pos.y;\n this.dir.normalize();\n \n //To avoid double counting, we change also the direction of the other Element\n\n other.dir = this.dir.copy();\n other.dir.mult(-1);\n \n this.visualize(other, d);\n}\n\n }\n\n //Use this for debugging purpouses;\n\n this.show = function(){\n stroke(0, 255);\n ellipse(this.pos.x, this.pos.y, this.r * 2, this.r * 2);\n line(this.pos.x + this.dir.x * this.r, this.pos.y + this.dir.y * this.r, this.pos.x, this.pos.y);\n }\n\n // Check if the Element touches the edges, in which case it bounces back;\n\n this.bounce = function(){\n if (this.pos.x < this.r){\n this.pos.x = this.r;\n this.vel.x = -this.vel.x;\n\n }\n\n if (this.pos.x > width - this.r){\n this.pos.x = width - this.r;\n this.vel.x = -this.vel.x;\n\n }\n\n if (this.pos.y < this.r){\n this.pos.y = this.r;\n this.vel.y = -this.vel.y;\n\n }\n\n if (this.pos.y > height - this.r){\n this.pos.y = height - this.r;\n this.vel.y = -this.vel.y;\n\n }\n }\n \n /*Define visualization: draw a line between the centers when they overlap; the distance between\n the centers controls the thickness of the line;\n */\n \n this.visualize = function(other, d){\n var c = map(d, 0, (this.r + other.r) * (this.r + other.r), 1, 0.5);\n noFill();\n strokeWeight(c * 2);\n stroke(lerpColor(this.color, other.color, 0.5));\n line(this.pos.x, this.pos.y, other.pos.x, other.pos.y);\n\n\n }\n}", "function collision() {\n let impact = edge.NONE;\n\n if (y+size >= height) impact = edge.BOTTOM;\n if (y-size <= 0) impact = edge.TOP;\n if (x+size >= width) impact = edge.RIGHT;\n if (x-size <= 0) impact = edge.LEFT;\n\n if (impact === edge.NONE) {\n // no collision detected\n return;\n }\n\n // get correct orientation of collision (base is BOTTOM)\n let cx = 0;\n let cy = 0;\n if (impact === edge.BOTTOM) {\n cx = dx;\n cy = dy;\n } else if (impact === edge.TOP) {\n cx = -dx;\n cy = -dy;\n } else if (impact === edge.LEFT) {\n cx = dy;\n cy = -dx;\n } else if (impact === edge.RIGHT) {\n cx = -dy;\n cy = dx;\n }\n\n // get angle of impact (in [-90, 90])\n let theta = Math.abs(Math.atan2(cy, cx) / Math.PI * 180);\n if (theta > 90) theta -= 90;\n if (theta < -90) theta += 90;\n\n // make coefficient of restitution vary in [-1,1] for AOIs in [-90,90] degrees\n let ex = -(90 - theta)/90 + theta/90;\n\n // =======================================================================================================\n // calculate new velocities\n // see: https://pdfs.semanticscholar.org/5a4a/c4105406ff2055344e943093687002da8513.pdf\n cy = -ey * cy;// - (1 + ey)*sy;\n cx = ((1 - alpha*ex) / (1 + alpha)) * cx + alpha * (1 + ex) / (1 + alpha) * ((size/scale) * dr);\n dr = ((alpha - ex) / (1 + alpha)) * dr + (1 + ex) / (1 + alpha) * (cx/scale) / (size/scale);\n // =======================================================================================================\n\n // reverse orientation\n if (impact === edge.BOTTOM) {\n dx = cx;\n dy = cy;\n } else if (impact === edge.TOP) {\n dx = -cx;\n dy = -cy;\n } else if (impact === edge.LEFT) {\n dx = -cy;\n dy = cx;\n } else if (impact === edge.RIGHT) {\n dx = cy;\n dy = -cx;\n }\n}" ]
[ "0.6880175", "0.6743808", "0.66726935", "0.6667265", "0.6661963", "0.65212256", "0.6485141", "0.64675665", "0.64594316", "0.6438658", "0.6372675", "0.6301188", "0.6300236", "0.6289286", "0.6287253", "0.62800753", "0.62685823", "0.62571645", "0.6256001", "0.62412816", "0.62404495", "0.6226857", "0.6175413", "0.6149319", "0.61472255", "0.6145526", "0.6102184", "0.6086606", "0.6062549", "0.6041288", "0.6024049", "0.60215265", "0.60199755", "0.60071695", "0.599877", "0.59980655", "0.59823394", "0.59681004", "0.5959416", "0.59544003", "0.59462094", "0.5939586", "0.5923891", "0.59206223", "0.5898581", "0.587797", "0.5854292", "0.584757", "0.58466935", "0.5842811", "0.5826836", "0.5822459", "0.58130914", "0.5812587", "0.58107406", "0.57890964", "0.5787109", "0.57857233", "0.5783052", "0.5782326", "0.5775129", "0.5774066", "0.577375", "0.57721305", "0.5766924", "0.57613224", "0.57611686", "0.57532436", "0.5737381", "0.57371235", "0.5736062", "0.5720672", "0.5713598", "0.5713497", "0.5707345", "0.5705402", "0.5701922", "0.5700345", "0.56927764", "0.5682051", "0.566268", "0.56599975", "0.56572855", "0.56514585", "0.5647755", "0.56445634", "0.564421", "0.5635306", "0.5633593", "0.5633291", "0.56280035", "0.56276816", "0.56144994", "0.5603685", "0.56008613", "0.55907696", "0.55906785", "0.558841", "0.5587312", "0.5586852" ]
0.64430106
9
Get selected text on Title button click
function getSelectedText1() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection) { text = document.selection.createRange().text; } if (tFlag === 0) { var a = String('<title id="' + text + '">'); data_arr.push(a); tFlag = 1; } else { if (mpFlag === 0) { data_arr.push(String('</title>')); tFlag = 0; var a = String('<title id="' + text + '">'); data_arr.push(a); tFlag = 1; } else { data_arr.push(String('</mp>')); data_arr.push(String('</title>')); tFlag = 0; mpFlag = 0; var a = String('<title id="' + text + '">'); data_arr.push(a); tFlag = 1; } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "getSelectedText() {\n return window.getSelection().toString();\n }", "function getSelectedText() {\n return getSelectedTextAndRange()[0];\n}", "function getSelectedText() {\n var text = \"\";\n if (typeof window.getSelection != \"undefined\") {\n text = window.getSelection().toString();\n \n \n } else if (typeof document.selection != \"undefined\" && document.selection.type == \"Text\") {\n text = document.selection.createRange().text;\n \n \n }\n return text;\n }", "selectText(i) {\n const input = document.getElementById(\"titleBox-\" + this.props.category + i);\n input.focus();\n input.select();\n }", "function getSelectedText() {\n\tif(window.getSelection){\n \treturn window.getSelection().toString();\n }else if (document.getSelection){\n\t\treturn document.getSelection.toString();\n\t\t\n\t}\n\n\n return \"\";\n}", "function getGraphTitleFtn() {\n return obj.selected;\n }", "function getGraphTitleFtn() {\n return obj.selected;\n }", "function getSelectedText() {\n var text = \"\";\n if (typeof window.getSelection != \"undefined\") {\n text = window.getSelection().toString();\n } else if (typeof document.selection != \"undefined\" && document.selection.type == \"Text\") {\n text = document.selection.createRange().text;\n }\n return text;\n}", "function getSelectedText() {\r\n if (window.getSelection) {\r\n return window.getSelection();\r\n }\r\n else if (document.selection) {\r\n return document.selection.createRange().text;\r\n }\r\n return '';\r\n}", "function getSelText()\n{\n if (window.getSelection){\n return window.getSelection();\n } else if (document.getSelection) {\n return document.getSelection();\n }else if (document.selection){\n return document.selection.createRange().text;\n }else\n return;\n}", "function getSelectionText(){\n var selectedText = \"\"\n if (window.getSelection){ // all modern browsers and IE9+\n selectedText = window.getSelection().toString()\n }\n return selectedText\n }", "function selectText3() {\n if (window.getSelection) {\n theText = window.getSelection().toString();\n alert(theText);\n } else if (document.getSelection) {\n theText = document.getSelection();\n alert(theText);\n } else if (document.getSelection && document.selection.createRange) {\n theText = document.selection.createRange().text;\n alert(theText);\n } \n}", "function changeCustomSelectTitle(event) {\n let selectedItem = event.currentTarget;\n let selection = event.currentTarget.parentNode.parentNode.previousElementSibling;\n let title = event.currentTarget.parentNode.parentNode.firstElementChild;\n selection.selectedIndex = parseInt(selectedItem.dataset.index);\n title.textContent = selectedItem.dataset.value;\n}", "function getSelectedText() {\n\t if (window.getSelection) {\n\t return window.getSelection();\n\t }\n\t else if (document.selection) {\n\t return document.selection.createRange().text;\n\t }\n\t return '';\n\t}", "function getSelectionText() {\n var text = \"\";\n var activeEl = document.activeElement;\n var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;\n if (\n (activeElTagName == \"p\") ||\n (typeof activeEl.selectionStart == \"number\")\n ) {\n text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);\n } else if (window.getSelection) {\n text = window.getSelection().toString();\n }\n return text\n}", "getSelection() {\n return this._selectionService ? this._selectionService.selectionText : '';\n }", "function getSelectedText () {\n let selection = window.getSelection();\n let selectedText = selection.toString().trim();\n\n if (selectedText.length && selection.isCollapsed === false) {\n return selectedText;\n } else {\n return null;\n }\n }", "function selectedText() {\n\t\treturn e.session.getTextRange(e.getSelectionRange())\n\t}", "getSelection(){\n return this.win.getSelection();\n }", "function handTitleClick() {\n console.log('title was clicked!');\n}", "function getSelectedText() {\n let txt = \"\";\n let selection = window.getSelection();\n if (selection !== null) {\n txt = selection.toString();\n }\n if (txt === \"\" && document.activeElement.value !== undefined) {\n txt = document.activeElement.value.substring(document.activeElement.selectionStart, document.activeElement.selectionEnd);\n }\n if (txt === \"\") {\n txt = document.body.innerText;\n }\n return txt;\n}", "function showSelection(){\n let selection = window.getSelection();\n alert(selection);\n}", "function getSelected() {\n if(window.getSelection) { \n \treturn window.getSelection(); \n } else if(document.getSelection) { \n \treturn document.getSelection(); \n }else {\n var selection = document.selection && document.selection.createRange();\n if(selection.text) { \n \treturn selection.text; \n }\n return \"\";\n }\n return \"\";\n}", "function get_selection()\n {\n return selection;\n }", "function otherTitleSelected () {\n if ($(\"#title :selected\").text() === \"Other\") {\n $(\"#other-title\").show();\n } else {\n $(\"#other-title\").hide();\n }\n}", "function frankerCoreGetSelectedText(doc, trim) {\n\tvar selection = doc.getSelection();\n\treturn (trim) ? frankerUtilTrimString(selection + \"\") : selection + \"\";\n}", "selectText(){\r\n this.getRef('input').selectText();\r\n }", "function getSelectionText(){\n var text = \"\";\n if (window.getSelection) {\n text = window.getSelection().toString();\n } else if (document.selection && document.selection.type != \"Control\") {\n text = document.selection.createRange().text;\n }\n return text;\n}", "function getSelectedText() {\r\n var txt = '';\r\n if (window.getSelection) {\r\n txt = window.getSelection();\r\n }\r\n else if (document.getSelection) // FireFox\r\n {\r\n txt = document.getSelection() + \"\";\r\n }\r\n else if (document.selection) // IE 6/7\r\n {\r\n txt = document.selection.createRange().text;\r\n }\r\n return txt;\r\n\r\n}", "function getDesc(selection) {\n //let txtSelected = selection.selectedIndex;\n let expName =\n \"Experiment Name: \" + selection.options[selection.selectedIndex].text;\n let description =\n \"Some description for \" +\n selection.options[selection.selectedIndex].text +\n \"...\";\n document.getElementById(\"expname\").innerHTML = expName;\n document.getElementById(\"description\").innerHTML = description;\n}", "function selectedText() {\n var selection = '';\n if (window.getSelection) {\n selection = window.getSelection();\n } else if (document.selection) { // Opera\n selection = document.selection.createRange();\n }\n if (selection.text) {\n selection = selection.text;\n } else if (selection.toString) {\n selection = selection.toString();\n }\n return selection;\n }", "getSelectedSubject(){\n return this.selectedSubject.getText();\n }", "static get tag(){return\"rich-text-editor-selection\"}", "function getSelectionText() {\n var text = \"\";\n if (window.getSelection) {\n text = window.getSelection().toString();\n } else if (document.selection && document.selection.type != \"Control\") {\n text = document.selection.createRange().text;\n }\n return text;\n}", "function getSelectionText() {\n var text = \"\";\n if (window.getSelection) {\n text = window.getSelection().toString();\n } else if (document.selection && document.selection.type != \"Control\") {\n text = document.selection.createRange().text;\n }\n return text;\n}", "function getSelectedTextFromPage() {\n //console.log(\"getSelectedTextFromPage start...\");\n //console.log(window.getSelection.toString());\n\n if(window.getSelection){\n // this technique is the most likely to be standardized.\n // getSelection() returns a Selection object\n //console.log(window.getSelection().toString());\n return window.getSelection().toString();\n } else if(document.getSelection){\n //this is an older,simpler technique that returns a string\n return document.getSelection();\n }else if (document.selection){\n // this is the IE-specific technique.\n return document.selection.createRange().text;\n }\n}", "function fnGetSelectedText() {\n var _dom = document.activeElement;\n var _sel = { text: \"\", slice: \"\", start: -1, end: -1 };\n if (window.getSelection) {\n // Get selected text from input fields\n if (input.isText(_dom)) {\n _sel.start = _dom.selectionStart;\n _sel.end = _dom.selectionEnd;\n if (_sel.end > _sel.start) {\n _sel.text = _dom.value.substring(_sel.start, _sel.end);\n _sel.slice = _dom.value.slice(0, _sel.start) + _dom.value.slice(_sel.end);\n }\n }\n // Get selected text from document\n else _sel.text = window.getSelection().toString();\n } else if (document.selection.createRange)\n _sel.text = document.selection.createRange().text;\n if (_sel.text !== \"\") _sel.text = $.trim(_sel.text);\n return _sel;\n }", "function getSelection(){\n return selection;\n }", "function addTitleEvent(button, title) {\n button.addEventListener('click', () => {\n setProjectActive(title);\n console.log(`selected project: ${title}`);\n });\n}", "function displaySelectedTextDialog( event ) \n {\n if (! (element && element == this)) \n {\n return;\n }\n element = null;\n \n var selectedText = getSelectedText();\n if ( '' == selectedText ) \n { \n return;\n }\n selectedText = cleanText(selectedText);\n \n var $container = makeDialog(selectedText, event);\n selectTextAgain($container);\n }", "function getSelectedText(select2_) {\n var select2 = _getSelect2(select2_);\n var data = select2.select2('data');\n if (!data || !data[0])\n return \"\";\n var res = data[0].text;\n return res;\n }", "function addListenerH3Title() {\n const listOfTitles = document.querySelectorAll('h3');\n\n for (const title of listOfTitles) {\n title.addEventListener('click', (event) => {\n const target = event.target;\n // hide the title.\n target.style.display = 'none';\n // show the input with focus and pick current value from h3\n target.parentNode.querySelector('input').style.display = \"inline-block\";\n target.parentNode.querySelector('input').focus();\n target.parentNode.querySelector('input').value = title.textContent;\n });\n }\n}", "function choiceSelectHandler(el) {\n console.log(el.innerText)\n}", "function getSel() {\r\n var mySel = '';\r\n if (window.getSelection) {\r\n mySel = window.getSelection();\r\n } else if (document.getSelection) {\r\n mySel = document.getSelection();\r\n } else if (document.selection) {\r\n mySel = document.selection.createRange().text;\r\n }\r\n return mySel; \r\n }", "function getButtonText() {\n return 'Click on me!';\n}", "function getSelectedText3() {\r\n var text = \"\";\r\n if (window.getSelection) {\r\n text = window.getSelection().toString();\r\n } else if (document.selection) {\r\n text = document.selection.createRange().text;\r\n }\r\n var a = String('<sp>' + text + '</sp>');\r\n data_arr.push(a);\r\n}", "handleClick(i) {\n const name = document.getElementById(\"title-\"+ this.props.category + i).innerHTML; \n document.getElementById(\"titleChange-\" + this.props.category + i).className = \"displayed titleChangeBox\";\n document.getElementById(\"dimmer\").className=\"displayed\";\n this.selectText(i); \n this.setState({ taskTitle: name}); \n }", "function selectionHandler ( info, tab ) {\n sendItem( { 'message': info.selectionText } );\n}", "function onClickHandler(info, tab) {\n\tvar itemId = info.menuItemId;\n\tvar context = itemId.split('_', 1)[0];\n\t\n\tswitch (context) {\n\t\tcase 'selection':\n\t\t\tif (info.selectionText.length > 0) {\n\t\t\t\tconsole.log(JSON.stringify(info.selectionText));\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tconsole.log('Other context than selection');\n\t}\n\t\n\n}", "function gText(e) {\n displayValue = (document.all) ? document.selection.createRange().text : document.getSelection();\n document.getElementById('input').value = displayValue \n}", "function displayTitle (event) {\n $display.textContent = listoftitles[event.target.getAttribute('id')-1]\n }", "function getDataFromSelection() {\n Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,\n\t\t\tfunction (result) {\n\t\t\t if (result.status === Office.AsyncResultStatus.Succeeded) {\n\t\t\t app.showNotification('The selected text is:', '\"' + result.value + '\"');\n\t\t\t } else {\n\t\t\t app.showNotification('Error:', result.error.message);\n\t\t\t }\n\t\t\t}\n\t\t);\n }", "function copy(){\nif (!window.x) {\n x = {};\n}\nx.Selector = {};\nx.Selector.getSelected = function() {\n var t = '';\n if (window.getSelection) {\n t = window.getSelection();\n } else if (document.getSelection) {\n t = document.getSelection();\n } else if (document.selection) {\n t = document.selection.createRange().text;\n }\n return t;\n}\nvar mytext = x.Selector.getSelected();\ndocument.getElementById(\"book\").innerHTML =mytext;\n}", "function textdumper_getSelection() {\r\n var selectionText = \"\";\r\n var trywindow = false;\r\n\r\n var focusedElement = document.commandDispatcher.focusedElement;\r\n if (focusedElement && null != focusedElement) {\r\n try {\r\n selectionText = focusedElement.value.substring(\r\n focusedElement.selectionStart, focusedElement.selectionEnd);\r\n } catch (exc) {\r\n trywindow = true;\r\n }\r\n } else {\r\n trywindow = true;\r\n }\r\n\r\n if (trywindow) {\r\n var focusedWindow = document.commandDispatcher.focusedWindow;\r\n try {\r\n var winWrapper = new XPCNativeWrapper(focusedWindow, 'document',\r\n 'getSelection()');\r\n var selection = winWrapper.getSelection();\r\n } catch (exc) {\r\n var selection = focusedWindow.getSelection();\r\n }\r\n\r\n selectionText = selection.toString();\r\n }\r\n\r\n return selectionText;\r\n}", "function getSelectionText() {\n var text = \"\";\n if (window.getSelection) {\n text = window.getSelection().toString(); // non IE\n } else if (document.selection && document.selection.type != \"Control\") {\n text = document.selection.createRange().text; // for IE\n }\n return text;\n\t}", "function buttonText(){\n return document.getElementById(\"go-button\").innerText;\n}", "retriveText() {\n let exactText;\n let currentElement;\n if (!isNullOrUndefined(this.currentContextInfo) && this.currentContextInfo.element) {\n currentElement = this.currentContextInfo.element;\n exactText = this.currentContextInfo.element.text;\n this.viewer.selection.start = currentElement.start;\n this.viewer.selection.end = currentElement.end;\n }\n else {\n let startPosition = this.viewer.selection.start;\n let offset = startPosition.offset;\n let startIndex = 0;\n let startInlineObj = startPosition.currentWidget.getInline(offset, startIndex);\n currentElement = startInlineObj.element;\n exactText = startInlineObj.element.text;\n }\n return { 'text': exactText, 'element': currentElement };\n }", "function getSelection() {\n\n if ((\"\" + document.activeElement.name).indexOf('label') > -1 ||\n (\"\" + document.activeElement.name).indexOf('name') > -1)\n return '';\n\n var result = '' + self.document.getSelection().toString();\n var iframes = document.querySelectorAll(\"iframe\");\n if (!iframes.length && document.querySelector(\"[global-navigation-config]\")) //try to find iframe in case of polaris\n iframes = document.querySelector(\"[global-navigation-config]\").shadowRoot.querySelectorAll(\"iframe\");\n\n iframes.forEach(frame => {\n\n try {\n result += frame.contentWindow.getSelection().toString();\n } catch (error) {\n console.log(error);\n }\n });\n return '' + result;\n}", "function getHighlightedText() {\n let acronym = window.getSelection().toString()\n acronym = acronym.trim();\n console.log(acronym);\n if (!/\\w+/.test(acronym)) {\n return '';\n }\n return acronym;\n}", "function copySelectedHtmlText() {\n commonLookup.getUserTltSetting().then((tlt) => {\n let txt = \"\";\n if (!tlt.userTltSetting.htmltextFormatWithoutTag) { \n txt = getSelectedObject().innerHTML;\n }\n else {\n txt = getSelectedObject().innerText;\n }\n copyToClipboard(txt);\n });\n}", "function checkSelectedText(e) {\n var selectedText = (document.all)\n ? document.selection.createRange().text\n : document.getSelection();\n if (selectedText.toString().length > 0) {\n //node of selected text\n var node = selectedText.baseNode.parentElement;\n if (node.classList.contains(\"asc-selectable-text\")) {\n editMenuClick(e, node);\n }\n } else {\n hideEditMenu(e);\n }\n }", "function GetSelectedText() {\n const documentText = vscode.window.activeTextEditor.document.getText();\n if (!documentText) {\n return \"\";\n }\n let activeSelection = vscode.window.activeTextEditor.selection;\n if (activeSelection.isEmpty) {\n return \"\";\n }\n const selStartoffset = vscode.window.activeTextEditor.document.offsetAt(\n activeSelection.start\n );\n const selEndOffset = vscode.window.activeTextEditor.document.offsetAt(\n activeSelection.end\n );\n\n let selectedText = documentText.slice(selStartoffset, selEndOffset).trim();\n selectedText = selectedText.replace(/\\s\\s+/g, \" \");\n return selectedText;\n}", "function getSelectDataTitle(name) {\n var e = document.getElementById(name);\n var value = e.options[e.selectedIndex].text;\n return value;\n}", "function getSelectedText2() {\r\n var text = \"\";\r\n if (window.getSelection) {\r\n text = window.getSelection().toString();\r\n } else if (document.selection) {\r\n text = document.selection.createRange().text;\r\n }\r\n\r\n if (mpFlag === 0) {\r\n var a = String('<mp id=\"' + text + '\">');\r\n data_arr.push(a);\r\n mpFlag = 1;\r\n }\r\n else {\r\n data_arr.push(String('</mp>'));\r\n mpFlag = 0;\r\n var a = String('<mp id=\"' + text + '\">');\r\n data_arr.push(a);\r\n mpFlag = 1;\r\n }\r\n}", "getSelectionGroupTitle() {\n return this.selectionGroupTitle;\n }", "function titleClick() {\n (function () {\n /*\n Optional text might be provided, affecting the Array index of what is stored\n\n 0: CZO selection\n 1: Topics\n 2: Optional text (or Location)\n 3: Location (or Dates if Optional text was provided in 2)\n 4: Dates (if Optional text was provided in 2)\n */\n let sections = $(\"#txt-title\").val().split(\" -- \");\n let topics;\n let yearsSection;\n\n if (!this.$data.title) { // don't repopulate modal if user never browsed away; UI will already contain previous selections\n if (sections.length === 5) { // title contains optional subtopic\n this.$data.regionSelected = sections[0];\n topics = sections[1].split(\",\");\n this.$data.subtopic = sections[2];\n this.$data.location = sections[3];\n yearsSection = sections[4]\n } else if (sections.length === 4) {\n this.$data.regionSelected = sections[0];\n topics = sections[1].split(\",\");\n this.$data.location = sections[2];\n yearsSection = sections[3];\n }\n\n if (sections.length === 4 || sections.length === 5) { // only 4 or 5 sections accepted; no other quantity is valid\n topics.forEach(function (topic) {\n this.$data.topics.selectedItems.push({value: topic.trim(), displayValue: topic.trim(), isSelected: false});\n }.bind(this));\n\n yearsSection = yearsSection.substring(1, yearsSection.length - 1).split(\"-\");\n this.$data.startYear = yearsSection[0];\n this.$data.endYear = yearsSection[1];\n if (this.$data.endYear === \"Ongoing\") {\n $(\"#end-date-ongoing\").prop(\"checked\", true)\n }\n this.itemMoved();\n }\n }\n if (!this.subtopic) {\n this.$data.subtopic = 'clear';\n this.$data.subtopic = '';\n }\n $(\"#title-modal\").modal('show');\n }.bind(TitleAssistantApp)());\n}", "function changeColorTitle(event) {\n let clickedColor = event.currentTarget;\n clickedColor.parentNode.previousElementSibling.lastElementChild.textContent = clickedColor.dataset.title;\n}", "copySelectedCellValue() {\n var txtView = new latte.TextView();\n txtView.text = this.selectedCell.text();\n var btnOk = new latte.ButtonItem();\n btnOk.text = strings.ok;\n var d = new latte.DialogView(txtView, [btnOk]);\n d.show();\n txtView.textElement.focus();\n txtView.textElement.select();\n }", "'click .js-title-edit-button'( e, t ) {\n e.preventDefault();\n TTL.titleEditText( e, t, P );\n//---------------------------------------------------------\n }", "function getSelectedText()\n {\n var result;\n if ($.browser.msie)\n {\n result = document.selection.createRange().htmlText;\n }\n else\n {\n var selection = window.getSelection();\n var range = selection.getRangeAt(0);\n selection = selection.toString();\n range = range.toString();\n //selection works for line numbers on, range otherwise\n result = /\\n/.test(selection) ? selection : range;\n }\n return result;\n }", "function tagItem1(){\r\n var current = getCurrentEntry();\r\n var currentEntry = current.getElementsByTagName(\"entry-tagging-action-title\")[0];\r\n // var currentEntry = $(\"#current-entry .entry-actions\r\n // .entry-tagging-action-title\");\r\n simulateClick(currentEntry);\r\n }", "function title_view(title) {\n var titleInput = gId(\"title\");\n gId('story_title').innerHTML = title;\n gId('story_title').style.display = \"block\";\n titleInput.style.display = \"none\";\n gId('add_title').style.display = \"none\";\n}", "function clickMenuCallback(info, tab) {\n console.log(\"Trying to classify text\");\n textClassifier.classifyText(info.selectionText, tab.id);\n}", "changeTitle(v) {\n this.setState({titleText: v.target.value})\n }", "function callText(){\n $(\".ShowText\").click(function(){\n $(\".box-option-click\").show();\n });\n $(\".box-option-click .third-list li a\").click(function(){\n $(\".ShowText\").text(\"\");\n var text = $(this).text();\n $(\".ShowText\").text(text);\n $(\".box-option-click\").hide();\n });\n }", "function handleClick(event) {\n alert(event.target.text);\n}", "function selectFunction() {\n let selected = document.querySelector(\"#title\").selectedIndex;\n let option = document.querySelectorAll('option');\n console.log(option[selected].value);\n}", "getSelectionData() {\n let sel = this.selection.commonAncestorContainer,\n parent = sel.tagName === \"A\" ? sel : sel.parentNode;\n if (parent.tagName === \"A\") {\n this.value.link = parent.getAttribute(\"href\");\n this.target = parent;\n } else {\n this.target = document.createElement(\"a\");\n this.target.appendChild(this.selection.extractContents());\n this.selection.insertNode(this.target);\n }\n if (!this.target.getAttribute(\"id\"))\n this.target.setAttribute(\"id\", \"prompt\" + Date.now());\n this.__style = this.style;\n this.target.style.backgroundColor = getComputedStyle(this).getPropertyValue(\n \"--rich-text-editor-selection-bg\"\n );\n this.value.text = this.target.innerHTML;\n }", "function getTitle() {\n\tlet title = $(\"#propertyTitle\").text();\n\treturn title;\n}", "function getTitle() {\n return document.getElementById( \"eow-title\" ).title;\n}", "doTextOperation(){let root=this,selection=root.selection;if(root.toggled&&null!==root.toggledCommand){document.execCommand(root.toggledCommand,!1,root.toggledCommand||\"\")}else if(null!==root.command){root.dispatchEvent(new CustomEvent(root.command+\"-button\",{bubbles:!0,cancelable:!0,composed:!0,detail:root}));document.execCommand(root.command,!1,root.commandVal||\"\");root.selection=selection}}", "function onTitleClick(e) {\n var $item = $(this).closest(_C_ITEM);\n debug(\"onTitleClick: \" + $item.attr('id'));\n\n toggleItemFolded($item, true);\n //e.stopImmediatePropagation();\n}", "_onLabelClick(ev) {\n const $target = $(ev.currentTarget);\n this.trigger('revisionSelected', [0, $target.data('revision')]);\n }", "function getTextPrecedingCurrentSelection( ctx ) {\nvar text;\nif (isSelectedElementTextAreaOrInput(ctx)) {\nvar textComponent = getDocument(ctx).activeElement;\nvar startPos = textComponent.selectionStart;\ntext = textComponent.value.substring(0, startPos);\n} else {\nvar selectedElem = getWindowSelection(ctx).anchorNode;\nif ( selectedElem !== null ) {\nvar workingNodeContent = selectedElem.textContent;\nvar selectStartOffset = getWindowSelection(ctx).getRangeAt(0).startOffset;\nif ( selectStartOffset >= 0 ) {\ntext = workingNodeContent.substring( 0, selectStartOffset );\n}\n}\n}\nreturn text;\n}", "function clickable() {\r\n var t = window.document.getElementById(\"shape_name\");\r\n t.innerHTML = this.getAttribute(\"title\");\r\n}", "function get_selected_element() {\n\n return iframe.find(\".yp-selected\");\n\n }", "function previewTitleClick(e){\n e.preventDefault();\n var entry = getEntry(e);\n if (e.ctrlKey) {\n //Ctrl+click : open in a new tab\n openEntryInNewTab(entry);\n } else {\n var btn = gfe(entry, 'btn-preview');//span\n previewize(btn, entry, locked, e);\n }\n }", "function getInputTitle() {\n return document.querySelector('input[name=\"title\"]').value;\n}", "function selectedText() {\n var selection = window.getSelection();\n return selection.type === 'Range' ? selection : false\n }", "function getTitle() {\n const title = document.querySelector('#title');\n title.addEventListener('change', (e) => {\n if (title.value !== '') {\n searchBooksObj.partialTitle = e.target.value;\n }\n });\n}", "getSelection(){\n return this.element;\n }", "function handleChangeTitle(event) {\n setTitle(event.target.value);\n }", "function getSelectedQuizName(hrefID) {\n\tvar retval = document.getElementById(hrefID).textContent;\n\tconsole.log(retval);\n\treturn retval;\n}", "function setSelectedText( $cell, control, columnIndex ){\n var $button = $cell.children( '.' + BUTTON_CLASS );\n if( $cell.hasClass( SELECTED_CLASS ) ){\n $button.html( ( control.selectedText !== undefined )?( control.selectedText ):( control.label ) );\n } else {\n $button.html( ( control.unselectedText !== undefined )?( control.unselectedText ):( control.label ) );\n }\n }", "function selectText(element) {\n\n if (document.body.createTextRange) {\n var range = document.body.createTextRange();\n range.moveToElementText(element);\n range.select();\n } else if (window.getSelection) {\n var selection = window.getSelection();\n var range = document.createRange();\n range.selectNode(element);\n selection.removeAllRanges();\n selection.addRange(range);\n }\n }", "static get BUTTON_SELECT() {\n return \"select\";\n }", "getHeaderContent() {\n const element = this.sections.modalHeader;\n I.grabTextFrom(element);\n}", "onHighlighted(fragment) {\n const text = Core.utils.htmlHelpers.highlightText(this.model.get('title'), fragment);\n this.ui.title.html(text);\n }", "get title() {\n return this.getText('title');\n }", "get title() {\n return this.getText('title');\n }" ]
[ "0.7160881", "0.69038504", "0.68798363", "0.6838814", "0.6703329", "0.6686906", "0.6686906", "0.65892845", "0.6555423", "0.65261877", "0.6504765", "0.6497718", "0.6451045", "0.6429562", "0.64286363", "0.6407339", "0.6403446", "0.6402466", "0.6397058", "0.6316844", "0.6309171", "0.6308207", "0.62562203", "0.62480307", "0.6239587", "0.6220019", "0.6192557", "0.61818475", "0.6167682", "0.61564094", "0.61448485", "0.6136136", "0.61179596", "0.6111117", "0.6111117", "0.6092876", "0.60680807", "0.6050972", "0.6044449", "0.60340124", "0.60308105", "0.60242474", "0.60149205", "0.59870285", "0.5983548", "0.5961614", "0.5958631", "0.59562147", "0.5953375", "0.59472686", "0.59436524", "0.5931862", "0.5928443", "0.5925224", "0.592266", "0.5909239", "0.5894939", "0.58847374", "0.5877013", "0.5862618", "0.5855096", "0.58512306", "0.5849699", "0.5827483", "0.5805085", "0.5802036", "0.57973564", "0.57967377", "0.57877934", "0.5786856", "0.57853603", "0.57839316", "0.57793605", "0.5778948", "0.57772845", "0.5772781", "0.57417977", "0.5733281", "0.5727609", "0.57201177", "0.57174295", "0.57107186", "0.5694111", "0.56876475", "0.567628", "0.56751865", "0.5671142", "0.56685627", "0.56669", "0.56635547", "0.56634504", "0.5662917", "0.5656002", "0.56558794", "0.5647033", "0.56376225", "0.5635376", "0.56350976", "0.5634023", "0.5634023" ]
0.7067919
1
Get selected text on Main Point button click
function getSelectedText2() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection) { text = document.selection.createRange().text; } if (mpFlag === 0) { var a = String('<mp id="' + text + '">'); data_arr.push(a); mpFlag = 1; } else { data_arr.push(String('</mp>')); mpFlag = 0; var a = String('<mp id="' + text + '">'); data_arr.push(a); mpFlag = 1; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "getSelectedText() {\n return window.getSelection().toString();\n }", "function getSelectedText() {\n return getSelectedTextAndRange()[0];\n}", "function getSelectedText() {\n var text = \"\";\n if (typeof window.getSelection != \"undefined\") {\n text = window.getSelection().toString();\n \n \n } else if (typeof document.selection != \"undefined\" && document.selection.type == \"Text\") {\n text = document.selection.createRange().text;\n \n \n }\n return text;\n }", "function selectedText() {\n\t\treturn e.session.getTextRange(e.getSelectionRange())\n\t}", "function getSelectedText() {\n\tif(window.getSelection){\n \treturn window.getSelection().toString();\n }else if (document.getSelection){\n\t\treturn document.getSelection.toString();\n\t\t\n\t}\n\n\n return \"\";\n}", "function showSelection(){\n let selection = window.getSelection();\n alert(selection);\n}", "function selectText3() {\n if (window.getSelection) {\n theText = window.getSelection().toString();\n alert(theText);\n } else if (document.getSelection) {\n theText = document.getSelection();\n alert(theText);\n } else if (document.getSelection && document.selection.createRange) {\n theText = document.selection.createRange().text;\n alert(theText);\n } \n}", "function getSelectionText() {\n var text = \"\";\n var activeEl = document.activeElement;\n var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;\n if (\n (activeElTagName == \"p\") ||\n (typeof activeEl.selectionStart == \"number\")\n ) {\n text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);\n } else if (window.getSelection) {\n text = window.getSelection().toString();\n }\n return text\n}", "function getSelectedText() {\n var text = \"\";\n if (typeof window.getSelection != \"undefined\") {\n text = window.getSelection().toString();\n } else if (typeof document.selection != \"undefined\" && document.selection.type == \"Text\") {\n text = document.selection.createRange().text;\n }\n return text;\n}", "getSelection(){\n return this.win.getSelection();\n }", "function get_selection()\n {\n return selection;\n }", "function getSelectedText() {\r\n if (window.getSelection) {\r\n return window.getSelection();\r\n }\r\n else if (document.selection) {\r\n return document.selection.createRange().text;\r\n }\r\n return '';\r\n}", "function onSelected() {\n let selection = window.getSelection();\n if (selection.toString().trim()) {\n // console.log(selection);\n selectedNode = selection.anchorNode;\n selectedRect = selection.getRangeAt(0).getBoundingClientRect();\n } \n}", "function getSelectionText(){\n var selectedText = \"\"\n if (window.getSelection){ // all modern browsers and IE9+\n selectedText = window.getSelection().toString()\n }\n return selectedText\n }", "function getSelectedText() {\n\t if (window.getSelection) {\n\t return window.getSelection();\n\t }\n\t else if (document.selection) {\n\t return document.selection.createRange().text;\n\t }\n\t return '';\n\t}", "function getSelText()\n{\n if (window.getSelection){\n return window.getSelection();\n } else if (document.getSelection) {\n return document.getSelection();\n }else if (document.selection){\n return document.selection.createRange().text;\n }else\n return;\n}", "function getSelection(){\n return selection;\n }", "function getSelectedText3() {\r\n var text = \"\";\r\n if (window.getSelection) {\r\n text = window.getSelection().toString();\r\n } else if (document.selection) {\r\n text = document.selection.createRange().text;\r\n }\r\n var a = String('<sp>' + text + '</sp>');\r\n data_arr.push(a);\r\n}", "function getSelected() {\n if(window.getSelection) { \n \treturn window.getSelection(); \n } else if(document.getSelection) { \n \treturn document.getSelection(); \n }else {\n var selection = document.selection && document.selection.createRange();\n if(selection.text) { \n \treturn selection.text; \n }\n return \"\";\n }\n return \"\";\n}", "function getTextPrecedingCurrentSelection( ctx ) {\nvar text;\nif (isSelectedElementTextAreaOrInput(ctx)) {\nvar textComponent = getDocument(ctx).activeElement;\nvar startPos = textComponent.selectionStart;\ntext = textComponent.value.substring(0, startPos);\n} else {\nvar selectedElem = getWindowSelection(ctx).anchorNode;\nif ( selectedElem !== null ) {\nvar workingNodeContent = selectedElem.textContent;\nvar selectStartOffset = getWindowSelection(ctx).getRangeAt(0).startOffset;\nif ( selectStartOffset >= 0 ) {\ntext = workingNodeContent.substring( 0, selectStartOffset );\n}\n}\n}\nreturn text;\n}", "function getSelectionText(){\n var text = \"\";\n if (window.getSelection) {\n text = window.getSelection().toString();\n } else if (document.selection && document.selection.type != \"Control\") {\n text = document.selection.createRange().text;\n }\n return text;\n}", "function selectedText() {\n var selection = '';\n if (window.getSelection) {\n selection = window.getSelection();\n } else if (document.selection) { // Opera\n selection = document.selection.createRange();\n }\n if (selection.text) {\n selection = selection.text;\n } else if (selection.toString) {\n selection = selection.toString();\n }\n return selection;\n }", "function textdumper_getSelection() {\r\n var selectionText = \"\";\r\n var trywindow = false;\r\n\r\n var focusedElement = document.commandDispatcher.focusedElement;\r\n if (focusedElement && null != focusedElement) {\r\n try {\r\n selectionText = focusedElement.value.substring(\r\n focusedElement.selectionStart, focusedElement.selectionEnd);\r\n } catch (exc) {\r\n trywindow = true;\r\n }\r\n } else {\r\n trywindow = true;\r\n }\r\n\r\n if (trywindow) {\r\n var focusedWindow = document.commandDispatcher.focusedWindow;\r\n try {\r\n var winWrapper = new XPCNativeWrapper(focusedWindow, 'document',\r\n 'getSelection()');\r\n var selection = winWrapper.getSelection();\r\n } catch (exc) {\r\n var selection = focusedWindow.getSelection();\r\n }\r\n\r\n selectionText = selection.toString();\r\n }\r\n\r\n return selectionText;\r\n}", "function fnGetSelectedText() {\n var _dom = document.activeElement;\n var _sel = { text: \"\", slice: \"\", start: -1, end: -1 };\n if (window.getSelection) {\n // Get selected text from input fields\n if (input.isText(_dom)) {\n _sel.start = _dom.selectionStart;\n _sel.end = _dom.selectionEnd;\n if (_sel.end > _sel.start) {\n _sel.text = _dom.value.substring(_sel.start, _sel.end);\n _sel.slice = _dom.value.slice(0, _sel.start) + _dom.value.slice(_sel.end);\n }\n }\n // Get selected text from document\n else _sel.text = window.getSelection().toString();\n } else if (document.selection.createRange)\n _sel.text = document.selection.createRange().text;\n if (_sel.text !== \"\") _sel.text = $.trim(_sel.text);\n return _sel;\n }", "getSelection() {\n return this._selectionService ? this._selectionService.selectionText : '';\n }", "function gText(e) {\n displayValue = (document.all) ? document.selection.createRange().text : document.getSelection();\n document.getElementById('input').value = displayValue \n}", "function getSelectedText () {\n let selection = window.getSelection();\n let selectedText = selection.toString().trim();\n\n if (selectedText.length && selection.isCollapsed === false) {\n return selectedText;\n } else {\n return null;\n }\n }", "function handleMouseDown(e) {\n $(\"#submitTextOnCanvas\").css(\"background\",\"green\");\n $(\"#submitTextOnCanvas\").css(\"color\",\"white\");\n $(\"#hint\").html(\"Then click 'Save'\");\n e.preventDefault();\n text_startX = parseInt(e.clientX - text_canvas.offset().left);\n text_startY = parseInt(e.clientY - text_canvas.offset().top);\n // Put your mousedown stuff here\n for (var i = 0; i < texts.length; i++) {\n if (textHittest(text_startX, text_startY, i)) {\n console.log(\"text-e\");\n \n selectedText = i;\n }\n }\n }", "doTextOperation(){let root=this,selection=root.selection;if(root.toggled&&null!==root.toggledCommand){document.execCommand(root.toggledCommand,!1,root.toggledCommand||\"\")}else if(null!==root.command){root.dispatchEvent(new CustomEvent(root.command+\"-button\",{bubbles:!0,cancelable:!0,composed:!0,detail:root}));document.execCommand(root.command,!1,root.commandVal||\"\");root.selection=selection}}", "function getSelectedText() {\r\n var txt = '';\r\n if (window.getSelection) {\r\n txt = window.getSelection();\r\n }\r\n else if (document.getSelection) // FireFox\r\n {\r\n txt = document.getSelection() + \"\";\r\n }\r\n else if (document.selection) // IE 6/7\r\n {\r\n txt = document.selection.createRange().text;\r\n }\r\n return txt;\r\n\r\n}", "function getSelectionText() {\n var text = \"\";\n if (window.getSelection) {\n text = window.getSelection().toString();\n } else if (document.selection && document.selection.type != \"Control\") {\n text = document.selection.createRange().text;\n }\n return text;\n}", "function getSelectionText() {\n var text = \"\";\n if (window.getSelection) {\n text = window.getSelection().toString();\n } else if (document.selection && document.selection.type != \"Control\") {\n text = document.selection.createRange().text;\n }\n return text;\n}", "function getSelection() {\n\n if ((\"\" + document.activeElement.name).indexOf('label') > -1 ||\n (\"\" + document.activeElement.name).indexOf('name') > -1)\n return '';\n\n var result = '' + self.document.getSelection().toString();\n var iframes = document.querySelectorAll(\"iframe\");\n if (!iframes.length && document.querySelector(\"[global-navigation-config]\")) //try to find iframe in case of polaris\n iframes = document.querySelector(\"[global-navigation-config]\").shadowRoot.querySelectorAll(\"iframe\");\n\n iframes.forEach(frame => {\n\n try {\n result += frame.contentWindow.getSelection().toString();\n } catch (error) {\n console.log(error);\n }\n });\n return '' + result;\n}", "function getSelectedTextFromPage() {\n //console.log(\"getSelectedTextFromPage start...\");\n //console.log(window.getSelection.toString());\n\n if(window.getSelection){\n // this technique is the most likely to be standardized.\n // getSelection() returns a Selection object\n //console.log(window.getSelection().toString());\n return window.getSelection().toString();\n } else if(document.getSelection){\n //this is an older,simpler technique that returns a string\n return document.getSelection();\n }else if (document.selection){\n // this is the IE-specific technique.\n return document.selection.createRange().text;\n }\n}", "function getSelectedText() {\n let txt = \"\";\n let selection = window.getSelection();\n if (selection !== null) {\n txt = selection.toString();\n }\n if (txt === \"\" && document.activeElement.value !== undefined) {\n txt = document.activeElement.value.substring(document.activeElement.selectionStart, document.activeElement.selectionEnd);\n }\n if (txt === \"\") {\n txt = document.body.innerText;\n }\n return txt;\n}", "selectText(){\r\n this.getRef('input').selectText();\r\n }", "function markButton(){\n//store value of letter in the selected button \nlet selection = event.target.innerHTML; \n//pass button into games handle interaction function \ngameOne.handleInteraction(selection);\n}", "function wordPicker() {\n console.log(currentWord);\n console.log(currentWord[3]);\n }", "retriveText() {\n let exactText;\n let currentElement;\n if (!isNullOrUndefined(this.currentContextInfo) && this.currentContextInfo.element) {\n currentElement = this.currentContextInfo.element;\n exactText = this.currentContextInfo.element.text;\n this.viewer.selection.start = currentElement.start;\n this.viewer.selection.end = currentElement.end;\n }\n else {\n let startPosition = this.viewer.selection.start;\n let offset = startPosition.offset;\n let startIndex = 0;\n let startInlineObj = startPosition.currentWidget.getInline(offset, startIndex);\n currentElement = startInlineObj.element;\n exactText = startInlineObj.element.text;\n }\n return { 'text': exactText, 'element': currentElement };\n }", "function frankerCoreGetSelectedText(doc, trim) {\n\tvar selection = doc.getSelection();\n\treturn (trim) ? frankerUtilTrimString(selection + \"\") : selection + \"\";\n}", "function GetSelectedText() {\n const documentText = vscode.window.activeTextEditor.document.getText();\n if (!documentText) {\n return \"\";\n }\n let activeSelection = vscode.window.activeTextEditor.selection;\n if (activeSelection.isEmpty) {\n return \"\";\n }\n const selStartoffset = vscode.window.activeTextEditor.document.offsetAt(\n activeSelection.start\n );\n const selEndOffset = vscode.window.activeTextEditor.document.offsetAt(\n activeSelection.end\n );\n\n let selectedText = documentText.slice(selStartoffset, selEndOffset).trim();\n selectedText = selectedText.replace(/\\s\\s+/g, \" \");\n return selectedText;\n}", "function _corexitOnMouseUp(event) {\r\n\tvar selection = window.getSelection();\r\n\tvar selectedText = selection ? selection.toString() : \"\";\r\n\r\n //unselect\r\n //selection.collapseToStart();\r\n\r\n\t//if (selectedText.length != 0) {\r\n chrome.extension.sendRequest({command : \"sendText\", text : selectedText});\r\n\t//}\r\n \r\n\t//gClickInTextBox = false;\r\n \r\n}", "function selectedText() {\n var selection = window.getSelection();\n return selection.type === 'Range' ? selection : false\n }", "function getDataFromSelection() {\n Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,\n\t\t\tfunction (result) {\n\t\t\t if (result.status === Office.AsyncResultStatus.Succeeded) {\n\t\t\t app.showNotification('The selected text is:', '\"' + result.value + '\"');\n\t\t\t } else {\n\t\t\t app.showNotification('Error:', result.error.message);\n\t\t\t }\n\t\t\t}\n\t\t);\n }", "copySelectedCellValue() {\n var txtView = new latte.TextView();\n txtView.text = this.selectedCell.text();\n var btnOk = new latte.ButtonItem();\n btnOk.text = strings.ok;\n var d = new latte.DialogView(txtView, [btnOk]);\n d.show();\n txtView.textElement.focus();\n txtView.textElement.select();\n }", "function getSelectedText1() {\r\n var text = \"\";\r\n if (window.getSelection) {\r\n text = window.getSelection().toString();\r\n } else if (document.selection) {\r\n text = document.selection.createRange().text;\r\n }\r\n\r\n if (tFlag === 0) {\r\n var a = String('<title id=\"' + text + '\">');\r\n data_arr.push(a);\r\n tFlag = 1;\r\n }\r\n else {\r\n if (mpFlag === 0) {\r\n data_arr.push(String('</title>'));\r\n tFlag = 0;\r\n var a = String('<title id=\"' + text + '\">');\r\n data_arr.push(a);\r\n tFlag = 1;\r\n }\r\n else {\r\n data_arr.push(String('</mp>'));\r\n data_arr.push(String('</title>'));\r\n tFlag = 0;\r\n mpFlag = 0;\r\n var a = String('<title id=\"' + text + '\">');\r\n data_arr.push(a);\r\n tFlag = 1;\r\n }\r\n }\r\n}", "function getSelectionText() {\n var text = \"\";\n if (window.getSelection) {\n text = window.getSelection().toString(); // non IE\n } else if (document.selection && document.selection.type != \"Control\") {\n text = document.selection.createRange().text; // for IE\n }\n return text;\n\t}", "function onClickHandler(info, tab) {\n\tvar itemId = info.menuItemId;\n\tvar context = itemId.split('_', 1)[0];\n\t\n\tswitch (context) {\n\t\tcase 'selection':\n\t\t\tif (info.selectionText.length > 0) {\n\t\t\t\tconsole.log(JSON.stringify(info.selectionText));\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tconsole.log('Other context than selection');\n\t}\n\t\n\n}", "function commandLine() {\n let selection = document.getSelection()\n let node = selection.anchorNode\n let text = node.textContent.slice(0, selection.focusOffset)\n return text \n}", "function selectionHandler ( info, tab ) {\n sendItem( { 'message': info.selectionText } );\n}", "function select () {\r\n\t\t\t\tthis.tool.select();\r\n\t\t\t}", "function handleMouseDown(e) {\n e.preventDefault();\n startX = parseInt(e.clientX - offsetX);\n // console.log(startX);\n startY = parseInt(e.clientY - offsetY);\n // console.log(startY);\n\n // Put your mousedown stuff here\n // for (var i = 0; i < texts.length; i++) {\n // if (textHittest(startX, startY, i)) {\n selectedText = currentIndex;\n // }\n // }\n}", "function getSel() {\r\n var mySel = '';\r\n if (window.getSelection) {\r\n mySel = window.getSelection();\r\n } else if (document.getSelection) {\r\n mySel = document.getSelection();\r\n } else if (document.selection) {\r\n mySel = document.selection.createRange().text;\r\n }\r\n return mySel; \r\n }", "function UISelection(){\n\n }", "function makeSelection(point, pSelection) {\n\t\t//alert(pSelection);\n\t\t//add clicked point to qPoint/tPoint\n\t\tif(pSelection != null){\n\t\t\tif(pSelection == 1){\n\t\t\t\tif(qPoint){\n\t\t\t\t\tqPoint.select(false, true);\n\t\t\t\t}\n\t\t\t\tqPoint = point;\n\t\t\t}\n\t\t\telse if(pSelection == 0){\n\t\t\t\tif(tPoint){\n\t\t\t\t\ttPoint.select(false, true);\n\t\t\t\t}\n\t\t\t\ttPoint = point;\n\t\t\t}\n\t\t\tpoint.select(true, true);\n\t\t} //else null without any selection, do nothing\t\n\t\tmakeQTText();\n }", "function copy(){\nif (!window.x) {\n x = {};\n}\nx.Selector = {};\nx.Selector.getSelected = function() {\n var t = '';\n if (window.getSelection) {\n t = window.getSelection();\n } else if (document.getSelection) {\n t = document.getSelection();\n } else if (document.selection) {\n t = document.selection.createRange().text;\n }\n return t;\n}\nvar mytext = x.Selector.getSelected();\ndocument.getElementById(\"book\").innerHTML =mytext;\n}", "function getSelectedText()\n {\n var result;\n if ($.browser.msie)\n {\n result = document.selection.createRange().htmlText;\n }\n else\n {\n var selection = window.getSelection();\n var range = selection.getRangeAt(0);\n selection = selection.toString();\n range = range.toString();\n //selection works for line numbers on, range otherwise\n result = /\\n/.test(selection) ? selection : range;\n }\n return result;\n }", "function showCurrentText() {\n\tunselectAll();\n\thideAll();\n\tshowAllHeaders();\n\t$(\"#pano\" + currentpanonum).addClass('selected').children().show(5,scrollTo(currentpanonum));\n}", "function buttonClicked(e) {\n\tvar element = e.memo.element;\n\tif (this.options.singleSelect) {\n\t\tthis.select(element);\n\t} else {\n\t\tif (this.isSelected(element)) {\n\t\t\tthis.deselect(element);\t\n\t\t} else {\n\t\t\tthis.select(element);\n\t\t}\n\t}\n}", "updateTextPosition(widget, point) {\n let caretPosition = point;\n let element = undefined;\n let index = 0;\n let isImageSelected = false;\n let isImageSelectedObj = this.updateTextPositionIn(widget, element, index, point, false);\n if (!isNullOrUndefined(isImageSelectedObj)) {\n element = isImageSelectedObj.element;\n index = isImageSelectedObj.index;\n caretPosition = isImageSelectedObj.caretPosition;\n isImageSelected = isImageSelectedObj.isImageSelected;\n this.isImageSelected = isImageSelected;\n }\n if (isImageSelected) {\n this.selectInternal(widget, element, index, caretPosition);\n if (index === 0) {\n this.extendForward();\n }\n else {\n this.extendBackward();\n }\n }\n else {\n this.selectInternal(widget, element, index, caretPosition);\n }\n }", "function handleClick(event) {\n alert(event.target.text);\n}", "function selectText(element) {\n\n if (document.body.createTextRange) {\n var range = document.body.createTextRange();\n range.moveToElementText(element);\n range.select();\n } else if (window.getSelection) {\n var selection = window.getSelection();\n var range = document.createRange();\n range.selectNode(element);\n selection.removeAllRanges();\n selection.addRange(range);\n }\n }", "function buttonText(){\n return document.getElementById(\"go-button\").innerText;\n}", "function selectHandler() {\n var selectedItem = chart.getSelection()[0];\n if (selectedItem) {\n var value = data.getValue(selectedItem.row, 0);\n openPopup(value);\n // console.log('The user selected - ' + value);\n }\n }", "function ShowButton(message, x, y, width, height, selection, buttonID){\n var active = selection == buttonID;\n var magicValue = 3;\n var color = active ? 'red' : 'blue';\n colorRect(x, y, width, height, color);\n var w = Math.round(width/2) - Math.round( measurePixelfont(message) / 2 );\n drawPixelfont(message, Math.round(x + w)+magicValue, Math.round( y + height/2)-3 ) ;\n\n\n //Mouse Bound Check \n if( mouseCanvasY < (y + height) && mouseCanvasY > y && mouseCanvasX < (x+width) && mouseCanvasX > x) {\n mainMenuCurrentSelection = buttonID; //note(keenan): HACK BLAH!!!\n }\n}", "function onClickHandler(info, tab) {\n\tvar text = info.selectionText;\n\tvar msg = new SpeechSynthesisUtterance(text);\n\twindow.speechSynthesis.speak(msg);\n}", "function selectHandler() {\n var selectedItem = chart.getSelection()[0];\n if (selectedItem) {\n var value = data.getValue(selectedItem.row, selectedItem.column);\n alert('The user selected ' + value);\n }\n }", "updateTextPositionForSelection(cursorPoint, tapCount) {\n let widget = this.getLineWidget(cursorPoint);\n if (!isNullOrUndefined(widget)) {\n this.selection.updateTextPosition(widget, cursorPoint);\n }\n if (tapCount > 1) {\n this.isMouseDown = false;\n this.useTouchSelectionMark = false;\n if (this.pages.length === 0) {\n return;\n }\n //Double tap/triple tap selection\n if (!isNullOrUndefined(this.currentPage) && !isNullOrUndefined(this.owner.selection.start)) {\n if (tapCount % 2 === 0) {\n this.owner.selection.selectCurrentWord();\n }\n else {\n this.owner.selection.selectParagraph();\n }\n }\n }\n }", "selectText(i) {\n const input = document.getElementById(\"titleBox-\" + this.props.category + i);\n input.focus();\n input.select();\n }", "function getSelection() {\r\n return this.window.getSelection ? this.window.getSelection() : this.document.selection;\r\n }", "function get_selected_element() {\n\n return iframe.find(\".yp-selected\");\n\n }", "function selectHandler() {\n var selectedItem = chart.getSelection()[0];\n if (selectedItem) {\n var value = data.getValue(selectedItem.row, selectedItem.column);\n alert('The user selected ' + value);\n }\n }", "function selectHandler() {\n var selectedItem = chart.getSelection()[0];\n if (selectedItem) {\n var value = data.getValue(selectedItem.row, selectedItem.column);\n alert('The user selected ' + value);\n }\n }", "function displaySelectedTextDialog( event ) \n {\n if (! (element && element == this)) \n {\n return;\n }\n element = null;\n \n var selectedText = getSelectedText();\n if ( '' == selectedText ) \n { \n return;\n }\n selectedText = cleanText(selectedText);\n \n var $container = makeDialog(selectedText, event);\n selectTextAgain($container);\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 }", "function select() {\n getElements()[selection].getElementsByTagName('a')[0].click();\n\n}", "function checkSelectedText(e) {\n var selectedText = (document.all)\n ? document.selection.createRange().text\n : document.getSelection();\n if (selectedText.toString().length > 0) {\n //node of selected text\n var node = selectedText.baseNode.parentElement;\n if (node.classList.contains(\"asc-selectable-text\")) {\n editMenuClick(e, node);\n }\n } else {\n hideEditMenu(e);\n }\n }", "function clickFunction(e){\n var currLine = getCurrentLine(this);\n num_lines_selected = 1; //returns to default, in case just clicking, if it is selected that's taken care of in subsequent onselect\n prevLine = currLine;\n}", "function _selection() {\n if (window.getSelection) {\n return window.getSelection();\n } else if (document.getSelection) {\n return document.getSelection();\n } else if (document.selection) {\n return document.selection.createRange().text;\n }\n }", "select() {\n this.getInput().select();\n }", "function current_selection() {\n return window.current_row_index;\n}", "function selectedText(editor) {\n restoreRange(editor);\n return getSelection(editor).toString();\n }", "function selectText(el) {\n var range;\n if (window.getSelection && document.createRange) {\n range = document.createRange();\n let sel = window.getSelection();\n range.selectNodeContents(el.currentTarget);\n sel.removeAllRanges();\n sel.addRange(range);\n } else if (document.body && document.body.createTextRange) {\n range = document.body.createTextRange();\n range.moveToElementText(el);\n range.select();\n }\n}", "static get tag(){return\"rich-text-editor-selection\"}", "function getHighlightedText() {\n let acronym = window.getSelection().toString()\n acronym = acronym.trim();\n console.log(acronym);\n if (!/\\w+/.test(acronym)) {\n return '';\n }\n return acronym;\n}", "function selectHandler() {\n var selectedItem = oTree.getSelection();\n if (selectedItem && selectedItem.word) {\n sRootWord = selectedItem.word;\n }\n }", "get caretPos() {\n return this.textSelection[0];\n }", "function ansClicked (eventData) {\n\tlet buttonInformation = eventData;\n\tlet ansClicked = buttonInformation.target.textContent;\n\tinsertDisplay(ansClicked);\n\t\n}", "select() {\n\t\tthis.inputView.select();\n\t}", "function buttonClick(e) {\n\tvar element = e.memo.element;\n\tif (this.options.singleSelect) {\n\t\tthis.select(element);\n\t} else {\n\t\tif (this.isSelected(element)) {\n\t\t\tthis.deselect(element);\t\n\t\t} else {\n\t\t\tthis.select(element);\n\t\t}\n\t}\n}", "function getSelectedText(select2_) {\n var select2 = _getSelect2(select2_);\n var data = select2.select2('data');\n if (!data || !data[0])\n return \"\";\n var res = data[0].text;\n return res;\n }", "getSelection(){\n return this.element;\n }", "function getDataFromSelection(){\r\n\r\n // Word.run(function (context) {\r\n\r\n // // Create a proxy object for the document body.\r\n // var body = context.document.body;\r\n\r\n // // Queue a commmand to get the HTML contents of the body.\r\n // var bodyHTML = body.getHtml();\r\n\r\n // // Synchronize the document state by executing the queued commands,\r\n // // and return a promise to indicate task completion.\r\n // return context.sync().then(function () {\r\n // console.log(\"Body HTML contents: \" + bodyHTML.value);\r\n // });\r\n // })\r\n // .catch(function (error) {\r\n // console.log(\"Error: \" + JSON.stringify(error));\r\n // if (error instanceof OfficeExtension.Error) {\r\n // console.log(\"Debug info: \" + JSON.stringify(error.debugInfo));\r\n // }\r\n // });\r\n \r\n if (!app.isNotificationClosed()) {\r\n app.closeNotification();\r\n }\r\n Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,\r\n function(result){\r\n if (result.status === Office.AsyncResultStatus.Succeeded) {\r\n if (result.value !== '') {\r\n var data = {\r\n text: result.value\r\n }\r\n app.socket.emit('data', data);\r\n }\r\n\r\n // app.showNotification('The selected text is:', '\"' + result.value + '\"');\r\n } else {\r\n app.showNotification('Error:', result.error.message);\r\n }\r\n }\r\n );\r\n\r\n }", "mouseDown(pt) {}", "mouseDown(pt) {}", "function buttonHandler(button){\r\n\tvar text = document.getElementById(\"htmlText\");\r\n\r\n\tvar tags = {\r\n\t\tbold : [\"<span class='bold'>\", \"</span>\"],\r\n\t\titalic : [\"<span class='italic'>\", \"</span>\"],\r\n\t\tunderline : [\"<span class='underline'>\", \"</span>\"],\r\n\t\timg : [\"<img class='postImg' src='' alt=''>\", \"</img>\"],\r\n\t\tlink : [\"<a class='postLink' href=''>\", \"</a>\"],\r\n\t\tquote : [\"<q class='postQuote'>\", \"</q>\"],\r\n\t\tmore : [\"<!-- more -->\", \"\"]\r\n\t};\r\n\t\r\n\tvar posI = text.selectionStart;\r\n\tvar posF = text.selectionEnd;\r\n\tvar before = text.value.substring(0, posI);\r\n\tvar after = text.value.substring(posF, text.value.length);\r\n\tvar selected = text.value.substring(posI, posF);\r\n\t\r\n\ttext.value = before + tags[button][0] + selected + tags[button][1] + after;\r\n\r\n\ttext.focus();\r\n\r\n\t//riposiziono adeguatamente il cursore\r\n\ttext.selectionStart = posI + tags[button][0].length;\r\n\ttext.selectionEnd = text.selectionStart;\r\n}", "_evtClick(event) {\n // only handle primary button clicks\n if (event.button !== 0 || this._selected) {\n return;\n }\n const inputElement = this.inputElement;\n event.preventDefault();\n event.stopPropagation();\n this._selected = true;\n const selectEnd = inputElement.value.indexOf('.');\n if (selectEnd === -1) {\n inputElement.select();\n }\n else {\n inputElement.setSelectionRange(0, selectEnd);\n }\n }", "function getSel() {\n\tvar txt = '';\n\tvar foundIn = '';\n\tdocument.getElementById('selectedblastp').innerHTML = \"\";\n\tdocument.getElementById('selectedblastnfull').innerHTML = \"\";\n\tdocument.getElementById('selectedblastncds').innerHTML = \"\";\n\t\n\tif (window.getSelection)\n\t{\n\t\ttxt = window.getSelection();\n\t\tfoundIn = 'window.getSelection()';\n\t}\n\telse if (document.getSelection)\n\t{\n\t\ttxt = document.getSelection();\n\t\tfoundIn = 'document.getSelection()';\n\t}\n\telse if (document.selection)\n\t{\n\t\ttxt = document.selection.createRange().text;\n\t\tfoundIn = 'document.selection.createRange()';\n\t}\n\telse return false;\n\t//fixtxt = txt.replace(/<br>/ig, \"\");\n\tvar fixtxt = new String(txt);\n\n\tfixtxt = fixtxt.replace(/\\W/ig, \"\");\n\tif (fixtxt.match(/^[A-Z]+$/)) {\n\t\treturn fixtxt;\n\t}\n\telse return false;\n}", "function saveSelection() {\n if (window.getSelection) {\n sel = window.getSelection();\n if (sel.getRangeAt && sel.rangeCount) {\n return sel.getRangeAt(0);\n }\n } else if (document.selection && document.selection.createRange) {\n return document.selection.createRange();\n }\n return null;\n }", "function leftButtonSelect(cm, e, start, type, addNew) {\n\t\t var display = cm.display, doc = cm.doc;\n\t\t e_preventDefault(e);\n\t\t\n\t\t var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;\n\t\t if (addNew && !e.shiftKey) {\n\t\t ourIndex = doc.sel.contains(start);\n\t\t if (ourIndex > -1)\n\t\t ourRange = ranges[ourIndex];\n\t\t else\n\t\t ourRange = new Range(start, start);\n\t\t } else {\n\t\t ourRange = doc.sel.primary();\n\t\t ourIndex = doc.sel.primIndex;\n\t\t }\n\t\t\n\t\t if (chromeOS ? e.shiftKey && e.metaKey : e.altKey) {\n\t\t type = \"rect\";\n\t\t if (!addNew) ourRange = new Range(start, start);\n\t\t start = posFromMouse(cm, e, true, true);\n\t\t ourIndex = -1;\n\t\t } else if (type == \"double\") {\n\t\t var word = cm.findWordAt(start);\n\t\t if (cm.display.shift || doc.extend)\n\t\t ourRange = extendRange(doc, ourRange, word.anchor, word.head);\n\t\t else\n\t\t ourRange = word;\n\t\t } else if (type == \"triple\") {\n\t\t var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));\n\t\t if (cm.display.shift || doc.extend)\n\t\t ourRange = extendRange(doc, ourRange, line.anchor, line.head);\n\t\t else\n\t\t ourRange = line;\n\t\t } else {\n\t\t ourRange = extendRange(doc, ourRange, start);\n\t\t }\n\t\t\n\t\t if (!addNew) {\n\t\t ourIndex = 0;\n\t\t setSelection(doc, new Selection([ourRange], 0), sel_mouse);\n\t\t startSel = doc.sel;\n\t\t } else if (ourIndex == -1) {\n\t\t ourIndex = ranges.length;\n\t\t setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),\n\t\t {scroll: false, origin: \"*mouse\"});\n\t\t } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == \"single\" && !e.shiftKey) {\n\t\t setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),\n\t\t {scroll: false, origin: \"*mouse\"});\n\t\t startSel = doc.sel;\n\t\t } else {\n\t\t replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);\n\t\t }\n\t\t\n\t\t var lastPos = start;\n\t\t function extendTo(pos) {\n\t\t if (cmp(lastPos, pos) == 0) return;\n\t\t lastPos = pos;\n\t\t\n\t\t if (type == \"rect\") {\n\t\t var ranges = [], tabSize = cm.options.tabSize;\n\t\t var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);\n\t\t var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);\n\t\t var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);\n\t\t for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));\n\t\t line <= end; line++) {\n\t\t var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);\n\t\t if (left == right)\n\t\t ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));\n\t\t else if (text.length > leftPos)\n\t\t ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));\n\t\t }\n\t\t if (!ranges.length) ranges.push(new Range(start, start));\n\t\t setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),\n\t\t {origin: \"*mouse\", scroll: false});\n\t\t cm.scrollIntoView(pos);\n\t\t } else {\n\t\t var oldRange = ourRange;\n\t\t var anchor = oldRange.anchor, head = pos;\n\t\t if (type != \"single\") {\n\t\t if (type == \"double\")\n\t\t var range = cm.findWordAt(pos);\n\t\t else\n\t\t var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));\n\t\t if (cmp(range.anchor, anchor) > 0) {\n\t\t head = range.head;\n\t\t anchor = minPos(oldRange.from(), range.anchor);\n\t\t } else {\n\t\t head = range.anchor;\n\t\t anchor = maxPos(oldRange.to(), range.head);\n\t\t }\n\t\t }\n\t\t var ranges = startSel.ranges.slice(0);\n\t\t ranges[ourIndex] = new Range(clipPos(doc, anchor), head);\n\t\t setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);\n\t\t }\n\t\t }\n\t\t\n\t\t var editorSize = display.wrapper.getBoundingClientRect();\n\t\t // Used to ensure timeout re-tries don't fire when another extend\n\t\t // happened in the meantime (clearTimeout isn't reliable -- at\n\t\t // least on Chrome, the timeouts still happen even when cleared,\n\t\t // if the clear happens after their scheduled firing time).\n\t\t var counter = 0;\n\t\t\n\t\t function extend(e) {\n\t\t var curCount = ++counter;\n\t\t var cur = posFromMouse(cm, e, true, type == \"rect\");\n\t\t if (!cur) return;\n\t\t if (cmp(cur, lastPos) != 0) {\n\t\t cm.curOp.focus = activeElt();\n\t\t extendTo(cur);\n\t\t var visible = visibleLines(display, doc);\n\t\t if (cur.line >= visible.to || cur.line < visible.from)\n\t\t setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);\n\t\t } else {\n\t\t var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;\n\t\t if (outside) setTimeout(operation(cm, function() {\n\t\t if (counter != curCount) return;\n\t\t display.scroller.scrollTop += outside;\n\t\t extend(e);\n\t\t }), 50);\n\t\t }\n\t\t }\n\t\t\n\t\t function done(e) {\n\t\t cm.state.selectingText = false;\n\t\t counter = Infinity;\n\t\t e_preventDefault(e);\n\t\t display.input.focus();\n\t\t off(document, \"mousemove\", move);\n\t\t off(document, \"mouseup\", up);\n\t\t doc.history.lastSelOrigin = null;\n\t\t }\n\t\t\n\t\t var move = operation(cm, function(e) {\n\t\t if (!e_button(e)) done(e);\n\t\t else extend(e);\n\t\t });\n\t\t var up = operation(cm, done);\n\t\t cm.state.selectingText = up;\n\t\t on(document, \"mousemove\", move);\n\t\t on(document, \"mouseup\", up);\n\t\t }" ]
[ "0.7392748", "0.7247428", "0.7093416", "0.6959516", "0.68941975", "0.68923473", "0.68259126", "0.67985296", "0.67747056", "0.67375016", "0.6694859", "0.6693119", "0.6634629", "0.6574312", "0.6568881", "0.653621", "0.6507076", "0.6485507", "0.64854485", "0.6483102", "0.64287704", "0.6422994", "0.64213604", "0.64138836", "0.6395106", "0.63901985", "0.6370556", "0.636834", "0.6349551", "0.63484687", "0.6336204", "0.6336204", "0.6330602", "0.6315749", "0.6310969", "0.63069844", "0.63056016", "0.6242118", "0.62327105", "0.62240887", "0.62139386", "0.62124", "0.6199978", "0.61958", "0.6187765", "0.6136027", "0.61330944", "0.61218596", "0.61138743", "0.61080354", "0.6088337", "0.60883296", "0.60739774", "0.6071425", "0.60646784", "0.60357136", "0.6018242", "0.6013218", "0.6012687", "0.60048735", "0.5948073", "0.5923968", "0.59129494", "0.59128916", "0.59123904", "0.5904339", "0.59040856", "0.5900668", "0.5898726", "0.5894238", "0.58879983", "0.58804065", "0.58804065", "0.58763146", "0.5875154", "0.5874136", "0.58652216", "0.586177", "0.5856573", "0.5854357", "0.58408934", "0.58284825", "0.5783425", "0.5776356", "0.57744294", "0.57738733", "0.57726985", "0.5767613", "0.57473356", "0.5747124", "0.574135", "0.5740727", "0.57124215", "0.57088494", "0.57088494", "0.57055026", "0.57044995", "0.57021266", "0.5696975", "0.5684765" ]
0.6211039
42
Get selected text on Sub Point button click
function getSelectedText3() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection) { text = document.selection.createRange().text; } var a = String('<sp>' + text + '</sp>'); data_arr.push(a); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "getSelectedText() {\n return window.getSelection().toString();\n }", "function getSelectedText() {\n return getSelectedTextAndRange()[0];\n}", "function getSelectedText() {\n var text = \"\";\n if (typeof window.getSelection != \"undefined\") {\n text = window.getSelection().toString();\n \n \n } else if (typeof document.selection != \"undefined\" && document.selection.type == \"Text\") {\n text = document.selection.createRange().text;\n \n \n }\n return text;\n }", "function selectText3() {\n if (window.getSelection) {\n theText = window.getSelection().toString();\n alert(theText);\n } else if (document.getSelection) {\n theText = document.getSelection();\n alert(theText);\n } else if (document.getSelection && document.selection.createRange) {\n theText = document.selection.createRange().text;\n alert(theText);\n } \n}", "function showSelection(){\n let selection = window.getSelection();\n alert(selection);\n}", "function selectedText() {\n\t\treturn e.session.getTextRange(e.getSelectionRange())\n\t}", "function getSelectedText() {\n\tif(window.getSelection){\n \treturn window.getSelection().toString();\n }else if (document.getSelection){\n\t\treturn document.getSelection.toString();\n\t\t\n\t}\n\n\n return \"\";\n}", "getSelection(){\n return this.win.getSelection();\n }", "function getSelectionText() {\n var text = \"\";\n var activeEl = document.activeElement;\n var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;\n if (\n (activeElTagName == \"p\") ||\n (typeof activeEl.selectionStart == \"number\")\n ) {\n text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);\n } else if (window.getSelection) {\n text = window.getSelection().toString();\n }\n return text\n}", "function get_selection()\n {\n return selection;\n }", "function onSelected() {\n let selection = window.getSelection();\n if (selection.toString().trim()) {\n // console.log(selection);\n selectedNode = selection.anchorNode;\n selectedRect = selection.getRangeAt(0).getBoundingClientRect();\n } \n}", "function getSelText()\n{\n if (window.getSelection){\n return window.getSelection();\n } else if (document.getSelection) {\n return document.getSelection();\n }else if (document.selection){\n return document.selection.createRange().text;\n }else\n return;\n}", "function getSelectedText() {\n var text = \"\";\n if (typeof window.getSelection != \"undefined\") {\n text = window.getSelection().toString();\n } else if (typeof document.selection != \"undefined\" && document.selection.type == \"Text\") {\n text = document.selection.createRange().text;\n }\n return text;\n}", "function getSelection(){\n return selection;\n }", "function getSelectionText(){\n var selectedText = \"\"\n if (window.getSelection){ // all modern browsers and IE9+\n selectedText = window.getSelection().toString()\n }\n return selectedText\n }", "function getTextPrecedingCurrentSelection( ctx ) {\nvar text;\nif (isSelectedElementTextAreaOrInput(ctx)) {\nvar textComponent = getDocument(ctx).activeElement;\nvar startPos = textComponent.selectionStart;\ntext = textComponent.value.substring(0, startPos);\n} else {\nvar selectedElem = getWindowSelection(ctx).anchorNode;\nif ( selectedElem !== null ) {\nvar workingNodeContent = selectedElem.textContent;\nvar selectStartOffset = getWindowSelection(ctx).getRangeAt(0).startOffset;\nif ( selectStartOffset >= 0 ) {\ntext = workingNodeContent.substring( 0, selectStartOffset );\n}\n}\n}\nreturn text;\n}", "function gText(e) {\n displayValue = (document.all) ? document.selection.createRange().text : document.getSelection();\n document.getElementById('input').value = displayValue \n}", "function getSelectedText() {\r\n if (window.getSelection) {\r\n return window.getSelection();\r\n }\r\n else if (document.selection) {\r\n return document.selection.createRange().text;\r\n }\r\n return '';\r\n}", "selectText(){\r\n this.getRef('input').selectText();\r\n }", "doTextOperation(){let root=this,selection=root.selection;if(root.toggled&&null!==root.toggledCommand){document.execCommand(root.toggledCommand,!1,root.toggledCommand||\"\")}else if(null!==root.command){root.dispatchEvent(new CustomEvent(root.command+\"-button\",{bubbles:!0,cancelable:!0,composed:!0,detail:root}));document.execCommand(root.command,!1,root.commandVal||\"\");root.selection=selection}}", "function getSelectionText(){\n var text = \"\";\n if (window.getSelection) {\n text = window.getSelection().toString();\n } else if (document.selection && document.selection.type != \"Control\") {\n text = document.selection.createRange().text;\n }\n return text;\n}", "getSelection() {\n return this._selectionService ? this._selectionService.selectionText : '';\n }", "function getSelected() {\n if(window.getSelection) { \n \treturn window.getSelection(); \n } else if(document.getSelection) { \n \treturn document.getSelection(); \n }else {\n var selection = document.selection && document.selection.createRange();\n if(selection.text) { \n \treturn selection.text; \n }\n return \"\";\n }\n return \"\";\n}", "function getSelection() {\n\n if ((\"\" + document.activeElement.name).indexOf('label') > -1 ||\n (\"\" + document.activeElement.name).indexOf('name') > -1)\n return '';\n\n var result = '' + self.document.getSelection().toString();\n var iframes = document.querySelectorAll(\"iframe\");\n if (!iframes.length && document.querySelector(\"[global-navigation-config]\")) //try to find iframe in case of polaris\n iframes = document.querySelector(\"[global-navigation-config]\").shadowRoot.querySelectorAll(\"iframe\");\n\n iframes.forEach(frame => {\n\n try {\n result += frame.contentWindow.getSelection().toString();\n } catch (error) {\n console.log(error);\n }\n });\n return '' + result;\n}", "function getSelectedText() {\n\t if (window.getSelection) {\n\t return window.getSelection();\n\t }\n\t else if (document.selection) {\n\t return document.selection.createRange().text;\n\t }\n\t return '';\n\t}", "function textdumper_getSelection() {\r\n var selectionText = \"\";\r\n var trywindow = false;\r\n\r\n var focusedElement = document.commandDispatcher.focusedElement;\r\n if (focusedElement && null != focusedElement) {\r\n try {\r\n selectionText = focusedElement.value.substring(\r\n focusedElement.selectionStart, focusedElement.selectionEnd);\r\n } catch (exc) {\r\n trywindow = true;\r\n }\r\n } else {\r\n trywindow = true;\r\n }\r\n\r\n if (trywindow) {\r\n var focusedWindow = document.commandDispatcher.focusedWindow;\r\n try {\r\n var winWrapper = new XPCNativeWrapper(focusedWindow, 'document',\r\n 'getSelection()');\r\n var selection = winWrapper.getSelection();\r\n } catch (exc) {\r\n var selection = focusedWindow.getSelection();\r\n }\r\n\r\n selectionText = selection.toString();\r\n }\r\n\r\n return selectionText;\r\n}", "function getSelectionText() {\n var text = \"\";\n if (window.getSelection) {\n text = window.getSelection().toString();\n } else if (document.selection && document.selection.type != \"Control\") {\n text = document.selection.createRange().text;\n }\n return text;\n}", "function getSelectionText() {\n var text = \"\";\n if (window.getSelection) {\n text = window.getSelection().toString();\n } else if (document.selection && document.selection.type != \"Control\") {\n text = document.selection.createRange().text;\n }\n return text;\n}", "function fnGetSelectedText() {\n var _dom = document.activeElement;\n var _sel = { text: \"\", slice: \"\", start: -1, end: -1 };\n if (window.getSelection) {\n // Get selected text from input fields\n if (input.isText(_dom)) {\n _sel.start = _dom.selectionStart;\n _sel.end = _dom.selectionEnd;\n if (_sel.end > _sel.start) {\n _sel.text = _dom.value.substring(_sel.start, _sel.end);\n _sel.slice = _dom.value.slice(0, _sel.start) + _dom.value.slice(_sel.end);\n }\n }\n // Get selected text from document\n else _sel.text = window.getSelection().toString();\n } else if (document.selection.createRange)\n _sel.text = document.selection.createRange().text;\n if (_sel.text !== \"\") _sel.text = $.trim(_sel.text);\n return _sel;\n }", "function selectedText() {\n var selection = '';\n if (window.getSelection) {\n selection = window.getSelection();\n } else if (document.selection) { // Opera\n selection = document.selection.createRange();\n }\n if (selection.text) {\n selection = selection.text;\n } else if (selection.toString) {\n selection = selection.toString();\n }\n return selection;\n }", "function getSelectedText2() {\r\n var text = \"\";\r\n if (window.getSelection) {\r\n text = window.getSelection().toString();\r\n } else if (document.selection) {\r\n text = document.selection.createRange().text;\r\n }\r\n\r\n if (mpFlag === 0) {\r\n var a = String('<mp id=\"' + text + '\">');\r\n data_arr.push(a);\r\n mpFlag = 1;\r\n }\r\n else {\r\n data_arr.push(String('</mp>'));\r\n mpFlag = 0;\r\n var a = String('<mp id=\"' + text + '\">');\r\n data_arr.push(a);\r\n mpFlag = 1;\r\n }\r\n}", "function _corexitOnMouseUp(event) {\r\n\tvar selection = window.getSelection();\r\n\tvar selectedText = selection ? selection.toString() : \"\";\r\n\r\n //unselect\r\n //selection.collapseToStart();\r\n\r\n\t//if (selectedText.length != 0) {\r\n chrome.extension.sendRequest({command : \"sendText\", text : selectedText});\r\n\t//}\r\n \r\n\t//gClickInTextBox = false;\r\n \r\n}", "function getSelectedText1() {\r\n var text = \"\";\r\n if (window.getSelection) {\r\n text = window.getSelection().toString();\r\n } else if (document.selection) {\r\n text = document.selection.createRange().text;\r\n }\r\n\r\n if (tFlag === 0) {\r\n var a = String('<title id=\"' + text + '\">');\r\n data_arr.push(a);\r\n tFlag = 1;\r\n }\r\n else {\r\n if (mpFlag === 0) {\r\n data_arr.push(String('</title>'));\r\n tFlag = 0;\r\n var a = String('<title id=\"' + text + '\">');\r\n data_arr.push(a);\r\n tFlag = 1;\r\n }\r\n else {\r\n data_arr.push(String('</mp>'));\r\n data_arr.push(String('</title>'));\r\n tFlag = 0;\r\n mpFlag = 0;\r\n var a = String('<title id=\"' + text + '\">');\r\n data_arr.push(a);\r\n tFlag = 1;\r\n }\r\n }\r\n}", "function getSelectedText() {\r\n var txt = '';\r\n if (window.getSelection) {\r\n txt = window.getSelection();\r\n }\r\n else if (document.getSelection) // FireFox\r\n {\r\n txt = document.getSelection() + \"\";\r\n }\r\n else if (document.selection) // IE 6/7\r\n {\r\n txt = document.selection.createRange().text;\r\n }\r\n return txt;\r\n\r\n}", "function frankerCoreGetSelectedText(doc, trim) {\n\tvar selection = doc.getSelection();\n\treturn (trim) ? frankerUtilTrimString(selection + \"\") : selection + \"\";\n}", "function copy(){\nif (!window.x) {\n x = {};\n}\nx.Selector = {};\nx.Selector.getSelected = function() {\n var t = '';\n if (window.getSelection) {\n t = window.getSelection();\n } else if (document.getSelection) {\n t = document.getSelection();\n } else if (document.selection) {\n t = document.selection.createRange().text;\n }\n return t;\n}\nvar mytext = x.Selector.getSelected();\ndocument.getElementById(\"book\").innerHTML =mytext;\n}", "function getSelectionText() {\n var text = \"\";\n if (window.getSelection) {\n text = window.getSelection().toString(); // non IE\n } else if (document.selection && document.selection.type != \"Control\") {\n text = document.selection.createRange().text; // for IE\n }\n return text;\n\t}", "function getSelectedText () {\n let selection = window.getSelection();\n let selectedText = selection.toString().trim();\n\n if (selectedText.length && selection.isCollapsed === false) {\n return selectedText;\n } else {\n return null;\n }\n }", "function getSel() {\r\n var mySel = '';\r\n if (window.getSelection) {\r\n mySel = window.getSelection();\r\n } else if (document.getSelection) {\r\n mySel = document.getSelection();\r\n } else if (document.selection) {\r\n mySel = document.selection.createRange().text;\r\n }\r\n return mySel; \r\n }", "function getSelectedTextFromPage() {\n //console.log(\"getSelectedTextFromPage start...\");\n //console.log(window.getSelection.toString());\n\n if(window.getSelection){\n // this technique is the most likely to be standardized.\n // getSelection() returns a Selection object\n //console.log(window.getSelection().toString());\n return window.getSelection().toString();\n } else if(document.getSelection){\n //this is an older,simpler technique that returns a string\n return document.getSelection();\n }else if (document.selection){\n // this is the IE-specific technique.\n return document.selection.createRange().text;\n }\n}", "function handleMouseDown(e) {\n $(\"#submitTextOnCanvas\").css(\"background\",\"green\");\n $(\"#submitTextOnCanvas\").css(\"color\",\"white\");\n $(\"#hint\").html(\"Then click 'Save'\");\n e.preventDefault();\n text_startX = parseInt(e.clientX - text_canvas.offset().left);\n text_startY = parseInt(e.clientY - text_canvas.offset().top);\n // Put your mousedown stuff here\n for (var i = 0; i < texts.length; i++) {\n if (textHittest(text_startX, text_startY, i)) {\n console.log(\"text-e\");\n \n selectedText = i;\n }\n }\n }", "function UISelection(){\n\n }", "copySelectedCellValue() {\n var txtView = new latte.TextView();\n txtView.text = this.selectedCell.text();\n var btnOk = new latte.ButtonItem();\n btnOk.text = strings.ok;\n var d = new latte.DialogView(txtView, [btnOk]);\n d.show();\n txtView.textElement.focus();\n txtView.textElement.select();\n }", "function commandLine() {\n let selection = document.getSelection()\n let node = selection.anchorNode\n let text = node.textContent.slice(0, selection.focusOffset)\n return text \n}", "retriveText() {\n let exactText;\n let currentElement;\n if (!isNullOrUndefined(this.currentContextInfo) && this.currentContextInfo.element) {\n currentElement = this.currentContextInfo.element;\n exactText = this.currentContextInfo.element.text;\n this.viewer.selection.start = currentElement.start;\n this.viewer.selection.end = currentElement.end;\n }\n else {\n let startPosition = this.viewer.selection.start;\n let offset = startPosition.offset;\n let startIndex = 0;\n let startInlineObj = startPosition.currentWidget.getInline(offset, startIndex);\n currentElement = startInlineObj.element;\n exactText = startInlineObj.element.text;\n }\n return { 'text': exactText, 'element': currentElement };\n }", "function selectedText() {\n var selection = window.getSelection();\n return selection.type === 'Range' ? selection : false\n }", "function getSelectedText()\n {\n var result;\n if ($.browser.msie)\n {\n result = document.selection.createRange().htmlText;\n }\n else\n {\n var selection = window.getSelection();\n var range = selection.getRangeAt(0);\n selection = selection.toString();\n range = range.toString();\n //selection works for line numbers on, range otherwise\n result = /\\n/.test(selection) ? selection : range;\n }\n return result;\n }", "function getDataFromSelection() {\n Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,\n\t\t\tfunction (result) {\n\t\t\t if (result.status === Office.AsyncResultStatus.Succeeded) {\n\t\t\t app.showNotification('The selected text is:', '\"' + result.value + '\"');\n\t\t\t } else {\n\t\t\t app.showNotification('Error:', result.error.message);\n\t\t\t }\n\t\t\t}\n\t\t);\n }", "function onClickHandler(info, tab) {\n\tvar itemId = info.menuItemId;\n\tvar context = itemId.split('_', 1)[0];\n\t\n\tswitch (context) {\n\t\tcase 'selection':\n\t\t\tif (info.selectionText.length > 0) {\n\t\t\t\tconsole.log(JSON.stringify(info.selectionText));\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tconsole.log('Other context than selection');\n\t}\n\t\n\n}", "function getSelectedText() {\n let txt = \"\";\n let selection = window.getSelection();\n if (selection !== null) {\n txt = selection.toString();\n }\n if (txt === \"\" && document.activeElement.value !== undefined) {\n txt = document.activeElement.value.substring(document.activeElement.selectionStart, document.activeElement.selectionEnd);\n }\n if (txt === \"\") {\n txt = document.body.innerText;\n }\n return txt;\n}", "function makeSelection(point, pSelection) {\n\t\t//alert(pSelection);\n\t\t//add clicked point to qPoint/tPoint\n\t\tif(pSelection != null){\n\t\t\tif(pSelection == 1){\n\t\t\t\tif(qPoint){\n\t\t\t\t\tqPoint.select(false, true);\n\t\t\t\t}\n\t\t\t\tqPoint = point;\n\t\t\t}\n\t\t\telse if(pSelection == 0){\n\t\t\t\tif(tPoint){\n\t\t\t\t\ttPoint.select(false, true);\n\t\t\t\t}\n\t\t\t\ttPoint = point;\n\t\t\t}\n\t\t\tpoint.select(true, true);\n\t\t} //else null without any selection, do nothing\t\n\t\tmakeQTText();\n }", "function select () {\r\n\t\t\t\tthis.tool.select();\r\n\t\t\t}", "function selectionHandler ( info, tab ) {\n sendItem( { 'message': info.selectionText } );\n}", "function GetSelectedText() {\n const documentText = vscode.window.activeTextEditor.document.getText();\n if (!documentText) {\n return \"\";\n }\n let activeSelection = vscode.window.activeTextEditor.selection;\n if (activeSelection.isEmpty) {\n return \"\";\n }\n const selStartoffset = vscode.window.activeTextEditor.document.offsetAt(\n activeSelection.start\n );\n const selEndOffset = vscode.window.activeTextEditor.document.offsetAt(\n activeSelection.end\n );\n\n let selectedText = documentText.slice(selStartoffset, selEndOffset).trim();\n selectedText = selectedText.replace(/\\s\\s+/g, \" \");\n return selectedText;\n}", "function markButton(){\n//store value of letter in the selected button \nlet selection = event.target.innerHTML; \n//pass button into games handle interaction function \ngameOne.handleInteraction(selection);\n}", "function onClickHandler(info, tab) {\n\tvar text = info.selectionText;\n\tvar msg = new SpeechSynthesisUtterance(text);\n\twindow.speechSynthesis.speak(msg);\n}", "function handleMouseDown(e) {\n e.preventDefault();\n startX = parseInt(e.clientX - offsetX);\n // console.log(startX);\n startY = parseInt(e.clientY - offsetY);\n // console.log(startY);\n\n // Put your mousedown stuff here\n // for (var i = 0; i < texts.length; i++) {\n // if (textHittest(startX, startY, i)) {\n selectedText = currentIndex;\n // }\n // }\n}", "function _selection() {\n if (window.getSelection) {\n return window.getSelection();\n } else if (document.getSelection) {\n return document.getSelection();\n } else if (document.selection) {\n return document.selection.createRange().text;\n }\n }", "static get tag(){return\"rich-text-editor-selection\"}", "function selectText(element) {\n\n if (document.body.createTextRange) {\n var range = document.body.createTextRange();\n range.moveToElementText(element);\n range.select();\n } else if (window.getSelection) {\n var selection = window.getSelection();\n var range = document.createRange();\n range.selectNode(element);\n selection.removeAllRanges();\n selection.addRange(range);\n }\n }", "get selection() {\n return this.$.selection.getSelection();\n }", "getSelection(){\n return this.element;\n }", "function checkSelectedText(e) {\n var selectedText = (document.all)\n ? document.selection.createRange().text\n : document.getSelection();\n if (selectedText.toString().length > 0) {\n //node of selected text\n var node = selectedText.baseNode.parentElement;\n if (node.classList.contains(\"asc-selectable-text\")) {\n editMenuClick(e, node);\n }\n } else {\n hideEditMenu(e);\n }\n }", "function select() {\n getElements()[selection].getElementsByTagName('a')[0].click();\n\n}", "_evtClick(event) {\n // only handle primary button clicks\n if (event.button !== 0 || this._selected) {\n return;\n }\n const inputElement = this.inputElement;\n event.preventDefault();\n event.stopPropagation();\n this._selected = true;\n const selectEnd = inputElement.value.indexOf('.');\n if (selectEnd === -1) {\n inputElement.select();\n }\n else {\n inputElement.setSelectionRange(0, selectEnd);\n }\n }", "function getSelection() {\r\n return this.window.getSelection ? this.window.getSelection() : this.document.selection;\r\n }", "updateTextPosition(widget, point) {\n let caretPosition = point;\n let element = undefined;\n let index = 0;\n let isImageSelected = false;\n let isImageSelectedObj = this.updateTextPositionIn(widget, element, index, point, false);\n if (!isNullOrUndefined(isImageSelectedObj)) {\n element = isImageSelectedObj.element;\n index = isImageSelectedObj.index;\n caretPosition = isImageSelectedObj.caretPosition;\n isImageSelected = isImageSelectedObj.isImageSelected;\n this.isImageSelected = isImageSelected;\n }\n if (isImageSelected) {\n this.selectInternal(widget, element, index, caretPosition);\n if (index === 0) {\n this.extendForward();\n }\n else {\n this.extendBackward();\n }\n }\n else {\n this.selectInternal(widget, element, index, caretPosition);\n }\n }", "function buttonClicked(e) {\n\tvar element = e.memo.element;\n\tif (this.options.singleSelect) {\n\t\tthis.select(element);\n\t} else {\n\t\tif (this.isSelected(element)) {\n\t\t\tthis.deselect(element);\t\n\t\t} else {\n\t\t\tthis.select(element);\n\t\t}\n\t}\n}", "function get_selected_element() {\n\n return iframe.find(\".yp-selected\");\n\n }", "function clickFunction(e){\n var currLine = getCurrentLine(this);\n num_lines_selected = 1; //returns to default, in case just clicking, if it is selected that's taken care of in subsequent onselect\n prevLine = currLine;\n}", "updateTextPositionForSelection(cursorPoint, tapCount) {\n let widget = this.getLineWidget(cursorPoint);\n if (!isNullOrUndefined(widget)) {\n this.selection.updateTextPosition(widget, cursorPoint);\n }\n if (tapCount > 1) {\n this.isMouseDown = false;\n this.useTouchSelectionMark = false;\n if (this.pages.length === 0) {\n return;\n }\n //Double tap/triple tap selection\n if (!isNullOrUndefined(this.currentPage) && !isNullOrUndefined(this.owner.selection.start)) {\n if (tapCount % 2 === 0) {\n this.owner.selection.selectCurrentWord();\n }\n else {\n this.owner.selection.selectParagraph();\n }\n }\n }\n }", "function saveSelection() {\n if (window.getSelection) {\n sel = window.getSelection();\n if (sel.getRangeAt && sel.rangeCount) {\n return sel.getRangeAt(0);\n }\n } else if (document.selection && document.selection.createRange) {\n return document.selection.createRange();\n }\n return null;\n }", "select() {\n this.getInput().select();\n }", "function wordPicker() {\n console.log(currentWord);\n console.log(currentWord[3]);\n }", "function handleClick(event) {\n alert(event.target.text);\n}", "function selectHandler() {\n var selectedItem = chart.getSelection()[0];\n if (selectedItem) {\n var value = data.getValue(selectedItem.row, selectedItem.column);\n alert('The user selected ' + value);\n }\n }", "selectText(i) {\n const input = document.getElementById(\"titleBox-\" + this.props.category + i);\n input.focus();\n input.select();\n }", "function getSel() {\n\tvar txt = '';\n\tvar foundIn = '';\n\tdocument.getElementById('selectedblastp').innerHTML = \"\";\n\tdocument.getElementById('selectedblastnfull').innerHTML = \"\";\n\tdocument.getElementById('selectedblastncds').innerHTML = \"\";\n\t\n\tif (window.getSelection)\n\t{\n\t\ttxt = window.getSelection();\n\t\tfoundIn = 'window.getSelection()';\n\t}\n\telse if (document.getSelection)\n\t{\n\t\ttxt = document.getSelection();\n\t\tfoundIn = 'document.getSelection()';\n\t}\n\telse if (document.selection)\n\t{\n\t\ttxt = document.selection.createRange().text;\n\t\tfoundIn = 'document.selection.createRange()';\n\t}\n\telse return false;\n\t//fixtxt = txt.replace(/<br>/ig, \"\");\n\tvar fixtxt = new String(txt);\n\n\tfixtxt = fixtxt.replace(/\\W/ig, \"\");\n\tif (fixtxt.match(/^[A-Z]+$/)) {\n\t\treturn fixtxt;\n\t}\n\telse return false;\n}", "function selectHandler() {\n var selectedItem = chart.getSelection()[0];\n if (selectedItem) {\n var value = data.getValue(selectedItem.row, selectedItem.column);\n alert('The user selected ' + value);\n }\n }", "function selectHandler() {\n var selectedItem = chart.getSelection()[0];\n if (selectedItem) {\n var value = data.getValue(selectedItem.row, selectedItem.column);\n alert('The user selected ' + value);\n }\n }", "function selectText(el) {\n var range;\n if (window.getSelection && document.createRange) {\n range = document.createRange();\n let sel = window.getSelection();\n range.selectNodeContents(el.currentTarget);\n sel.removeAllRanges();\n sel.addRange(range);\n } else if (document.body && document.body.createTextRange) {\n range = document.body.createTextRange();\n range.moveToElementText(el);\n range.select();\n }\n}", "function selectionChange(e) {\n var pointRng;\n\n // Check if the button is down or not\n if (e.button) {\n // Create range from mouse position\n pointRng = rngFromPoint(e.pageX, e.pageY);\n\n if (pointRng) {\n // Check if pointRange is before/after selection then change the endPoint\n if (pointRng.compareEndPoints('StartToStart', startRng) > 0)\n pointRng.setEndPoint('StartToStart', startRng);\n else\n pointRng.setEndPoint('EndToEnd', startRng);\n\n pointRng.select();\n }\n } else {\n endSelection();\n }\n }", "function selectHandler() {\n var selectedItem = chart.getSelection()[0];\n if (selectedItem) {\n var value = data.getValue(selectedItem.row, 0);\n openPopup(value);\n // console.log('The user selected - ' + value);\n }\n }", "selectIt() {\n var index = 1,\n text,\n modIndex,\n modLength;\n text = this.selected.text;\n modIndex = this.mod.indexOf(text);\n modLength = this.mod.slice(0, modIndex).length;\n var modEnd = this.mod.slice(modIndex + text.length, this.mod.length);\n if (this.modded) {\n index = this.selected.start + modLength;\n } else {\n index = this.selected.start - modLength;\n }\n this.el.focus();\n // el.selectionStart = index;\n // el.selectionEnd = selected.text.length + index;\n var ending = this.selected.text.length + index;\n this.setSelectionRange(this.el, index, ending);\n }", "get caretPos() {\n return this.textSelection[0];\n }", "function SelectionChange() {}", "function SelectionChange() {}", "function SelectionChange() {}", "function SelectionChange() {}", "function selectionGet() {\n // for webkit, mozilla, opera\n if (window.getSelection)\n return window.getSelection();\n // for ie\n else if (document.selection && document.selection.createRange && document.selection.type != \"None\")\n return document.selection.createRange();\n }", "function showCurrentText() {\n\tunselectAll();\n\thideAll();\n\tshowAllHeaders();\n\t$(\"#pano\" + currentpanonum).addClass('selected').children().show(5,scrollTo(currentpanonum));\n}", "function ClickBarra() {\n\n var selectedItem = chart.getSelection()[0];\n if (selectedItem) {\n var planta = data.getValue(selectedItem.row, 0);\n click_grafica(planta);\n\n\n }\n }", "mouseDown(pt) {}", "mouseDown(pt) {}", "function selectItem(e) {\n\n for (var i = 0; i < e.currentTarget.parentNode.children.length; i++) {\n e.currentTarget.parentNode.children[i].classList.remove(\"selected\");\n }\n\n e.currentTarget.classList.add(\"selected\");\n console.log($(e.currentTarget).children().eq(1).text());\n updateP1Moves($(e.currentTarget).children().eq(1).text());\n \n}", "selectSubCollection(e) {\n if (!e.detail.chart.getSelection()[0]) {\n return;\n }\n\n let targetItem = e.detail.chart.getSelection()[0].name;\n if (!targetItem || targetItem.match(/_\\(/)) {\n return;\n }\n const selectedTarget = targetItem.match(/ \\((.*?)\\)/);\n const setSelectionTarget = selectedTarget ? selectedTarget[1] : targetItem;\n if (targetItem === this.targetItem) {\n let win = window.open(\n `../${this.language}/text/${setSelectionTarget}`,\n '_blank'\n );\n win.focus();\n return;\n }\n this.targetItem = targetItem;\n this.setSelection(\n this.language + '_' + setSelectionTarget,\n this.selectedCollections\n );\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 }", "function getSelectedText(select2_) {\n var select2 = _getSelect2(select2_);\n var data = select2.select2('data');\n if (!data || !data[0])\n return \"\";\n var res = data[0].text;\n return res;\n }", "function SelectionChange() { }", "function SelectionChange() { }" ]
[ "0.73353237", "0.71102285", "0.70235944", "0.6944137", "0.6935864", "0.691551", "0.6827972", "0.6819054", "0.6806455", "0.6716165", "0.6712815", "0.66891825", "0.6683969", "0.66208017", "0.659375", "0.65929246", "0.6589905", "0.6586066", "0.65468585", "0.65317166", "0.6514218", "0.6490573", "0.64846575", "0.6461097", "0.64458895", "0.64384985", "0.64185494", "0.64185494", "0.6408588", "0.63783", "0.6375026", "0.6368208", "0.6351623", "0.6334028", "0.62807137", "0.6278808", "0.62763375", "0.62394893", "0.6231056", "0.6208753", "0.6190289", "0.61688226", "0.6155225", "0.61433446", "0.6132104", "0.61066633", "0.6099246", "0.6093185", "0.60930765", "0.6086007", "0.6062977", "0.60495627", "0.6046773", "0.60189825", "0.6013187", "0.6004341", "0.59964263", "0.598797", "0.5981289", "0.5971569", "0.5965988", "0.59630686", "0.5956467", "0.59551376", "0.59504527", "0.5945421", "0.5930266", "0.5928069", "0.5907584", "0.58812314", "0.5875075", "0.5872223", "0.5866337", "0.58633876", "0.5861053", "0.5859189", "0.5856406", "0.5852464", "0.5847356", "0.5847356", "0.58441544", "0.58436847", "0.58299565", "0.581353", "0.5811504", "0.58067685", "0.58067685", "0.58067685", "0.58067685", "0.58000255", "0.5798096", "0.579201", "0.578504", "0.578504", "0.5782132", "0.57698333", "0.5769356", "0.57623214", "0.57621616", "0.57621616" ]
0.6707061
11
INSERT CODE HERE TO EXECUJE Definimos la Promise
function resolveAfter2Seconds() { return new Promise(resolve => { setTimeout(() => { resolve(`El nombre del empleado con id ${id}, es ${employees.find(x => x.id === id).name} y su salario es de ${salaries.find(x => x.id === id).salary}`); }, 2000); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function fullPromise(param) {\n\t//PLACE YOUR CODE HERE:\n}", "function ITSAPluginPromise() {}", "runPromise(self) {\n const context = this.fiberContext(self);\n return new Promise((res, rej) => {\n context.runAsync(exit => {\n switch (exit._tag) {\n case \"Success\":\n {\n res(exit.value);\n break;\n }\n\n case \"Failure\":\n {\n rej(Cause.squash(identity)(exit.cause));\n break;\n }\n }\n });\n });\n }", "function faireQqc() {\n return new Promise((successCallback, failureCallback) => { \n\n console.log(\"Dans Promise, dans l'ordre des appels \");\n // réussir une fois sur deux\n var variable = Math.random() ; \n if (variable > .5) {\n console.log(\"Dans Promise Success, dans l'ordre des appels\") ;\n successCallback(\"Réussite : \" + variable);\n } else {\n console.log(\"Dans Promise Fail, dans l'ordre des appels\") ;\n failureCallback(\"Échec : \" + variable);\n }\n \n })\n }", "async function miAsyncFunction()\n{\n try \n { //Esto de acá sería como el then de la async function miAsyncFunction() \n const promesa = await miPromesa; //espera el resultado de la promesa satisfecha (resolved)\n console.log(`Este es el valor de la promesa ${promesa}`);\n } //Esto de acá sería como el catch de la async function miAsyncFunction() \n catch (error) {\n console.log(\"La pecheaste\"); \n }\n}", "async function funcionConPromesaYAwait(){\n let miPromesa = new Promise((resolved) => {\n resolved(\"Promesa con await\"); \n });\n\n //Ya no es necesario utilizar .then() sino que con await va a recibir el valor\n // y se va a mostrar en consola \n console.log( await miPromesa );\n}", "function Promise() {\n}", "function register()\n{\n return new Promise((pRes, pRej) => {\n\n })\n}", "function query_promise_then(result) {\n\n\n }", "function query_promise_then(result) {\n\n\n }", "async function miFuncionConPromesa ()\r\n{\r\n return 'saludos con promesa y async';\r\n}", "function Def(){this.promise=new Promise((function(a,b){this.resolve=a,this.reject=b}).bind(this))}", "function hipcamp_promise_then(result) {\n my_query.hipcamp_url=result;\n var promise=MTP.create_promise(result,parse_hipcamp,parse_hipcamp_then,function() { GM_setValue(\"returnHit\",true); });\n }", "function query_promise_then(result) {\n }", "function query_promise_then(result) {\n }", "static promiseURI(theURI, form) {\nreturn new Promise((resolve, reject) => {\nvar theCB;\ntheCB = (val, errC, errT, part) => {\nif (errC > 0) {\nif (typeof lggr.trace === \"function\") {\nlggr.trace(`promiseURI ${theURI} rejecting ${errT}`);\n}\nreturn reject(new Error(JSON.stringify([errC, errT, part])));\n} else {\nif (typeof lggr.trace === \"function\") {\nlggr.trace(`promiseURI ${theURI} resolving`);\n}\nreturn resolve(val);\n}\n};\nreturn Data.fetchURI(theURI, theCB, form);\n});\n}", "function AbstractPromiseExecutor() {}", "async function miFuncionConPromesa(){\n return \"Saludos con promeso y async\";\n}", "function customPromise(selector, cPage, followID){\n return new Promise(function (resolve,reject){\n // wait for click\n let waitForInputSelector = cPage.waitForSelector(selector,{visible:true});\n waitForInputSelector.then(function (){\n let clickInput = cPage.click(selector,{delay:100});\n return clickInput;\n }).then(function(){\n let typingItem = cPage.keyboard.type(followID,{delay:300});\n return typingItem;\n }).then(function (){\n let future5secondAfter = Date.now() + 10000;\n while (Date.now() < future5secondAfter) {\n }\n cPage.keyboard.press('ArrowDown',{ delay: 100 });\n let keyBoardDown = cPage.keyboard.press('Enter');\n return keyBoardDown;\n }).then(function (){\n let future18secondAfter = Date.now() + 12000;\n while (Date.now() < future18secondAfter) {\n }\n console.log(\"clicking on follow\",Date.now() - startTime);\n let waitForEleSelector = handelIfNotPresent('div[style=\"height: 30px;\"]',cPage);\n return waitForEleSelector; \n }).then(function(){\n let future29secondAfter = Date.now() + 10000;\n while (Date.now() < future29secondAfter) {\n }\n console.log(\"Successfully clicked on follow button\",Date.now() - startTime);\n return future29secondAfter;\n // Ending of follow button\n }).then(function(){\n resolve();\n }).catch(function (){\n resolve();\n console.log(\"Error occurs in Follow loop function kindly check selector----------------------\",Date.now() - startTime);\n })\n })\n}", "async method(){}", "async function funcionAsincronaDeclarada (){\r\n try {\r\n console.log(`Inicio de Async function`)\r\n let obj = await cuadradoPromise(0);\r\n console.log(`Async function: ${obj.value}, ${obj.result}`)\r\n \r\n obj = await cuadradoPromise(1);\r\n console.log(`Async function: ${obj.value}, ${obj.result}`)\r\n\r\n obj = await cuadradoPromise(2);\r\n console.log(`Async function: ${obj.value}, ${obj.result}`)\r\n\r\n obj = await cuadradoPromise(3);\r\n console.log(`Async function: ${obj.value}, ${obj.result}`)\r\n\r\n obj = await cuadradoPromise(4);\r\n console.log(`Async function: ${obj.value}, ${obj.result}`)\r\n } catch (err) {\r\n console.error(err)\r\n }\r\n}", "function func() {\n const prom = () => new Promise((resolve) => {\n setTimeout(() => resolve('Resolved'), 100);\n });\n const res = prom();\n expect(res).to.equal('Resolved');\n done();\n }", "function foo() {\n prepare().then( result => console.log(result))\n console.log(\"Then the milk!!!\")\n}", "start(data){\n\t\treturn new Promise((resolve, reject) => this._execute(0, data, resolve, reject));\n\t}", "async function executeMpromise(){\n \n try{\n const val=await myPromiseFunc(10);\n console.log(val);\n }\n catch(error){\n console.log(\"Error\",err);\n }\n}", "function nativePromiseDinner() {\n brainstormDinner().then((meal) => {\n console.log(`I'm going to make ${meal} for dinner.`);\n })\n}", "function newF(){\n // promice ak callback function lata ha\n const prom = new Promise((resolve, reject) => {\n setTimeout(() => {\n console.log('inside Promice')\n resolve(\"ok\")\n }, 1000)\n })\n // console.log(prom)\n return prom\n}", "execute() {\n return __awaiter(this, void 0, void 0, function* () {\n return { value: 'test_response' };\n });\n }", "then(onResovled, onRejected) {\n\n // each 'then' method return new promise object\n return new MyPromise((nextResolve, nextReject) => {\n\n // confirm has 'onResolved' callback\n if(this._isFunction(onResovled)) {\n // confirm the current status is fullfilled\n if(FULLFILLED === this.status) {\n\n // 后一个then可以捕获前一个then的异常\n try {\n\n // 拿到上一个promise成功回调执行结果 trigger the previous promise resolve callback and get the result\n let result = onResovled(this.value);\n\n // 判断执行的结果是否是一个promise对象 confirm return the promise object or not\n if(result instanceof MyPromise) {\n result.then(nextResolve, nextReject);\n } else {\n // return the primary data value\n console.log('result', result);\n // 将上一个promise成功回调执行结果传递给下一个promise成功的回调。\n // transfer the previouse promise resolve callback result to the next promise resolve callback\n nextResolve(result);\n }\n\n\n } catch (e) {\n nextReject(e);\n }\n\n \n\n \n }\n }\n // confirm has 'onRejected' callback\n if(this._isFunction(onRejected)) {\n\n try {\n\n // confirm the current status is rejected\n if(REJECTED === this.status) {\n // similar as resolved one.\n let result = onRejected(this.reason);\n\n // 判断执行的结果是否是一个promise对象 confirm return the promise object or not\n if(result instanceof MyPromise) {\n result.then(nextResolve, nextReject);\n } else if(result !== undefined ) {\n // result is the data\n // 上一个promise reject 结果传递给下一个resolve结果\n nextResolve(result);\n }\n else {\n nextReject();\n }\n \n }\n\n\n } catch (e) {\n nextReject(e);\n\n }\n \n }\n // 如果添加监听时候状态未改变,那么状态改变时候再执行监听回调\n // 判断当前的状态是否是默认状态 confirm the current status is the default status\n if(PENDING === this.status) {\n if(this._isFunction(onResovled)) {\n // this.onResovledCallback = onResovled;\n // this.onResovledCallback.push(onResovled);\n\n this.onResovledCallback.push(() => {\n\n try {\n\n let result = onResovled(this.value);\n\n // 判断执行的结果是否是一个promise对象 confirm return the promise object or not\n if(result instanceof MyPromise) {\n result.then(nextResolve, nextReject);\n } else {\n nextResolve(result);\n }\n\n } catch (e) {\n nextReject(e);\n }\n \n \n })\n } \n if(this._isFunction(onRejected)) {\n // this.onRejectedCallback = onRejected;\n // this.onRejectedCallback.push(onRejected);\n\n // deal with this by arrow function\n this.onRejectedCallback.push(() => {\n\n try {\n\n let result = onRejected(this.reason);\n // 判断执行的结果是否是一个promise对象 confirm return the promise object or not\n if(result instanceof MyPromise) {\n result.then(nextResolve, nextReject);\n } else if(result !== undefined) {\n nextResolve(result);\n } else {\n nextReject();\n }\n\n } catch (e) {\n nextReject(e);\n }\n \n \n })\n }\n }\n\n });\n\n \n }", "function wait () { return new Promise( (resolve,reject)=>{ setTimeout(resolve,5000)} )}", "function r(e){return Promise.resolve({data:e,once:!0,direct:!0})}", "function query_promise_then(result) {\n\n my_query.url=result;\n var promise=MTP.create_promise(my_query.url,find_logo,submit_if_done,function() {\n if(!my_query.failed_once&&my_query.old_url) {\n my_query.failed_once=true;\n const queryPromise = new Promise((resolve, reject) => {\n console.log(\"Beginning URL search\");\n query_search(my_query.name+\" real estate agent\" , resolve, reject, query_response,\"query\");\n });\n queryPromise.then(query_promise_then)\n .catch(function(val) {\n console.log(\"Failed at this queryPromise \" + val); GM_setValue(\"returnHit\",true); });\n return;\n }\n\n\n\n\n GM_setValue(\"returnHit\",true); });\n\n }", "function sc_makePromise(proc) {\n var isResultReady = false;\n var result = undefined;\n return function() {\n\tif (!isResultReady) {\n\t var tmp = proc();\n\t if (!isResultReady) {\n\t\tisResultReady = true;\n\t\tresult = tmp;\n\t }\n\t}\n\treturn result;\n };\n}", "static resolve(p) {\n return (p instanceof promise) ? p : new promise((r,j)=>{\n r(p)\n })\n }", "static async method(){}", "function promiseMaker() {\n //promise is a object which takes 2 callbacks, resolve and reject\n return new Promise(function(resolve, reject) {\n setTimeout(() => {\n var error = true;\n if (!error) {\n console.log('Promise has been resolved');\n //if the promise is kept then resolve will be called\n resolve();\n } else {\n console.log('Sorry i could not fulfill the promise');\n //if promise not kept then reject will be called;\n reject('Sorry not fulfilled');\n }\n }, 2000);\n });\n}", "function handle() {\n var args = _.toArray(arguments);\n var fn = args.shift();\n var result = fn.apply(this, args);\n if (result instanceof Promise) {\n return result;\n } else {\n return Promise.resolve(result);\n }\n}", "function hola(nombre) {\n return new Promise((resolve, reject) => {\n setTimeout(function () {\n console.log(\"Hola \" + nombre);\n resolve(nombre);\n }, 1000);\n });\n}", "constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }", "function testasPromise(){\n\t\n\treturn new Promise(function(resolve,reject){\n\t\t\n\t\tfs.readFile('test4.txt', (err, data) => {\n\t\t\t if (err) throw reject(err);\n\t\t\t resolve(data);\n\t\t});\n\t\t\n\t});\n\t\n\t\n}", "async function prosess (){\r\n try{\r\n console.log(\"Proses 1\");\r\n console.log(\"Proses 2\");\r\n console.log(\"Proses 3\");\r\n const result = await cariHariKerja(\"senin\")\r\n console.log(result);\r\n console.log(\"Proses 4\");\r\n console.log(\"Proses 5\");\r\n } catch(err){\r\n console.log(err);\r\n }\r\n}", "function pegarValor(){\r\n return new Promise(resolve => {\r\n setTimeout(() => resolve(10), 5000)\r\n })\r\n}", "then(resolve, reject) {\n return this.exec().then(resolve, reject);\n }", "function tercerPromesa() {\n return new Promise((res, rej) => setTimeout(res, 600, \"Tercer hola mundo\"));\n}", "function asincrona() {\n return new Promise ( (resolve) => {\n setTimeout(() => {\n console.log('Termina el proceso asincrono');\n resolve();\n }, 1000);\n });\n}", "async function ej3() {\n var res = await prom();\n console.log(res);\n}", "function runPromise()\n {\n Promise.all( ajaxesForPromice ).then( values => {\n values.forEach( function( value, vix ) {\n insertImage( values[vix], vix, 'data:image/png;base64,' );\n }); \n continueAfterChartsLoaded();\n }); \n }", "function helpMe() {\n return new Promise(resolve => { setTimeout(() => { \n console.log('promise');\n resolve('ok')\n }, 3000)})\n \n}", "async function funcionConPromesaAwaitTimeout(){\r\n console.log('inicio función');\r\n let miPromesa = new Promise(resolver => {\r\n // Aqui llamamos a la promesa y le damos un tiempo con setTimeout\r\n setTimeout(()=> resolver('promesa con await y timeout'), 3000);\r\n });\r\n /* await solo se puede utilizar dentro de las promesas que estan declaradas con async */\r\n // Aqui esperamos la respuesta de la proesa con await así que la siguiente linea de codigo no se\r\n // imprime hasra que obtenemos el resultado de esa promesa\r\n console.log( await miPromesa);\r\n console.log('fin función');\r\n}", "set p(promise) {\n promise.then(function (r) {\n return console.log(r);\n });\n }", "async function hola(nombre) {\n return new Promise((resolve, reject) => {\n setTimeout(function () {\n console.log(\"Hola \" + nombre);\n resolve(nombre);\n }, 1000);\n });\n}", "function promise(func, res){\nsetTimeout(function(){func.then(dt => {res(dt)})},5000)\n}", "function query_promise_then(result) {\n my_query.url=result;\n var query={dept_regex_lst:[/Staff/],title_regex_lst:[/Owner/,/Manager/,/Director/]};\n\n var promise=MTP.create_promise(my_query.url,Gov.init_Gov,gov_promise_then,function() { GM_setValue(\"returnHit\",true); },query);\n }", "function orderSunglasses (){\n return new Promise(executorFunction);\n }", "function tProm() {\n\n\tvar res = null;\n\tvar ref = null;\n\n\treturn new Promise(function(resolve, reject) {\n\t\tconsole.log('created promise');\n\n\t});\n/*\n\treturn {\n\t\tp: prom,\n\t\tres: \n\t\trej\n\t}\n*/\n}", "function microCreatesMacro()\n{\n Promise.resolve().then(() => \n {\n setTimeout(() => console.log(\"timeout\"), 0);\n }).then(() => \n {\n console.log(\"promise\");\n });\n}", "async function cobaAsync() {\n\n try {\n const coba = await cobaPromise();\n console.log(coba);\n } catch (error) {\n console.error(error);\n }\n}", "function prepare() {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n resolve(\"First the cereal!!!!\");\n }, 1000)\n });\n}", "async function Kosarajus(){}", "function waitForMath(){\n return new Promise((resolve, reject) => {\n try{\n someMath();\n resolve(); \n } catch(error){\n reject('error: numbers arent real');\n }\n \n }) \n\n\n\n\n\n}", "function liar() {\n\treturn new Promise(() => 0);\n}", "async function init(){\n await createPostPromise({title:'post six',body:'this is post six'})\n .then(getPosts)\n .catch(err=>console.log(err))\n}", "function query_promise_then(result) {\n my_query.done.query=true;\n submit_if_done();\n }", "calculoPromesa(val1, val2) {\n this.metodoPromesa(val1, val2)\n .then(function () {\n objCalculo.calculo(val1, val2)\n })\n .catch(err => console.log(err.message))\n }", "function compass_promise_then(url) {\n console.log(\"Fetching url=\"+url);\n GM_xmlhttpRequest({\n method: 'GET',\n url: url,\n\n onload: function(response) {\n // console.log(\"On load in crunch_response\");\n // crunch_response(response, resolve, reject);\n parse_compass(response);\n },\n onerror: function(response) { console.log(\"Fail\"); },\n ontimeout: function(response) { console.log(\"Fail\"); }\n\n\n });\n\n }", "function myFn() {\n return Promise.resolve(\"Hello\");\n}", "function setupPromise(filename, face) {\n\n myPromise = asyncGetSkyboxFile(filename, face);\n // We define what to do when the promise is resolved with the then() call,\n // and what to do when the promise is rejected with the catch() call\n myPromise.then((status) => {\n handleTextureLoaded(SkyboxImages[face], face)\n console.log(\"Yay! got the file\");\n })\n .catch(\n // Log the rejection reason\n (reason) => {\n console.log('Handle rejected promise (' + reason + ') here.');\n });\n }", "function r(){var e=this;this.promise=new a.default(function(t,n){e.resolve=t,e.reject=n})}", "async function myPromise (){\n return \"This is my promise\"\n}", "function query_promise_then(result) {\n console.log(\"# result=\"+JSON.stringify(result));\n if(result.type!==\"menupage_url\"||result.url===\"\") {\n if(result.type===\"facebook\") {\n console.log(\"THIS IS FACEBOOK\");\n my_query.fb_about_url=result.url.replace(/(facebook\\.com\\/[^\\/]+).*$/,\"$1\")\n .replace(/facebook\\.com\\//,\"facebook.com/pg/\").replace(/\\/$/,\"\")+\"/about/?ref=page_internal\";\n let fb_promise=MTP.create_promise(my_query.fb_about_url,MTP.parse_FB_about,parse_fb_about_then);\n my_query.begin_fb=true;\n my_query.fields[result.type]=result.url;\n }\n else {\n my_query.done[result.type]=true;\n my_query.other_menus_list.sort(Item.cmp);\n console.log(\"my_query.other_menus_list=\"+JSON.stringify(my_query.other_menus_list));\n my_query.fields[result.type]=my_query.other_menus_list.length>0?my_query.other_menus_list[0].text:\"\";\n }\n \n\n submit_if_done();\n }\n else {\n\n my_query[result.type]=result.url;\n var promise=MTP.create_promise(my_query[result.type],find_menu_page,find_menu_then,function(response) {\n console.log(\"Failed menupages\");\n my_query.fields[result.type]=\"\";\n my_query.done[result.type]=true;\n submit_if_done();\n });\n }\n\n }", "async payBack() {\n return await new Promise(res => {\n console.log(\"payBack entered\");\n });\n }", "function getComentarioPromise(num, debug) {\n return new Promise((resolve, reject) => {\n let xhr = new XMLHttpRequest\n xhr.open('get', 'https://jsonplaceholder.typicode.com/comments/' + num)\n xhr.addEventListener('load', () => {\n if (xhr.status == 200) {\n let respuesta = JSON.parse(xhr.response)\n //console.log(typeof respuesta)\n if (debug) console.log(respuesta)\n resolve(respuesta)\n }\n else {\n let error = {\n title: 'Error Status Ajax',\n body: xhr.status\n }\n reject(error)\n }\n })\n xhr.addEventListener('error', e => { \n let error = {\n title: 'Error General Ajax',\n body: e\n }\n reject(error)\n })\n xhr.send()\n })\n}", "function test_and_load (filename){//start function test_and_load\r\n\r\n var promise = new process.Promise();\r\n\r\n fs.stat(filename).addCallback(function(stat){//start funcion anonima\r\n\r\n if(!stat.isFile()){\r\n promise.emitError(error);\r\n\r\n return;\r\n\r\n }//end if\r\n\r\n //otra manera de leer un archivo dentro de\r\n fs.readFile(filename).andCallback(function (data){//start function anonima\r\n\r\n promise.emitSuccess(data);\r\n\r\n //end function anonima\r\n }).addErrback(function(error){//start function anonima\r\n\r\n\r\n promise.emitError(function(error){\r\n\r\n });//end function anonima\r\n\r\n\r\n }).addErrback(function(error){\r\n\r\n promise.emitError(error);\r\n\r\n });//end function anonima\r\n\r\n return promise;\r\n\r\n});\r\n}//end function test_and_load", "resolvePromise(a) {\n return delay(100).then( ()=> a + ' dog');\n }", "function myFunc (num){\r\n\r\n if(num>10){\r\n return Promise.resolve(num)\r\n }\r\n else{\r\n return Promise.reject(num)\r\n }\r\n\r\n}", "async function asyncPromiseAll() {\n //PLACE YOUR CODE HERE:\n}", "constructor() {\n this.promise = Promise.resolve();\n this.queued = 0;\n this.complete = 0;\n }", "async function main(){\n try{\n const usuario= await obterUsuario();\n // const telefone = await obterTelefone(usuario.id);\n // const endereco = await obterEnderecoAsync(usuario.id);\n\n //o promise all permite fazer com que as funcoes nele executem ao `mesmo tempo`\n const resultado = await Promise.all(\n [\n obterTelefone(usuario.id),\n obterEnderecoAsync(usuario.id)\n ]\n )\n console.log(`\n Nome:${usuario.nome}\n Telefone:${resultado[0].telefone}\n Endereco:${resultado[1].rua}\n `);\n\n }catch(error){\n console.error(`Deu ruim`,error)\n }\n\n}", "function myAsyncOperation() {\n return new Promise((resolve, reject) => {\n doSomethingAsynchronous((err, value) => {\n if (err) reject(err);\n else resolve(value);\n });\n });\n}", "function promisePost(url){\n return new Promise(function(resolve, reject){\n\n var xhr2 = new XMLHttpRequest();\n xhr2.open(\"POST\", \"http://localhost:3000/api/cameras/order\", true);\n xhr2.setRequestHeader(\"Content-Type\", \"application/json\");\n\n xhr2.onreadystatechange = function() {\n \n if (xhr2.readyState === 4) {\n resolve(xhr2.response);\n \n } else if (this.readyState == 4 && this.status == 404){\n reject(Error('erreur 404' + request.statusText)); \n }\n }\n \n xhr2.send(JSON.stringify(body));\n })//fin de la fonction Promise 1ere partie\n}", "function promiseTask() {\n return Promise.resolve(\"the value is ignored\");\n}", "function myFunction2 () {\n return Promise.resolve('Hello')\n}", "function retornarValor() {\n return new Promise (resolve => {\n setTimeout(() => resolve(10), 5000)\n })\n}", "function $Promise(executor){\n if (typeof executor !== 'function'){\n throw new TypeError ('executor is not a function')\n };\n this._handlerGroups= [];\n this._state = 'pending';\n\n\n executor(this._internalResolve.bind(this), this._internalReject.bind(this))\n\n}", "_resolve() {\n // Prevent loopback.\n const promise = this._promise;\n if (!promise) {\n this.dispose();\n return;\n }\n this._promise = null;\n ArrayExt.removeFirstOf(Private.launchQueue, promise.promise);\n this.dispose();\n promise.resolve();\n }", "function retornaValor() {\r\n return new Promise(resolve => {\r\n setTimeout(() => resolve(10), 5000);\r\n });\r\n}", "_resolve(button) {\n // Prevent loopback.\n const promise = this._promise;\n if (!promise) {\n this.dispose();\n return;\n }\n this._promise = null;\n ArrayExt.removeFirstOf(Private.launchQueue, promise.promise);\n const body = this._body;\n let value = null;\n if (button.accept &&\n body instanceof Widget &&\n typeof body.getValue === 'function') {\n value = body.getValue();\n }\n this.dispose();\n promise.resolve({ button, value });\n }", "function wrapInPromise(func){\r\n var promise = new Promise((resolve, reject) => {\r\n resolve(func);\r\n });\r\n return promise;\r\n}", "function clickToActHandler(paramStr) {\n return new Promise(function (resolve, reject) {\n try {\n let params = JSON.parse(paramStr);\n var phNo = params.value; //Retrieve the phone number to dial from parameters passed by CIF\n log(\"Click To Act placing a phone call to \" + phNo);\n $(\"#dialerPhoneNumber\").val(phNo);\n expandPanel(); //Programatically expand the panel if required\n placeCall(); //Make the call\n resolve(true);\n }\n catch (error) {\n reject(error);\n }\n });\n\n}", "async function AppelApi(parfunc=api_tan.GenericAsync(api_tan.getTanStations(47.2133057,-1.5604042)),\nretour=function(par){console.log(\"demo :\" + JSON.stringify(par))}) {\n let demo = await parfunc \n retour(demo);\n // console.log(\"demo : \" + JSON.stringify(demo));\n}", "function callPlugins() { return Promise.resolve(); }", "handleAuthorizationCode(req) {\n return new Promise((resolve,reject)=> {\n\n });\n }", "function clickToActHandler(paramStr) {\n return new Promise(function (resolve, reject) {\n try {\n let params = JSON.parse(paramStr);\n var phNo = params.value; //Retrieve the phone number to dial from parameters passed by CIF\n log(\"Click To Act placing a phone call to \" + phNo);\n $(\"#dialerPhoneNumber\").val(phNo);\n expandPanel(); //Programatically expand the panel if required\n placeCall(); //Make the call\n resolve(true);\n }\n catch (error) {\n reject(error);\n }\n });\n \n}", "entry (cfg) {\n // promises are made in constructor\n }", "function _fpWait() {\n let ms = 8000;\n return new Promise(resolve => setTimeout(resolve, ms));\n }", "function query_promise_then(response) {\n console.log(\"generic=\"+response.result);\n my_query.fields.genericname1=response.result;\n add_to_sheet();\n var promise=new Promise((resolve,reject)=>{\n do_generic_query(resolve,reject);\n });\n promise.then(submit_if_done).catch(function(val) { console.log(\"Failed at this queryPromise \" + val); GM_setValue(\"returnHit\"+MTurk.assignment_id,true); });\n\n }", "function testPromiseFunction(a,b){\n return new Promise((resolve,reject)=>{\n if(a<10||b<10){\n reject(\"numbers must be greater then 10\");\n }\n else{\n resolve(a*b);\n }\n });\n }", "then(onFulfilled) {\n const promise = privateProps.promise.get(this);\n return promise.then(onFulfilled);\n }", "_insertTestToken(){\n var self = this;\n if (!process.env.VCAP_SERVICES){\n var doc = {\n type: \"SESSION\",\n cn: 'BDD - Mocha Test Automation',\n uid: \"000000631\",\n mail: \"[email protected]\",\n expiration: moment().add(1, 'years').format(),\n cleanUp: moment().add(1, 'years').format(),\n token: this.tests.token\n };\n\n let options = {\n design: 'session',\n view: 'getAllSessions',\n query: {keys: [doc.token]}\n };\n\n this.select(options)\n .then((result) => {\n if (Array.isArray(result) && result.length === 0) {\n self.insert(doc); //is a promise but I dont care when it will be fulfilled.\n }\n });\n }\n }", "async function main() {\n // await in front of whatever is resolved from a fct and then returned into a const for instance\n const name = await myPromise;\n name;\n}", "async function runPromise(dispatch, type, promise) {\n try {\n dispatch({ type: \"SET_APP_CALLBACK_IN_PROGRESS\", isInProgress:true });\n const payload = await promise;\n dispatch({ type: \"SET_APP_CALLBACK_IN_PROGRESS\", isInProgress:false });\n dispatch({ type, payload });\n } catch (error) {\n console.log(error);\n dispatch({ type: \"SET_APP_CALLBACK_IN_PROGRESS\", isInProgress:false });\n }\n}" ]
[ "0.7062459", "0.664492", "0.65898395", "0.6557439", "0.6523006", "0.64700747", "0.644596", "0.6423541", "0.6390327", "0.6390327", "0.63475287", "0.6312212", "0.6250894", "0.62361705", "0.62361705", "0.62306494", "0.6223985", "0.62182105", "0.62127733", "0.62115204", "0.61904263", "0.61852294", "0.6158307", "0.61564606", "0.6147793", "0.61382014", "0.6131043", "0.61287695", "0.610067", "0.60686636", "0.60667664", "0.6060324", "0.60565186", "0.6046114", "0.604125", "0.6038419", "0.60375637", "0.60303223", "0.60217553", "0.60186344", "0.60024625", "0.60021764", "0.6001425", "0.598007", "0.597435", "0.5971997", "0.5956698", "0.5956543", "0.59463876", "0.59442025", "0.5933767", "0.5918853", "0.5895139", "0.5894928", "0.58935434", "0.58888596", "0.58755726", "0.5874105", "0.5861538", "0.58545333", "0.58476114", "0.58449924", "0.58193576", "0.58010423", "0.5798314", "0.5797918", "0.5797234", "0.579633", "0.57886726", "0.5782023", "0.5781697", "0.5779305", "0.57787347", "0.577723", "0.57702947", "0.5768724", "0.576819", "0.5763581", "0.57609886", "0.5751523", "0.57473576", "0.5732707", "0.57285416", "0.57228243", "0.5720713", "0.5715861", "0.5701218", "0.5698645", "0.5698144", "0.56970936", "0.5690961", "0.56886554", "0.5684465", "0.5679867", "0.5678114", "0.56755096", "0.5667982", "0.56604564", "0.5659959", "0.56544214", "0.5651758" ]
0.0
-1
Called when the user types a character into the status update box.
handleChange(e) { // Prevent the event from "bubbling" up the DOM tree. e.preventDefault(); this.setState({value: e.target.value}); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function updateTypingIndicator() {\n\t\t\t\tvar typingIndicationMessage='Typing: ';\n\t\t\t\t\n\t\t\t\tvar names = Array.from(typingMembers).slice(0,3);\n\t\t\t\t\n\t\t\t\tif (typingMembers.length) {\n\t\t\t\t\ttypingIndicationMessage += names.join(', ');\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (typingMembers.size > 3) {\n\t\t\t\t\ttypingIndicationMessage += ', and ' + (typingMembers.size-3) + 'more';\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (typingMembers.length) {\n\t\t\t\t\ttypingIndicationMessage += '...';\n\t\t\t\t} else {\n\t\t\t\t\ttypingIndicationMessage = '';\n\t\t\t\t}\n\t\t\t\t// console.log(this.typingIndicationMessage);\n\t\t\t\t$('#typing-indicator').text(typingIndicationMessage);\n\n}", "function onInput(){\n\t\n\tvar value = cliptext.value\n\t// we seem to have pressed backspace on android\t\n\tif(value.length === 4 && value === androidBackspace){\n\t\tcliptext.value = magicClip\n\t\tcliptext.selectionStart = defaultStart\n\t\tcliptext.selectionEnd = defaultEnd\n\t\tif(keyDownTriggered){\n\t\t\tkeyDownTriggered = false\n\t\t\tbus.postMessage({\n\t\t\t\tfn:'onKeyDown',\n\t\t\t\trepeat: 1,\n\t\t\t\tcode: 8\n\t\t\t})\n\t\t\tbus.postMessage({\n\t\t\t\tfn:'onKeyUp',\n\t\t\t\trepeat: 1,\n\t\t\t\tcode: 8\n\t\t\t})\n\t\t}\n\t\treturn\n\t}\n\t// Something changed from our clipboard-set to now\n\tif(value !== lastClipboard){\n\t\tlastClipboard = ''\n\t\tcliptext.value = magicClip\n\t\tlastStart = cliptext.selectionStart = defaultStart\n\t\tlastEnd = cliptext.selectionEnd = defaultEnd\n\t\t// special character accent popup \n\t\tif(defaultStart === 3 && value.charCodeAt(2) !== magicClip.charCodeAt(1)){\n\t\t\tbus.postMessage({\n\t\t\t\tfn:'onKeyPress',\n\t\t\t\tchar:value.charCodeAt(2),\n\t\t\t\tspecial:1,\n\t\t\t\trepeat: 1\n\t\t\t})\n\t\t}\n\t\t// the main keypress entry including multiple characters\n\t\t// like swipe android keyboards \n\t\telse for(var i = 0, len = value.length - 2 - defaultStart; i < len; i++){\n\t\t\tvar charcode = value.charCodeAt(i + defaultStart)\n\n\t\t\tvar msg = {\n\t\t\t\tfn:'onKeyPress',\n\t\t\t\tchar:charcode,\n\t\t\t\trepeat: 1\n\t\t\t}\n\t\t\t// if we are more than one character let the otherside know\n\t\t\t// about this (for instance for undo handling)\n\t\t\tif(len>1){\n\t\t\t\tmsg.groupIndex = i\n\t\t\t\tmsg.groupLen = len\n\t\t\t}\n\t\t\t// ignore newlines and magicClip values\n\t\t\tif(charcode !== 10 && charcode !== magicClip.charCodeAt(1)) bus.postMessage(msg)\n\t\t}\n\t}\n}", "function updateTyping () {\n \n if (!typing) {\n typing = true;\n socket.emit('typing', {name:username});\n }\n lastTypingTime = (new Date()).getTime();\n\n setTimeout(function () {\n var typingTimer = (new Date()).getTime();\n var timeDiff = typingTimer - lastTypingTime;\n if (timeDiff >= TYPING_TIMER_LENGTH && typing) {\n socket.emit('stop typing', {name:username});\n typing = false;\n }\n }, TYPING_TIMER_LENGTH);\n \n }", "textBoxDidUpdate() {\n // user is typing because the value of the textbox just changed\n this.isTyping = true;\n this.lastTypingTime = (new Date()).getTime();\n // Create Timer event\n setTimeout(() => {this.checkTyping()}, this.typingTimeout);\n }", "function typing_status(status) {\n\t// We don't care about the response or even if the sever gets it.. nothing important!\n\t$.post('/api/typing_status', { \"chat_id\":chat_id, \"status\":status, \"token\": token });\n}", "function update() {\n // give browser time to add current letter\n setTimeout(function() {\n // prevent whitespace from being collapsed\n tag.html(element.val().replace(/ /g, '&nbsp'));\n // clamp length and prevent text from scrolling\n var size = Math.max(min, Math.min(max, tag.width() + offset));\n if (size < max)\n element.scrollLeft(0);\n // apply width to element\n element.width(size);\n settings_resize();\n }, 0);\n }", "function updateTyping () {\n if (connected) {\n if (!typing) {\n typing = true;\n socket.emit('typing');\n }\n lastTypingTime = (new Date()).getTime();\n\n setTimeout(function () {\n var typingTimer = (new Date()).getTime();\n var timeDiff = typingTimer - lastTypingTime;\n if (timeDiff >= TYPING_TIMER_LENGTH && typing) {\n socket.emit('stop typing');\n typing = false;\n }\n }, TYPING_TIMER_LENGTH);\n }\n }", "function updateTyping () {\n if (connected) {\n if (!typing) {\n typing = true;\n socket.emit('typing');\n }\n lastTypingTime = (new Date()).getTime();\n\n setTimeout(function () {\n var typingTimer = (new Date()).getTime();\n var timeDiff = typingTimer - lastTypingTime;\n if (timeDiff >= TYPING_TIMER_LENGTH && typing) {\n socket.emit('stop typing');\n typing = false;\n }\n }, TYPING_TIMER_LENGTH);\n }\n }", "function updateTyping () {\n if (connected) {\n if (!typing) {\n typing = true;\n socket.emit('typing');\n }\n lastTypingTime = (new Date()).getTime();\n\n setTimeout(function () {\n var typingTimer = (new Date()).getTime();\n var timeDiff = typingTimer - lastTypingTime;\n if (timeDiff >= TYPING_TIMER_LENGTH && typing) {\n socket.emit('stop typing');\n typing = false;\n }\n }, TYPING_TIMER_LENGTH);\n }\n }", "function updateTyping () {\n if (connected) {\n if (!typing) {\n typing = true;\n socket.emit('typing');\n }\n lastTypingTime = (new Date()).getTime();\n\n setTimeout(function () {\n var typingTimer = (new Date()).getTime();\n var timeDiff = typingTimer - lastTypingTime;\n if (timeDiff >= TYPING_TIMER_LENGTH && typing) {\n socket.emit('stop typing');\n typing = false;\n }\n }, TYPING_TIMER_LENGTH);\n }\n }", "function updateTyping () {\n if (connected) {\n if (!typing) {\n typing = true;\n socket.emit('typing');\n }\n lastTypingTime = (new Date()).getTime();\n\n setTimeout(function () {\n var typingTimer = (new Date()).getTime();\n var timeDiff = typingTimer - lastTypingTime;\n if (timeDiff >= TYPING_TIMER_LENGTH && typing) {\n socket.emit('stop typing');\n typing = false;\n }\n }, TYPING_TIMER_LENGTH);\n }\n }", "function updateTyping () {\n if (connected) {\n if (!typing) {\n typing = true;\n socket.emit('typing', {\n target: target,\n });\n }\n lastTypingTime = (new Date()).getTime();\n\n setTimeout(function () {\n var typingTimer = (new Date()).getTime();\n var timeDiff = typingTimer - lastTypingTime;\n if (timeDiff >= TYPING_TIMER_LENGTH && typing) {\n socket.emit('stop typing', {\n target: target,\n });\n typing = false;\n }\n }, TYPING_TIMER_LENGTH);\n }\n }", "function handleKeyDown(e) {\n counter = counter + 1;\n if (counter === 1) {\n socket.emit('typing', name)\n }\n window.clearTimeout(timer);\n}", "function onInputTextChanging() {\n // Get the input text.\n var inputText = $('#input').html();\n\n // Has any text been entered?\n if (inputText.length > 0) {\n // Clear the default placeholder text.\n $('#inputPlaceholder').text(\"\");\n\n // Show an enabled icon on the send button.\n document.getElementById(\"sendButton\").className = \"sendButton active\";\n } else {\n // Replace the default placeholder text.\n $('#inputPlaceholder').text(\"Enter a message\");\n\n // Show a disabled icon on the send button.\n document.getElementById(\"sendButton\").className = \"sendButton\";\n }\n\n // Start a typing timer if not already started.\n if (!timeStartedTyping) {\n // When the user first starts typing, record the time.\n timeStartedTyping = new Date().getTime();\n } else if (!timeIsTypingSent &&\n new Date().getTime() - timeStartedTyping >= 5000) {\n // If isTyping has not been sent, and the user has typed 5 seconds ago,\n // send isTyping.\n timeIsTypingSent = new Date().getTime();\n messenger.chatTyping(selectedChatId);\n } else if (timeIsTypingSent &&\n new Date().getTime() - timeIsTypingSent >= 30000) {\n // If isTyping has not been sent for 30 seconds, send it.\n timeIsTypingSent = new Date().getTime();\n messenger.chatTyping(selectedChatId);\n }\n}", "function keyTyped() {\n letter = key;\n}", "handleInput(event) {\n\t\t\tthis.insertCharacter(event.which);\n\t}", "function sendUpdateTyping() {\n if (connected) {\n if (!typing) {\n typing = true;\n socket.emit('typing');\n }\n }\n lastTypingTime = (new Date()).getTime();\n $timeout(function () {\n var typingTimer = (new Date()).getTime();\n var timeDiff = typingTimer - lastTypingTime;\n if (timeDiff >= TYPING_TIMER_LENGTH && typing) {\n socket.emit('stop typing');\n typing = false;\n }\n }, TYPING_TIMER_LENGTH)\n }", "updateInputLabel(key)\n {\n switch(key.keyCode) \n {\n\n case 8:\n\n this.typeInput = this.typeInput.substring(0, this.typeInput.length - 1);\n\n break;\n\n default:\n\n let char = String.fromCharCode(key.keyCode).toString();\n\n if (char.length > 0 && char.length < 2) {\n\n this.typeInput += char;\n }\n break;\n\n }\n }", "function send_input(char) {\n\tget_request('php_send_handler.php?char='+char, draw_command_sent, do_nothing);\n\tif(char == 's')\n\t\tis_scanning = true;\n\telse\n\t\tis_scanning = false;\n\treturn false;\n}", "function begin_typing() {\t\t\t\t\t\t/*FUNCTION CONTROLLING TYPEWRITING EFFECT ---- */\r\n\tif (i < txt[type_flag].length) {\r\n\t\tdocument.getElementById(\"my_info_p\").innerHTML += txt[type_flag].charAt(i);\r\n\t\ti++;\r\n\t\tsetTimeout(begin_typing, speed);\r\n\t}\r\n\tif (i == txt[type_flag].length) {\r\n\t\tdocument.getElementById(\"my_info_p\").innerHTML += '<br>';\r\n\t\ttype_flag++;\r\n\t\ti = 0;\r\n\t\tbegin_typing();\r\n\t}\r\n\r\n}", "typeCharacter() {\n if (this.running_) {\n this.queryCursor_++;\n this.textElement_.innerHTML = this.query_.substring(0, this.queryCursor_);\n if (this.queryCursor_ > this.query_.length) {\n this.stop();\n this.grid_.createNewCell(this.rowIndex_, this.colIndex_);\n } else {\n this.typeDelay().then(this.typeCharacter.bind(this));\n }\n }\n }", "function updateUI(curr) {\r\n if (curr <= MAX_CHARACTERS) {\r\n handleRemaining(MAX_CHARACTERS - curr);\r\n } else if (curr > MAX_CHARACTERS) {\r\n handleOver(curr - MAX_CHARACTERS);\r\n } else {\r\n throw new Error(\"You have done the impossible\");\r\n }\r\n}", "function characterDisplay() {\r\n const newChannelInput = document.querySelector('input#newChannel');\r\n newChannelInput.addEventListener('focusin', displayChars);\r\n newChannelInput.addEventListener('keyup', displayChars);\r\n newChannelInput.addEventListener('focusout', displayChars);\r\n}", "function onKeyDown(e) {\n\n\t\t\tif(e.keyCode === 13) {\n\t\t\t\tparseInput(input.value)\n\n\t\t\t\tthis.lastUser = null\n\t\t\t\tthis.lastMessage = null\n\t\t\t\tinput.value = ''\n\t\t\t}\n\n\t\t\t// input.value = last user to talks name\n\t\t\telse if(e.keyCode === 40) {\n\t\t\t\tthis.lastUser = this.lastUser-1 || messages.length-1\n\t\t\t\tinput.value = (messages[this.lastUser] ? messages[this.lastUser].nick : ziggy.getNick()) + ' '\n\t\t\t\tsetTimeout(function(){\n\t\t\t\t\tinput.setSelectionRange(input.value.length, input.value.length)\n\t\t\t\t}, 0)\n\t\t\t}\n\n\t\t\t// input.value = last message\n\t\t\telse if(e.keyCode === 38) {\n\t\t\t\tthis.lastMessage = this.lastMessage-1 || messages.length-1\n\t\t\t\tinput.value = (messages[this.lastMessage] ? messages[this.lastMessage].text : '') + ' '\n\t\t\t\tsetTimeout(function(){\n\t\t\t\t\tinput.setSelectionRange(input.value.length, input.value.length)\n\t\t\t\t}, 0)\n\t\t\t}\n\t\t}", "onTextChange()\n {\n let data = this.pad.getContents()\n\n // add type\n data[\"@type\"] = \"mycelium::rich-text\"\n\n this.shroom.setData(this.key, data)\n }", "function changeEmojiHandler(event) {\n var meaning = emojiDictionary[event.target.value];\n console.log(event.target.value);\n // setUserInput(event.target.value);\n if (meaning === undefined) {\n meaning = \"Not Available\";\n }\n setEmojiMeaning(meaning);\n }", "function updateChar() {\n tweet1Count.textContent = tweet1.textLength;\n}", "function typing()\n\n\t{\n\t\tsocket.emit('typing', true)\n\t}", "_keyupHandler() {\n\t\tthis._error.classList.remove('shown');\n\n\t\tthis.convertInputValue();\n\t}", "function handleTyping(event) {\r\n // Check if the input has text, to avoid blank text to be inserted on the array\r\n var hasText = !!event.target.value && event.target.value.trim() !== '';\r\n if (!hasText) {\r\n // Clear input if its empty or blank spaces\r\n clearInput();\r\n return;\r\n }\r\n\r\n if (event.key === 'Enter') {\r\n // Check if is to edit a item or to insert an item\r\n if (isEditing) {\r\n // if is editing call function updateName with the especified event target value\r\n updateName(event.target.value);\r\n } else {\r\n insertName(event.target.value);\r\n }\r\n //After finishing its not editing anymore;\r\n isEditing = false;\r\n clearInput();\r\n render();\r\n }\r\n }", "static textChanged (text) {\n AppDispatcher.dispatch({'action': ActionTypes.TEXT_CHANGED, 'text': text});\n }", "function updateInput() {\n\talert('Input registered')\n}", "typingEvent(event){\n\t if (event.keyCode !== 9 && event.keyCode !== 18) // TAB and ALT\n\t\t if (event.keyCode === 13){\n\t\t\t this.sendMessageAction();\n\t\t\t this.$.inputMessage.value = \"\";\n\t \t\t}\n\t \t\telse\n\t \t\t\tthis._setSendMessage({type:'TYPING'});\n\t \t\t\n }", "updateInput (value) {\n this.setState({\n characters: value\n });\n }", "function user_is_typing(type, id)\n{\n\tvar URL = $.base_url + 'ajax/chat_type_ajax.php';\n\tvar timer, timeout = 750;\n \n $(type).keyup(function()\n {\n if (typeof timer != undefined)\n clearTimeout(timer);\n\n $.post(URL, 'status=typing_'+id, function(res) {});\n\t\t\n timer = setTimeout(function()\n {\n\t\t\t$.post(URL, 'status=stopped', function(res) {});\n }, timeout);\n });\t\n}", "_ackTypingHandler(json){\n \n var playTyping = false;\n this.isTyping = true;\n this.updateScroll();\n \n if ((this.countTypingMessages === 16) || \n (this.countTypingMessages === 32))\n playTyping = true;\n if (this.countTypingMessages === 50){\n playTyping = true;\n this.countTypingMessages--;\n }\n else{\n this.countTypingMessages--;\n if (this.countTypingMessages === -1)\n this.countTypingMessages = 50;\n }\n \n if ((json.user !== CooperativeEditorParticipants.userName) && (playTyping)){\n this.domHost.playSound(\"typing\", json.effect, json.position);\n }\n }", "function updateText(ev) {\n setText(ev.target.value);\n }", "function updateCharCount(target) {\n var length = target.value.length;\n displayMessage(length + \" characters\");\n}", "function updateComputerInput() {\n computerGuess.value = computerGuessWord();\n}", "function userinput()\n{\n\twindow.addEventListener(\"keydown\", function (event) {\n\t\tif (event.defaultPrevented) {\n\t\t\treturn; // Do nothing if the event was already processed\n\t\t}\n\n\t\tswitch (event.key) {\n\t\t\tcase \"b\":\n\t\t\t\t// code for \" \" key press.\n\t\t\t\tif(baw==0)\n\t\t\t\t{\n\t\t\t\t\tbaw=1;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbaw=0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"l\":\n\t\t\t\t// code for \" \" key press.\n\t\t\t\tif(lighton==0)\n\t\t\t\t{\n\t\t\t\t\tlighton=1;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tlighton=0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \" \":\n\t\t\t\t// code for \" \" key press.\n\t\t\t\tconsole.log(hoverbonus);\n\t\t\t\tif(hoverbonus>0)\n\t\t\t\t{\n\t\t\t\t\tend-=1;\n\t\t\t\t\thoverbonus-=1;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"ArrowDown\":\n\t\t\t\t// code for \"down arrow\" key press.\n\t\t\t\tcharacter.tick(\"d\",ontrain);\n\t\t\t\tbreak;\n\t\t\tcase \"ArrowLeft\":\n\t\t\t\t// code for \"left arrow\" key press.\n\t\t\t\tpol.tick(\"l\");\n\t\t\t\td.tick(\"l\");\n\t\t\t\tcharacter.tick(\"l\",ontrain);\n\t\t\t\tif(character.getpos()[0]==-6)\n\t\t\t\t{\n\t\t\t\t\tdead=1;\n\t\t\t\t\tend+=1;\n\t\t\t\t\tpol.tick(\"r\");\n\t\t\t\t\td.tick(\"r\");\n\t\t\t\t\tcharacter.tick(\"r\",ontrain);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"ArrowRight\":\n\t\t\t\t// code for \"right arrow\" key press.\n\t\t\t\tpol.tick(\"r\");\n\t\t\t\td.tick(\"r\");\n\t\t\t\tcharacter.tick(\"r\",ontrain);\n\t\t\t\tif(character.getpos()[0]==6)\n\t\t\t\t{\n\t\t\t\t\tdead=1;\n\t\t\t\t\tend+=1;\n\t\t\t\t\tpol.tick(\"l\");\n\t\t\t\t\td.tick(\"l\");\n\t\t\t\t\tcharacter.tick(\"l\",ontrain);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn; // Quit when this doesn't handle the key event.\n\t\t}\n\n\t\t// Cancel the default action to avoid it being handled twice\n\t\tevent.preventDefault();\n\t}, true);\n\t// the last option dispatches the event to the listener first,\n\t// then dispatches event to window\n}", "_textBoxKeyUpHandler() {\n const that = this;\n\n that.value = that._getValueWithTextMaskFormat({ start: 0, end: that._mask.length }, that.textMaskFormat);\n }", "function keyTyped() {\n if (key === '0') {\n activeClass = 0;\n } else if (key === '1') {\n activeClass = 1;\n } else if (key === '7') {\n activeClass = 7;\n }\n}", "function frequencyTypeChanged() {\n if (this.value == 'ff') {\n all_data.forEach(function(character, i) {\n character.percentage = character.fanfiction_percentage;\n character.last_rank = i;\n });\n }\n else {\n all_data.forEach(function(character, i) {\n character.percentage = character.canon_percentage;\n character.last_rank = i;\n });\n }\n all_data.sort(function(a, b) {\n return b.percentage - a.percentage;\n });\n cur_display = all_data.slice(0,num_characters);\n\n update();\n }", "function textValidation(event) {\n event.preventDefault();\n // debugger;\n var keyPressed = event.key;\n var keyCode = event.keyCode;\n if (keyCode == 8) {\n typingInput.classList.add('shake');\n } else if (keyPressed !== parsedCurrentPrompt[currentPromptChar]) {\n typingInput.classList.add('shake');\n } else {\n typingInput.value += keyPressed;\n currentPromptChar++;\n winLevel();\n }\n}", "function handle_keypress(e) {\n var ch = (typeof e.which == \"number\") ? e.which : e.keyCode\n console.log(\"got char code:\", ch)\n if (ch == 97) { // 'a'\n grow_type_span()\n } else if (ch == 115) { // 's'\n shrink_type_span()\n } else if (ch == 113) { // 'q'\n remove_type_span()\n }\n}", "function userKeyup()\n{\n hasUserChanged = true;\n this.style.backgroundColor = \"rgb(63, 66, 69)\";\n}", "function updateChatTypingElementForSelectedChat() {\n var typingUsers = messenger.getTypingUsers(selectedChatId);\n\n if (typingUsers.length > 0) {\n var text = \"\";\n if (typingUsers.length == 1) {\n text = getContactName(typingUsers[0].regId) + ' is writing a message...';\n } else {\n text = getContactName(typingUsers[0].regId) + ' and ' + typingUsers.length + ' other(s) are writing a message...';\n }\n\n var isTypingText = '<div class=\"isTypingText\" '\n + DATA_BIND_PREFIX + DATA_BIND_PREFIX_CONTACT + correctHTMLAttributeName(typingUsers[0])\n + '=\"' + DATA_CONTACT_NAME + '\">' + text + '</div>';\n\n //Show a bar of \"XXX is writing a message\"\n //or \"XXX and 2 other(s) are writing a message\" on the conversation pane\n $('#isTypingText').html(isTypingText);\n $('#isTypingBar').show();\n } else {\n //hide the bar of \"XXX is writing a message\" from the conversation pane\n $('#isTypingBar').hide();\n }\n\n setBubbleListHeight();\n}", "function update() {\n let keyTracker = Events.getKeyTracker();\n character.updatePosition(keyTracker, level);\n character.move(level);\n character = switchMask(level, character);\n\n // RenderEngine.render(character, level);\n\n if (isAlive() && !hasEnded()) {\n setTimeout(update, 10);\n } else {\n RenderEngine.drawDeath(character);\n }\n }", "function type() {\n // Type as long as there are characters left in phrase\n if (char_index <= text[text_index].length) {\n if (!typing) set_typing(true);\n set_typed_text(text[text_index].substring(0, char_index++));\n setTimeout(type, type_delay);\n }\n // Call erase when finished\n else {\n set_typing(false);\n setTimeout(erase, new_delay);\n }\n }", "function doneTyping (event) {\n\t\t\t\treo_update_properties( r , $(event.target).siblings().html() , $(event.target).val() );\n\t\t\t\tconsole.log( $(event.target).siblings().html() );\n\t\t\t}", "function handleClick(character) {\r\n swapiSearch.setCharacter(character);\r\n }", "function startGame(){\n runTyping(\"Immer einmal mehr wie du...\");\n inputTextElement.value ='sag was'; \n}", "function handlePlayerChange() {\n currentPlayer = currentPlayer === \"X\" ? \"O\" : \"X\";\n //updating interface\n statusDisplay.innerHTML = currentPlayerTurn();\n}", "update() {\n this.character.update();\n }", "function pressIt()\n{\n $('#typing').keydown(function(keyPressed){\n if(keyPressed.which == 71)\n {\n window.alert(\"You have pressed g/G key!!\");\n }\n });\n \n}", "function keyTyped(){\n\t\tbackground(backgroundColor);\t\n\t\tif (key==='a'){\n\t\t\tbackgroundColor=255;\n\t }\telse if (key==='s'){\n\t\t backgroundColor=0;\n\t }\n\t}", "UpdateUserName(evt){\n if (evt.key === 'Enter') {\n this.setState({\n Username: evt.target.value });\n this.SendUpdate(evt.target.value,evt.target.value+\" Has Joined Chat!\")\n }\n}", "function buttonPressed(key) {\n time_press = millis();\n\n if (key == last_clicked && key != 0 && time_press - last_press < double_click_delay)\n incrementLastLetter();\n else if (key == 0) currently_typed = currently_typed.slice(0, -1);\n else if (key == 1) currently_typed += \"a\";\n else if (key == 2) currently_typed += \"d\";\n else if (key == 3) currently_typed += \"g\";\n else if (key == 4) currently_typed += \"j\";\n else if (key == 5) currently_typed += \"m\";\n else if (key == 6) currently_typed += \"p\";\n else if (key == 7) currently_typed += \"t\";\n else if (key == 8) currently_typed += \"w\";\n\n /* used for the autocomplete*/\n current_word = currently_typed.slice(currently_typed.lastIndexOf(\" \") + 1);\n autocomplete();\n console.log(\">\" + current_word + \"<\");\n\n if (last_clicked == 0 && key == 0) last_clicked = \"\";\n else last_clicked = key;\n last_press = time_press;\n}", "function doneTyping () {\n\tif (userIsTyping) {\n\t\tuserIsTyping = false;\n\t\tconsole.log('end typing');\n\t\tsocket.send('update_typing_state,0');\n\t}\n}", "handleKeyDown(event) {\n sendTyping({\n username: this.props.location.state.username,\n workspaceId: this.state.currentWorkSpaceId,\n });\n }", "function keyTyped() {\n\n // this function is called by the system whenever a key is typed\n var theKey = key;\n \n // PRESS 'a' to add mail\n if (theKey == 'a') {\n\t\taddMail();\n } \n \n // PRESS 'r' to reset mail\n if (theKey == 'r') {\n\t\tresetMail();\n }\n}", "updateTypedLetter(position, letter) {\n for (let i = 0, len = this.typedLetters.length; i < len; i++) {\n if (this.typedLetters[i].position.x === position.x && this.typedLetters[i].position.y === position.y) {\n this.typedLetters[i].letter = letter;\n this.lastTypedLetter = this.typedLetters[i];\n break;\n }\n }\n }", "function keyTyped(){\r\n if(key==='c'){\r\n clear();\r\n }\r\n}", "function doneTyping () {\n console.log(myInput);\n console.log(\"Sending Text\");\n getLocation\n .then(chrome.runtime.sendMessage(\n null,\n {\n type: 'keyup',\n text: myInput,\n URI: URI,\n name: inputName,\n coords: `${latitude}, ${longitude}`,\n }\n ))\n .then(myInput = '');\n \n}", "function statusUpdate(status) {\n var statusTxt = 'You have won $ ' + status + '!';\n $('#status-winningRound p').text(statusTxt);\n}", "update() {\r\n this.draw();\r\n inputChange();\r\n }", "function checkInput() {\n transformToUpper();\n if (!isStart) {\n showInitialMessage();\n } else {\n initmessageStatus();\n }\n renderTextColor();\n disableBth();\n}", "function onSubmitLetter(){\n\t\t\n\t\tif(myHangmanGame.isGameOver || myHangmanGame.allLettersFound) return;\n\t\t\n\t\t//console.log(\"Clicked \" + letterFieldEle.value);\n\t\t\n\t\tmyHangmanGame.userLetters(String(letterFieldEle.value).toLowerCase())\n\t\t \n\t\t//console.log(\"userletter \" + myHangmanGame.userLetters());\n\t\t\n\t\tonHangmanPanelAppear();\n\t\t\n\t\tif(!myHangmanGame.isLetterCorrect){\n\t\t\tfor(var i = 0; i < hangmanPanel.getNumChildren(); i++){\n\t\t\t\tif(hangmanPanel.children[i].alpha == 0){\n\t\t\t\t\thangmanPanel.children[i].alpha = 1;\n\t\t\t\t\tupdate = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tcreateLettersUserPanel(\"Letters Used: \" + myHangmanGame.userLetters())\n\t\t\n\t\tif( myHangmanGame.isGameOver || myHangmanGame.allLettersFound) {\n\t\t\tvar status = \"\";\n\t\t\tconsole.log(\"GAME OVER\");\n\t\t\tstatus = \"GAME OVER - \";\n\t\t\tif(myHangmanGame.allLettersFound){\n\t\t\t\tconsole.log(\"You Won\");\n\t\t\t\tstatus = status + \" You Won.\";\n\t\t\t}else{\n\t\t\t\tconsole.log(\"You Lost\");\n\t\t\t\tstatus = status + \" You Lost.\";\n\t\t\t}\n\t\t\t\n\t\t\tcreateTitle(\"Hangman - \" + status);\n\t\t}\n\t}", "function Window_CharacterInput() {\n this.initialize.apply(this, arguments);\n}", "function begin_typing_2() {\t\t\t\t\t\t/*FUNCTION CONTROLLING TYPEWRITING EFFECT ---- */\r\n\tif (i_2 < txt_2[type_flag_2].length) {\r\n\t\tdocument.getElementById(\"looking_for_info_p\").innerHTML += txt_2[type_flag_2].charAt(i_2);\r\n\t\ti_2++;\r\n\t\tsetTimeout(begin_typing_2, speed_2);\r\n\t}\r\n\tif (i_2 == txt_2[type_flag_2].length) {\r\n\t\tdocument.getElementById(\"looking_for_info_p\").innerHTML += '<br>';\r\n\t\ttype_flag_2++;\r\n\t\ti_2 = 0;\r\n\t\tbegin_typing_2();\r\n\t}\r\n\r\n}", "onKeyUp(field, value){\n\t\t//const newMessage = {type: 'message', uuid: uuidv4(), username: this.state.currentUser, [field]: value};\n //sendText(this.state.userSocket, newMessage);\n console.log(\"onKeyUp\", field, value)\n }", "textChange() {\n core.dxp.log.debug('Inside textChange');\n this.assignPlaceholderText();\n }", "function inputChange(e)\n {\n resetInput($(this));\n $(this).val($(this).val().toUpperCase());\n if($(this).val().length > 1){\n if($(this).val() == \"QU\"){\n $(this).val(\"Q\");\n }\n \n if($(this).val().length > 2){\n $(this).val($(this).val().slice(0,2));\n } else {\n var lastChar = $(this).val().slice(-1);\n if(isNumber(lastChar)){\n $(this).data('special', parseInt(lastChar));\n } else {\n $(this).data('special', 0);\n $(this).val(lastChar);\n }\n }\n }\n decorateInput($(this));\n }", "update() {\n this.nameText.text = 'Submit Name to Leaderboard:\\n ' + this.userName + '\\n(Submits on New Game)';\n\n }", "function _inputChar(char) {\n if(_charIsPrintable(char.charCodeAt(0))\n &&utils.isSelectable(document.activeElement)) {\n // add the char\n // FIXME: put at caretPosition/replace selected content\n document.activeElement.value += char;\n // fire an input event\n utils.dispatch(document.activeElement, {type: 'input'});\n }\n }", "function updateChat(msg) {\n\tconsole.log(\"recieved\");\n if (msg.data.startsWith(\"DATA;\")){\n \tvar data = msg.data.split(\";\");\n \tvar word = data[1];\n \tvar col = parseFloat(data[2]);\n \tvar row = parseFloat(data[3]);\n \tvar orientation = data[4];\n\n if (orientation == \"DOWN\"){\n \tvar c = checkCol($(\".c\"+col), row, col, false);\n \tfor (i in c){\n \t\t$(c[i]).val(word[i]);\n \t}\n \t$(c).attr(\"disabled\", \"disabled\");\n $(c).addClass(\"inactive\");\n } else if (orientation == \"ACROSS\"){\n \tvar r = checkRow($(\".r\"+row), col, row, false);\n \tfor (i in r){\n \t\t$(r[i]).val(word[i]);\n \t}\n \t$(r).attr(\"disabled\", \"disabled\");\n \t$(r).addClass(\"inactive\");\n }\n \n foundWords += 1;\n console.log(timer);\n if (foundWords == numWords && timer){\n \t$(\"#win\").toggle();\n \t\n }\n \n } else if (msg.data.startsWith(\"LETTER;\")) {\n \tconsole.log(\"msg data \" + msg.data);\n \tvar data = msg.data.split(\";\");\n \tvar col = parseFloat(data[1]);\n \tvar row = parseFloat(data[2]);\n \tvar letter = data[3];\n \t$(\".c\"+col+\".r\"+row).val(letter);\n \t$(\".c\"+col+\".r\"+row).attr(\"disabled\", \"disabled\");\n \t$(\".c\"+col+\".r\"+row).addClass(\"inactive\");\n \tconsole.log(\"should have exposed letter \");\n \t\n } else if (msg.data.startsWith(\"ANAGRAM\")) {\n \tconsole.log(\"msg data \" + msg.data);\n \tvar data = msg.data.split(\";\");\n \tvar col = parseFloat(data[1]);\n \tvar row = parseFloat(data[2]);\n \tvar orientation = data[3];\n \tvar wordId = data[4];\n \tvar anagram = data[5];\n \t$(\"#anagramList\").hide();\n \t$(\".anagramChoice\").text(\"the letters of \" + orientation + \" \" + wordId + \" are \" + \"'\" + anagram + \"'\");\n \t$(\"#hint2\").off();\n \t$(\"#hint2\").unbind('mouseenter mouseleave');\n \t$(\"#hint2\").css(\"background-color\", \"transparent\");\n } else if (msg.data.startsWith(\"**ALL**\")) {\n \tconsole.log(\"showing all\");\n \tconsole.log(msg.data);\n \tvar data = msg.data.split(\":\")[1].split(\"\\n\");\n \tfor (row in data){\n \t\tvar cols = data[row].split(\" \");\n \t\tfor (col in cols){\n \t\t\tvar letter = \"S\";\n \t\t\t$(\".c\"+col+\".r\"+row).val(cols[col]);\n \t\t\t$(\".c\"+col+\".r\"+row).attr(\"disabled\", \"disabled\");\n \t\t}\n \t}\n \tclearInterval(timerGlobal);\n \t$(\"#end\").text(\"new game\");\n \t$(\"#end2\").toggle();\n } else if (msg.data.startsWith(\"**END**\")) {\n \tvar data = msg.data.split(\":\");\n \tvar other = data[1];\n \tconsole.log(other);\n \tif (other==\"show\"){\n\t\t\t$(\"#alert span\").text(\"chose not to continue\");\n\t\t\tconvertToOnePlayer();\n \t} else {\n \t\t$(\"#end\").toggle();\n \t}\n } else if (msg.data.startsWith(\"**CONVERT**\")) {\n \tif (!$(\"#end\").is(\":visible\")){\n \t\t$(\".hiddenEnd\").toggle();\n \t}\n \tplayers = \"single\";\n \t$(\"textarea\").attr(\"disabled\",false);\n \t$(\".inactive\").attr(\"disabled\",\"disabled\");\n \tvar clues = msg.data.split(\"/:/\");\n \tvar player = $(\"#player\").text();\n \tconsole.log(clues.length-2);\n \tvar total = clues.length-2;\n\t\tvar html = \"<ul id='clues' class='total\"+total+\"'>\";\n\t\thtml+= \"<span style='color:white'>\"+player+\" CLUES</span>\";\n \tfor (var i in clues){\n \t\tif (i>0 && i<clues.length-1){\n\t\t\t\tvar data = clues[i].split(\";\");\n\t\t\t\tvar o = data[2];\n\t\t\t\tif (o==player){\n\t\t\t\t\tvar col = data[0];\n\t\t\t\t\tvar row = data[1];\n\t\t\t\t\tvar clue = data[3];\n\t\t\t\t\thtml+=\"<li>\"+$(\".c\"+col+\".r\"+row).next().text()+\" : \"+clue+\"</li>\";\n\t\t\t\t}\n \t\t}\n \t}\n \thtml+=\"</ul>\";\n\t\t$(html).insertAfter(\"#clues\");\n\t\ttimer = false;\n\t\ttimerGlobal = false;\n \t\n } else {\n\t\tif (players == \"double\"){\n\t\t\tif (loading < 2){\n\t\t\t\tloading ++;\n\t\t\t\tvar player = $(\"#player\").text();\n\t\t\t\tif (player == \"ACROSS\"){\n\t\t\t\t\tloading = 2;\n\t\t\t\t\t$(\"#wait\").toggle();\n\t\t\t\t\ttimerGlobal = startTimer();\n\t\t\t\t} else if (loading==2){\n\t\t\t\t\t$(\"#wait\").toggle();\n\t\t\t\t\ttimerGlobal = startTimer();\n\t\t\t\t} \n\t\t\t}\n\t\t\tvar data = JSON.parse(msg.data);\n\t\t var innerMessage = data.userMessage.split(\"<p>\")[1].split(\"</p>\")[0];\n\t\t console.log(\".\"+innerMessage+\".\");\n\t\t if (innerMessage==\"down left the chat \" || innerMessage==\"across left the chat \"){\n\t\t \t if (!$(\"#end2\").is(\":visible\")){\n\t\t\t \t convertToOnePlayer();\n\t\t \t }\n\t\t }\n\t\t insert(\"chat\", data.userMessage);\n\t\t}\n }\n}", "function handleKeyUp(e) {\n window.clearTimeout(timer); // prevent errant multiple timeouts from being generated\n timer = window.setTimeout(() => {\n counter = 0;\n socket.emit('typing-done', name)\n }, timeoutVal);\n}", "handleTextChange(e) {}", "function saveCharacterEdits(){}", "function typeCharacter( paramDoc, paramCharCode ) {\t\r\n\t// Local variable to extract information about cursor after operations\r\n\tvar newCursorCoords;\r\n\t// Determine if we typing normally, or overwriting a selected block, and act accordingly\r\n\tif ( paramDoc.isSelection ) {\r\n\t\tvar tmpSel = paramDoc.getCurrentSelection();\r\n\t\tvar newCursorCoords = paramDoc.replaceTextInRange( tmpSel.startLine, tmpSel.startColumn, tmpSel.endLine, tmpSel.endColumn, String.fromCharCode(paramCharCode) );\r\n\t}\r\n\telse newCursorCoords = paramDoc.insertText( String.fromCharCode(paramCharCode), cursorLine, cursorColumn );\r\n\t\r\n\tcursorColumn = newCursorCoords[1];\r\n}", "function inputOnchange()\n {\n if(checkRegex())\n {\n inputClearError();\n addTokenToList();\n updateTextarea();\n return;\n }\n inputError();\n }", "handleKeyUp(){\n\n }", "function updateCount() {\r\n var commentText = document.getElementById(\"comment\").value;\r\n // this variable is created using a function as its value with the parameters of the commentText variable\r\n var charCount = countCharacters(commentText);\r\n\r\n var wordCountBox = document.getElementById(\"wordCount\");\r\n // The variable will be update the visible at the bottom of the page so as you type it changes to match how many characters have been typed\r\n wordCountBox.value = charCount + \"/1000\";\r\n // this changes the input box if 1000 chars are exceeded so that its a red background and the font is white\r\n if (charCount > 1000) {\r\n wordCountBox.style.backgroundColor = \"red\";\r\n wordCountBox.style.color = \"white\";\r\n } else {\r\n wordCountBox.style.backgroundColor = \"black\";\r\n wordCountBox.style.color = \"white\";\r\n }\r\n}", "function syncCharacter(e){\n const value = e.target.value;\n characterAmountNumber.value = value;\n characterAmountRange.value = value;\n}", "function changeStatScreen(character){\n //update PlayerIndex of statScreen \n statScreen.SinglePlayer.PlayerIndex = character.index;\n statScreen.SinglePlayer.CharacterNameString = character.name;\n //clear all graphics drawn from the graphics reference\n singleGraphics.clear();\n //updates the name of the character whose stats are displayed\n //NOTE: Does not check to see if name will fit yet\n statScreen.SinglePlayer.CharacterName.setText((character.name).toUpperCase());\n //redraw health bar and update stats if on the single player screen\n if(!statScreen.ShowAll){\n updateSinglePlayerHealthBar(statScreen.CurrentTurn);\n updateSinglePlayerStatScreen(statScreen.CurrentTurn);\n }\n}", "function d3_keyup() {\n\n lastKeyDown = -1;\n // ctrl\n if (!d3.event.ctrlKey) {\n rect.on('mousedown.drag', null)\n .on('touchstart.drag', null);\n svg.classed('ctrl', false);\n }\n}", "function UpdateCharacter() {\n if (!stateVars.requireUpdate) {\n return;\n }\n\n //Using the SaveData async function to let us know when the stateVars are done updating so the parent component can update\n SaveData()\n .then(() => {\n onUpdate();\n })\n .catch((error) => {\n navigation.navigate(\"Error\", { userMessage: \"An error occurred when trying to update the ICRPG item list.\", errorMessage: error });\n })\n }", "function updateText(event) {\n let vv = event.target.value;\n\n ch_push(vv); // used to be ch_push(Number: vv)});\n\n// setText(vv); COMMENTED OUT FOR CH_PUSH\n }", "function autoCheckTyping() {\n checkIsTyping();\n setTimeout(autoCheckTyping, 3000);\n}", "function doneTyping () {\n //do something\n}", "update()\n {\n this.healthText.text = \"Health: \" + this.player.hp + \"/\" + this.player.maxHp;\n \n this.buildingText.text = \"Selected building: \" + this.player.buildings[this.player.selectedBuilding];\n }", "function updateCharacterCount() {\n\ttry {\n\t\tvar content = $(\"#insightContent\").val();\n\t\tvar size = content.length;\n\t\tvar percent = size / MAX_CHARACTERS_INSIGHT * 100;\n\t\t$(\"#currentCaractersNumbers\").html(size);\n\t\t$( \"#progressbar\" ).progressbar({\n\t\t\tvalue: percent\n\t\t});\n\t\t\n\t\tif( size > MAX_CHARACTERS_INSIGHT ) {\n\t\t\t$(\"#caracterNumbers\").addClass(\"tooMuchCharacters\");\n\t\t} else {\n\t\t\t$(\"#caracterNumbers\").removeClass(\"tooMuchCharacters\");\n\t\t}\n\t} catch(e) {}\n}", "function markAsTyped(letter) {\n\t\t\tfor (var i = 0; i < $scope.wordTypedTracker.length; i++) {\n\t\t\t\tif ($scope.wordTypedTracker[i].letter == letter && !$scope.wordTypedTracker[i].typed) {\n\t\t\t\t\t$scope.wordTypedTracker[i].typed = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}", "function txtInputChange(a){\n\tif (document.getElementById(\"text-input\").value.length === 1){\n\t\tstartTypingDate = +new Date();\n\t\tconsole.log(startTypingDate);\n\t}\n\tif (this.value.length-previousLength>1){this.value=''; alert('copy pasting not allowed!')} //reset the input if something gets copy pasted into it\n\tif (currentText.indexOf(this.value) === 0){ //input is congruent with the text\n\t\tdocument.getElementById(\"text-was-typed\").innerHTML = this.value;\n\t\tdocument.getElementById(\"text-wrong\").innerHTML = '';\n\t\tdocument.getElementById(\"text-next-char\").innerHTML = currentText.slice(this.value.length,this.value.length+1);\n\t\tdocument.getElementById(\"text-to-type\").innerHTML = currentText.slice(this.value.length+1);\n\t\tdocument.getElementById(\"text-input\").classList.remove('error');\n\t\tif (this.value.length===currentText.length-1){//input equals text (ie. race complete)\n\t\t\tdocument.getElementById(\"scribo-box\").classList.add('complete');\n\t\t\tdocument.getElementById(\"text-input\").hidden = true;\n\t\t\tdocument.getElementById(\"main-menu\").hidden = false;\n\t\t\tclearInterval(wpmInterval)\n\t\t\tdocument.getElementById('race-info-box').hidden = false;\n\t\t\tdocument.getElementById('race-info-time').innerHTML=Math.floor(((+new Date() - startTypingDate)/1e3)/60)+\"m \"+(Math.floor((+new Date() - startTypingDate)/1e3)%60)+'s';\n\t\t\tdocument.getElementById('race-info-wpm').innerHTML= Math.round(document.getElementById(\"text-input\").value.length*12/((+new Date() - startTypingDate)/1e3));\n\t\t} else {//input does not equal text\n\t\t\tdocument.getElementById(\"scribo-box\").classList.remove('complete');\n\t\t}\n\t} else { //input does not match text\n\t\tdocument.getElementById(\"scribo-box\").classList.remove('complete');\n\t\tdocument.getElementById(\"text-next-char\").innerHTML = '';\n\t\tdocument.getElementById(\"text-input\").classList.add('error');\n\t\tfor (let i = 0; i<currentText.length; i++){\n\t\t\tif (currentText.charAt(i)!==this.value.charAt(i)){//find the first character where text does not match input\n\t\t\t\tdocument.getElementById(\"text-was-typed\").innerHTML = this.value.slice(0,i);\n\t\t\t\tdocument.getElementById(\"text-wrong\").innerHTML = currentText.slice(i,this.value.length)\n\t\t\t\tdocument.getElementById(\"text-to-type\").innerHTML = currentText.slice(this.value.length)\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tpreviousLength = this.value.length;\n}", "function keyboard_event(type) {\n\t\t\tconsole.log(type);\n\n\t\t\t$.ajax({\n\t\t\t\ttype: 'POST',\n\t\t\t\turl: \"/button\",\n\t\t\t\tdata: {\n\t\t\t\t \"type\": \"text\",\n\t\t\t\t\t\t\"type\": type\n\t\t\t\t\t},\n\t\t\t\tsuccess: function(result) { }\n\t\t\t});\n\t\t}", "function updateName() { changeTextField(name, nameLabel, isValidName()) }", "handleTextFieldInteraction() {\n if (this.adapter_.getNativeInput().disabled) {\n return;\n }\n this.receivedUserInput_ = true;\n }", "handleTextFieldInteraction() {\n if (this.adapter_.getNativeInput().disabled) {\n return;\n }\n this.receivedUserInput_ = true;\n }", "handleTextFieldInteraction() {\n if (this.adapter_.getNativeInput().disabled) {\n return;\n }\n this.receivedUserInput_ = true;\n }", "function nameKey(event)\n{\n if (timer)\n clearTimeout(timer);\n timer = setTimeout(update, 500);\n}", "function componingMsgListener() {\n var target = $('#main-search-bar-input');\n target.keyup(sendKeyupPressed);\n}" ]
[ "0.6371094", "0.6303216", "0.6293244", "0.6291071", "0.61866933", "0.60885304", "0.6064244", "0.6064244", "0.6064244", "0.6064244", "0.6064244", "0.59940857", "0.5934922", "0.59086096", "0.58761764", "0.5856744", "0.58140546", "0.5798186", "0.57946247", "0.5767547", "0.57604843", "0.5756698", "0.5748268", "0.5737636", "0.57271045", "0.57100356", "0.5698353", "0.56963456", "0.5661222", "0.56552607", "0.56534404", "0.5640283", "0.56396836", "0.56277806", "0.559808", "0.55955565", "0.55913895", "0.5584877", "0.55814606", "0.55753756", "0.5572474", "0.55688", "0.5566259", "0.5566215", "0.55653834", "0.55653733", "0.55503446", "0.5541225", "0.5532788", "0.5530314", "0.5528258", "0.55252004", "0.55054057", "0.5505127", "0.5502885", "0.54998326", "0.5498287", "0.5493433", "0.5483674", "0.54828435", "0.54804647", "0.5477886", "0.5476257", "0.547569", "0.5467438", "0.54658055", "0.5461534", "0.5450426", "0.5441472", "0.5438565", "0.54357", "0.5433448", "0.5428001", "0.5420141", "0.54166406", "0.54070693", "0.540633", "0.5406035", "0.54051924", "0.5404475", "0.5397467", "0.5392373", "0.5392106", "0.53920287", "0.53875774", "0.53827643", "0.5377046", "0.53766453", "0.53761125", "0.5374655", "0.53710675", "0.536472", "0.5363527", "0.5359246", "0.5358838", "0.53587234", "0.5355091", "0.5355091", "0.5355091", "0.53517747", "0.53439933" ]
0.0
-1
looks great! PROBLEM 2
function multiply(c, d) { // console.log('The product of ' + c + ' and ' + d + ' is ' + (c * d)); return c * d; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "private internal function m248() {}", "protected internal function m252() {}", "private public function m246() {}", "transient protected internal function m189() {}", "transient private protected internal function m182() {}", "static private internal function m121() {}", "transient final protected internal function m174() {}", "function StupidBug() {}", "static private protected internal function m118() {}", "transient private internal function m185() {}", "static final private internal function m106() {}", "transient final private protected internal function m167() {}", "static transient final private internal function m43() {}", "static private protected public internal function m117() {}", "transient final private internal function m170() {}", "static transient private protected internal function m55() {}", "static protected internal function m125() {}", "transient private protected public internal function m181() {}", "static transient final protected internal function m47() {}", "static final private protected internal function m103() {}", "_firstRendered() { }", "static transient private protected public internal function m54() {}", "static transient private internal function m58() {}", "transient private public function m183() {}", "static transient final private protected internal function m40() {}", "function sprinkles() {\n\n\t}", "static private public function m119() {}", "transient final private protected public internal function m166() {}", "function strSc(p){stcSc(p,0);stcIt(p.sc[0],0);stcIt(p.sc[1],0);p._sc.style.overflow=\"visible\";p._sc.style.width=\"\";p._sc.style.height=\"\";return 1;}", "function comportement (){\n\t }", "static final private protected public internal function m102() {}", "function princeCharming() { /* ... */ }", "static transient final protected public internal function m46() {}", "function Ze(){if(ea)t.innerHTML=ha;else if(ia)t.innerHTML=ia;$e();eb&&hb.call(window,eb);nb();eb=-1;bb=[];cb={};ac=j;Zb=0;$b=[];w.Cc();Bb=0;Cb=[];document.documentElement.className=\"js no-treesaver\";document.documentElement.style.display=\"block\"}", "function forFixingBug(idx) {\n\treturn idx*10 + 6;\n}", "function mostraNotas(){}", "function wa(){}", "function Ha(){}", "static transient private public function m56() {}", "__previnit(){}", "function itWorked() {\n\tgetDogrImg(words);\n}", "function Scdr() {\r\n}", "function Paper_format_other(){\n\n}", "overTime(){\n\t\t//\n\t}", "function TMP() {\n return;\n }", "transient final private public function m168() {}", "static transient final private protected public internal function m39() {}", "static transient final protected function m44() {}", "function k(){setTimeout(function(){// IE7 needs this so dimensions are calculated correctly\n!la.start&&p()&&// !currentView.start makes sure this never happens more than once\ns()},0)}", "static transient final private protected public function m38() {}", "function exceptions() {\n tricks[62][0] = \"fakie ollie one-foot\";\n tricks[82][0] = \"halfcab\";\n tricks[83][0] = \"fakie bigspin\";\n tricks[85][0] = \"halfcab flip\";\n tricks[86][0] = \"halfcab heelflip\";\n tricks[87][0] = \"halfcab double flip\";\n tricks[88][0] = \"halfcab double heelflip\";\n tricks[92][0] = \"FS halfcab\";\n tricks[95][0] = \"FS halfcab flip\";\n tricks[96][0] = \"FS halfcab heelflip\";\n tricks[97][0] = \"FS halfcab double flip\";\n tricks[98][0] = \"FS halfcab double heelflip\";\n tricks[183][0] = \"nollie\";\n tricks[184][0] = \"nollie one-foot\";\n}", "function mistake1() {\n\ttoss(\"data\");\n}", "fixupFrame() {\n // stub, used by Chaos Dragon\n }", "function t() {\n //$content.css('paddingTop', $pageMaskee.height());\n y.height(h.height()).width(h.width());\n }", "static transient final private public function m41() {}", "function Rep() {\r\n}", "preset () { return false }", "function gi(t,e){0}", "function MultiplicatorUnitFailure() {}", "function ea(){}", "function Hx(a){return a&&a.ic?a.Mb():a}", "static transient protected internal function m62() {}", "function iehack() {\r\n\trecalc();\r\n}", "function Yielder() {}", "function TMP(){return;}", "function TMP(){return;}", "function ______TEXT_QUERIES______() {}", "function Pe(e,t){0}", "function fm(){}", "function init() {\n //UH HUH, THIS MY SHIT!\n }", "function beetle_lvl2() {}", "function oi(){}", "function _0x407e48(_0x18187c, _0x27f1e8) {\n 0x0;\n }", "function _____SHARED_functions_____(){}", "draw () { //change name to generate?? also need to redo\n return null;\n }", "function wR(a,b){this.Fb=[];this.HF=a;this.YE=b||null;this.Pq=this.un=!1;this.ai=void 0;this.Gz=this.AK=this.ez=!1;this.uu=0;this.cb=null;this.az=0}", "function beetle_lvl4() {}", "function mistake8() {\n\ttoss();//not even a name\n}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}", "function i(e,t){0}" ]
[ "0.6651187", "0.6621415", "0.63667965", "0.6026865", "0.6017517", "0.58875245", "0.5820209", "0.57608175", "0.57564634", "0.5750279", "0.56594867", "0.5656668", "0.5492502", "0.54693794", "0.54257405", "0.53996444", "0.5360115", "0.5332175", "0.53163266", "0.5309554", "0.52908266", "0.525421", "0.5165957", "0.5145785", "0.5139634", "0.511721", "0.5113406", "0.50909704", "0.5083971", "0.50647557", "0.5043628", "0.5033158", "0.50026864", "0.49986207", "0.49863526", "0.4980218", "0.49665758", "0.4956706", "0.4924769", "0.49122605", "0.49061337", "0.49054667", "0.48968652", "0.4894519", "0.48862335", "0.486008", "0.485602", "0.48554555", "0.48451665", "0.48447618", "0.48417574", "0.48300803", "0.48243636", "0.48242083", "0.4815451", "0.48129874", "0.48102635", "0.4799825", "0.47925898", "0.47858167", "0.47812977", "0.47729692", "0.47624126", "0.47620755", "0.47548363", "0.47548363", "0.47522837", "0.47512847", "0.474833", "0.47475624", "0.47460133", "0.4745399", "0.4740712", "0.47275105", "0.47256193", "0.47219956", "0.47185776", "0.47161263", "0.471471", "0.471471", "0.471471", "0.471471", "0.471471", "0.471471", "0.471471", "0.471471", "0.471471", "0.471471", "0.471471", "0.471471", "0.471471", "0.471471", "0.471471", "0.471471", "0.471471", "0.471471", "0.471471", "0.471471", "0.471471", "0.471471", "0.471471" ]
0.0
-1
get user by id
getUser(){ Axios.get('/users/'+this.state.userId) .then(res => { this.setState({user: res.data}); this.getProfilePicture() }) .catch(error => { // console.log(error) }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getUser(id) {\n // return the one user with that id\n const user = users.find(user => user.id === id);\n return user;\n}", "function getUserById(id) {\n return getUserByProperty('id', id);\n}", "function getUserFromId(id) {\n let users = getUsers();\n if(users === null) return null;\n return users.find(u => u.user_id === id);\n}", "function getUserById(id){\n return $http.get(url.user + id).then( handleSuccess, handleError);\n }", "function findUserById(id) {\n return fetch(`${self.url}/${id}`).then(response => response.json())\n }", "async get(id) {\n try {\n let user;\n\n if (mongoose.Types.ObjectId.isValid(id)) {\n user = await this.findById(id).exec();\n }\n if (user) {\n return user;\n }\n\n throw new APIError({\n message: \"User does not exist\",\n status: httpStatus.NOT_FOUND,\n });\n } catch (error) {\n throw error;\n }\n }", "getById(id) {\r\n return new User(this, id);\r\n }", "async findById(id) {\n const query = this.getUserQueryBuilder();\n return this.findUser(query.where(this.config.identifierKey, id));\n }", "static async getById(id) {\n return await user_model.findById(id)\n }", "async GetById(id) {\n try {\n let user = await User.GetById(id);\n if (!user) {\n let response = constants.HTTP.ERROR.NOT_FOUND;\n return Promise.reject(response);\n }\n else {\n return user\n }\n } catch (err) {\n return Promise.reject(err);\n }\n }", "getUserById(id) {\n return this.http.get(\"http://localhost:8080/api/users/\" + id);\n }", "static async getUser(id) {\n const userRes = await db.query(\n ` SELECT username,\n first_name,\n last_name,\n email,\n photo_url\n FROM users\n WHERE id = $1`,\n [id]\n );\n\n const user = userRes.rows[0];\n\n if (!user) {\n throw new ExpressError(`There exists no user with id '${id}'`, 404);\n }\n\n return user;\n }", "function getUser(id) {\n\t\tvar query = User.findOne({'_id': id});\n\t\treturn query;\n\t}", "getUserById(id){\n return this.auth.get(`/user/${id}`,{}).then(({data})=> data);\n }", "function getUserById(id) {\n return Users.findById(id);\n}", "static getById(userId) {\n const query = 'SELECT * FROM Members WHERE id = $1 LIMIT 1';\n return db.one(query, [userId]).then(data => {\n return new User(data);\n }).catch(err => {\n console.error(err);\n console.error(`Couldn\\'t get user ${userId}.`);\n return null;\n });\n }", "getUser(id){\n return this.users.filter((user)=> user.id === id)[0]; /* FINDING AND RETURNING THE USER WITH SAME ID AND RETURNING IT WHICH WILL BE AT INDEX 0 */\n }", "getUser(_, { id }) {\n return db.user.findById(id);\n }", "getUserById(id) {\r\n return new SiteUser(this, `getUserById(${id})`);\r\n }", "function getUserByID(id) {\n return db('username_password')\n .where('id', id)\n .first();\n}", "function getUserById (id) {\n\n\tvar deferred = Q.defer();\n\n\tUser.findOne({_id: id}, {password:0})\n\t.then(user => {\n\t\tdeferred.resolve(user);\n\t})\n\t.catch(err => {\n\t\tdeferred.reject(err);\n\t});\n\n\treturn deferred.promise\n}", "function getUser(id){\n for (i in users){\n if (i.userId === id){\n return i\n }\n }\n return null\n}", "async getUserById(id){\n let users = await db.query('SELECT id, name, email FROM users WHERE id = ?', id);\n\n return users[0];\n }", "function getUserById(id) {\n // TODO: get user by id and set $scope.user to the user object. Angular will bind the object to the page \n }", "async getUser(_id) {\r\n if (!_id) throw \"You must provide an id to search for a user\";\r\n\r\n const userCollection = await usersList();\r\n const listOfUsers = await userCollection.find({ _id: _id }).limit(1).toArray();\r\n if (listOfUsers.length === 0) throw \"Could not find user with username \" + _id;\r\n\r\n return listOfUsers[0];\r\n\r\n\r\n }", "function getUser(id){\n return fetch(`http://localhost:3000/users/${id}`)\n .then(res => res.json())\n }", "getById(id) {\r\n return new SiteUser(this, `getById(${id})`);\r\n }", "function getUserById(id) {\r\n\tvar player = players.find(obj => obj.id == id);\r\n\tif (player) {\r\n\t\treturn player;\r\n\t}\r\n\tlog(2, 'No user could be found');\r\n\treturn undefined;\r\n}", "user(_, { id }) {\n return User.find(id);\n }", "async function getUserByUserId(id) {\n const [ results ] = await mysqlPool.query(\n 'SELECT * FROM users WHERE userId = ?',\n [ id ]\n );\n return results[0];\n }", "async get_user(user_id){\r\n\t\t\r\n\t\t//get user entry\r\n\t\tif(this.UsersInfo.has(user_id))\r\n\t\t\treturn this.UsersInfo.get(user_id)\r\n\t\telse \r\n\t\t\treturn this.load(user_id)\r\n\t}", "function getUser(id) {\n return $http.get('http://jsonplaceholder.typicode.com/users?id=' + id)\n .then(getUsersSuccess)\n .catch(getUsersError);\n }", "function getUser(id,res) {\n var user;\n if ( id && id !== '' && id !== undefined ) {\n userDbStub.forEach(function(element) {\n if(element.id === id ) {\n user = element;\n }\n }, this); \n \n if( !user && user === undefined) {\n if(res != null){\n res.status(404).send('user not found');\n }else{\n console.log('user not found');\n } \n }\n \n } else {\n if(res != null){\n res.status(401).send('id isn\\'t defined'); \n }else{\n console.log('id isn\\'t defined');\n } \n } \n return user;\n}", "function getUserById(req, res, next) {\n const sql = sqlString.format('SELECT * FROM users WHERE id = ?', [\n req.params.id\n ])\n db.execute(sql, (err, rows) => {\n if (err) return next(err)\n if (rows.length === 0) return next({ message: 'User not find' })\n res.send(rows[0])\n })\n}", "getUserById(db, userId) {\n return db('users').select('*').where('id', userId).first();\n }", "function getUserById(id) {\n var deferred = queue.defer();\n var findDeferred = queue.defer();\n User.findOne({\n _id: mongoose.Types.ObjectId(id)\n }, findDeferred.makeNodeResolver());\n findDeferred.promise.then(resolveOnlyWhenFound(deferred));\n return deferred.promise;\n }", "function getUserById(req, res) {\n var userId = req.params['userId'];\n\n userModel\n .findUserById(userId)\n .then(function (user) {\n res.json(user);\n });\n }", "function getById(_id) {\n var deferred = Q.defer();\n \n \n db.users.findById(_id, function (err, user) {\n if (err) deferred.reject(err);\n \n if (user) {\n // return user (without hashed password)\n deferred.resolve(_.omit(user, 'hash'));\n } else {\n // user not found\n deferred.resolve();\n }\n });\n\n return deferred.promise;\n}", "async getUserData(id) {\n return User.findByPk(id);\n }", "user({ id }) {\n return User.findById(id);\n }", "async getUserById(userId) {\n return db.oneOrNone('select * from users where user_id = $1', userId)\n }", "function getCurrentUser(id){\n return users.find(user => user.id === id);\n}", "async getOneUserId(req, res) {\n try {\n user.findOne({\n where: {\n id: req.params.id\n }\n })\n .then(result => {\n res.json({\n status: 'success',\n data: result\n })\n })\n } catch (e) {\n return res.status(401).json({\n status: \"Error!\",\n message: \"failed get one User by id\"\n })\n }\n\n }", "function find (id) {\n var user = database[\"User\"+id];\n if ((null === user) || (undefined === user)) {\n throw new Error('user not found');\n }\n return user;\n}", "getUser(id) {\n return this.users.filter(user => user.id === id)[0]; //VOY A TENER EL PRIMER ELEMENTO DE LA LISTA ES DECIR SOLO UN USUARIO / AL COLOCARLE QUIERO EL PRIMER ELEMENTO SOLO ME DARA EL OBJETO YA NO COMO LISTA DE OBJETO SINO SOLO EL OBJETO\n }", "function getUser(id: string): ?User {\n return usersById.get(id);\n}", "async getSingle(id = 1) {\n const response = await fetch(`${baseUrl}/users/${id}`);\n const data = await response.json();\n return data;\n }", "static getUserById(_id){\n return axios.get(`${baseUrl}${uniqUser}?_id=${_id}`)\n .then(function(res){\n return res\n }).catch((err) =>{\n throw(err)\n })\n }", "function findById(id) {\n\treturn db('users')\n\t\t.where({ id })\n\t\t.first();\n}", "static getUser(id) {\n const users = [\n {\n _id: 1,\n name: 'Michel Weststrate',\n twitterHandle: 'mweststrate',\n },\n {\n _id: 2,\n name: 'Jeff Hansen',\n twitterHandle: 'jeffijoe',\n },\n ]\n return Promise.resolve(users.find((x) => x._id === id))\n }", "function findUserById(id) {\n const user = _.find(Models.users, {id: id});\n\n // return 404 error if user not found\n if (! user) {\n return Promise.reject(new Errors.UserNotFound());\n }\n\n return Promise.resolve(user);\n}", "function findUserByMongoID (id) {\n return db.UserModel.findById(id)\n}", "getUserById(id, callback) {\n\t\tvar connection = this._connection;\n\n\t\t// Escape value\n\t\tvar _id = id; // Safe for later use\n\t\tid = connection.escape(id);\n\n\t\t// Run SQL statement\n\t\tvar _sql = sql.users.byId(id);\n\t\tconnection.query(_sql, function(err, result) {\n\t\t\tif(err) throw err;\n\n\t\t\tif(!result.length)\n\t\t\t\treturn callback(\"User not found\");\n\n\t\t\t// Transform and return user\n\t\t\tresult[0].ID = _id; // Hasn't been included in SQL result before\n\t\t\tvar user = sqlDataModel.user(result[0]);\n\t\t\tcallback(null, user);\n\t\t});\n\t}", "static async findById (id) {\n const criteria = {\n where: {\n id\n }\n }\n const entity = await User.findOne(criteria)\n if (!entity) {\n throw new errors.NotFoundError(`id: ${id} \"User\" doesn't exists.`)\n }\n return { id: entity.id, name: entity.name, profilePic: entity.profilePicture }\n }", "getDataFromID(id) {\n return this.users.find((user) => id === user.id);\n }", "function getByIdWithUser(id) {\n\t\treturn TokenFactory.query('SELECT * FROM `token` t JOIN `user` u ON t.`userid` = u.`id` WHERE t.`id` = ' + parseInt(id, 10) + ';');\n\t}", "function findUserById(req, res) {\n var userId = req.params['userId'];\n\n userModel\n .findUserById(userId)\n .then(function (user) {\n res.json(user);\n });\n\n }", "function getUserByIdQuery(_id) {\n return User.findById(_id);\n}", "async getUserbyId(id) {\n try {\n const sql = mysql.format(\"SELECT id, username, email, register_date FROM User WHERE id=?\", [id]);\n const res = await query(sql);\n return res;\n } catch (error) {\n return error;\n }\n }", "function getUser (req, res) {\n promiseResponse(userStore.findOne({ userId: req.params.id }), res);\n}", "function getUserById(userid) {\n}", "function getUser(id) {\n return \"Akhil\";\n}", "function findByIdAlt(id) {\n return db('users')\n .where({ id })\n .first();\n}", "getUserById(id, callback) {\r\n if (!id) {\r\n if (callback) {\r\n callback('No call ID passed', null);\r\n }\r\n return false;\r\n }\r\n var user = new User();\r\n user.load(id, function(error, user) {\r\n if (callback) {\r\n if (error) {\r\n callback(error, user);\r\n }\r\n callback(error, user);\r\n }\r\n });\r\n }", "getUser(id){\n //postDB(\"user/Get\", { \"use_id\" : id });\n return { \"name\" : \"steven\", \"img\" : '', \"share\" : false };\n }", "async function getById(req, res, next) {\n CRUD.read(User, req.params.id, res, next);\n}", "findById(id) {\n let sqlRequest = \"SELECT id, username, hashed_password FROM user WHERE id=$id\"\n let sqlParams = {$id: id}\n\n return this.common.findOne(sqlRequest, sqlParams).then(row => \n new User(row.id, row.username, row.hashed_password))\n }", "function getUser(id) {\n setTimeout(() => {\n console.log('Reading a user from database...');\n return { id: id, gitHubUsername: 'Nilank Nikhil' };\n }, 2000);\n return 1;\n}", "getUserById(req, res) {\n const id = req.params.id\n model.getUserById(id)\n .then((result) => {\n helper.response(res, result, 200, null)\n })\n .catch((err) => {\n helper.response(res, null, 400, err)\n })\n }", "function get_Current_User(id) {\r\n return c_users.find((p_user) => p_user.id === id);\r\n}", "async function GetUserByID(id) {\n let user = await UserModel.User.findOne({ user_id: id }).exec();\n return user;\n}", "function viewUser(id) {\r\n console.log('Inside user factory now');\r\n var deferred = $q.defer();\r\n\r\n $http.get(userUrl + '/user/' + id)\r\n .then (\r\n function(response) {\r\n deferred.resolve(response.data);\r\n },\r\n function(errResponse) {\r\n deferred.reject(errResponse);\r\n }\r\n );\r\n return deferred.promise;\r\n }", "function getUserById(id, callback) {\n User.findOne({'_id': id}, function(err, doc) {\n if (err) {\n callback(err);\n }\n else\n callback(null, doc);\n });\n}", "async getOne(req, res) {\n const { id } = req.params;\n\n try {\n const user = await UserModel.findById(id);\n res.send({ user });\n } catch (e) {\n res.status(400).send({ message: \"User not exists\" });\n }\n }", "async function getUserById(id) {\n try {\n const {\n rows: [user],\n } = await client.query(\n `\n SELECT *\n FROM users\n WHERE id=$1;\n `,\n [id]\n );\n\n //get orders for user\n const orders = await getAllOrdersByUserId({ id });\n if (orders.length != 0) {\n user.orders = orders;\n }\n\n\n\n //get reviews for user\n const reviews = await getAllReviewsByUserId({ id });\n if (reviews.length != 0) {\n user.reviews = reviews;\n }\n\n return user;\n } catch (error) {\n throw error;\n }\n}", "static async getUser(req, res) {\n const id = req.params.id;\n\n try {\n const user = await userModel.find(id);\n res.status(200).json(user);\n } catch (err) {\n res.status(404).json({ message: err.message });\n }\n }", "function getProfile(id) {\n\treturn users.findOne({ cookie_uuid: id });\n}", "function fetchUser(id){\n\t\"use strict\";\n\n\treturn new Promise((resolve,reject) => {\n\t\trequest.get(\"http://jsonplaceholder.typicode.com/users/\" + id, (err, response, body) => {\n\t\t\tif(err){return reject(err);}\n\n\t\t\tif(response.statusCode === 200){\n\t\t\t\tresolve(body);\n\t\t\t}else{\n\t\t\t\treject(new Error(\"statusCode is\" + response.statusCode));\n\t\t\t}\n\t\t})\n\t});\n}", "static get(id) {\n return this.map.get(\"username\" + id);\n }", "function findById(id) {\n return db(\"users\").where({ id }).first();\n}", "function findUserById(req, res){\n var userId = req.params.userId;\n userModel\n .findUserById(userId)\n .then(\n function(user) {\n if(user === null) {\n res.status(400).send(\"User \" + userId + \" not found\")\n } else {\n res.json(user);\n }\n },\n function(error) {\n res.status(400).send(\"User \" + userId + \" not found\")\n }\n );\n }", "function getUserById(req, res) {\r\n if (!req.params.userId) return res.status(400).json({success: false, message: 'User ID not provide'}); // Return Error\r\n User.findById(req.params.userId, (err, user) => {\r\n if (err) return res.status(500).json({ success: false, message: `Request failed: ${err}`}); // Return Coneccition Error\r\n if (!user) return res.status(404).json({ success: false, message: 'User not found'}) // Return as not found user\r\n return res.status(200).json({ success:true, user: user}); // Return user\r\n });\r\n}", "async function getById(req, res) {\n const user = await User.findById(req.params.id);\n if (!user) return res.status(404).send({ error: 'Usuario no encontrado' })\n return res.send(user);\n}", "getUserByID(userid, cb) {\n\t\tvar query = {\n\t\t\t_id: global.dbController.convertIdToObjectID(userid)\n\t\t}\n\t\tthis.getUserDetails(query, cb)\n\t}", "getUserById(userId) { //singleton!\n\t\treturn this._getSingleObject(\n\t\t\t(\n\t\t\t\t'SELECT * FROM USERS u ' + \n\t\t\t\t'WHERE u.user_id = :id'\n\t\t\t), \n\t\t\t{\n\t\t\t\tid: userId\n\t\t\t}\n\t\t);\n\t}", "findById(id) {\n const posicion = indexOfPorId(id);\n return posicion == -1 ? undefined : users[posicion];\n }", "getUser(id, callback) {\r\n\r\n this._connection.query('SELECT id, username FROM users WHERE id = ?', id, function (err, rows, fields) {\r\n if (err) {\r\n return callback(err);\r\n }\r\n\r\n callback(null, rows);\r\n }\r\n );\r\n\r\n this._connection.end();\r\n }", "async getById(userId) {\n try {\n const user = await this.model.find({\n userId: userId,\n statusFlag: true\n });\n return user;\n } catch (error) {\n throw new ApplicationError(error, 500, {});\n }\n }", "function getUserById(userId){\n return db.one(`\n SELECT * FROM users\n WHERE id = $1\n `, userId)\n .then(user => {\n return user;\n })\n .catch((e) => {\n console.log(e)\n })\n}", "function retrieveUserById(userId, callback) {\n var objUserId = undefined;\n try {\n objUserId = new ObjectId(userId);\n }\n catch (err) {\n objUserId = undefined;\n }\n retrieveUserByQuery({\"_id\": objUserId}, callback);\n}", "async queryStudent(ctx, id) {\n const userKey = User.makeKey([id]);\n const user = await ctx.studentList.getUser(userKey);\n if (!user) {\n throw new Error('Can not found User = ' + userKey);\n }\n\n return user;\n }", "function findById(id) {\n return db('users')\n .where({ id }).first();\n}", "function findUserById(userId) {\n var url = \"/api/user/\" + userId;\n return $http.get(url);\n }", "function findUserById(userId) {\n var url = \"/api/user/\" + userId;\n return $http.get(url);\n }", "async function findByUserId(id) {\n const user = await userDetailModel\n .findOne({user:id});\n console.log(user)\n if (!user) throw \"Details of user with\" + ` ${id} ` + \"not found\";\n return user;\n }", "function getUser(id){\n console.log(\"[inside getUser\", id);\n console.log(\"users array: \", users)\n return users.find((user) => user.id ===id);\n \n}", "function getUser(id) {\n return axios.get(api_host+\":\"+api_port+\"/api/user/\"+id)\n .then( res => {\n return res.data;\n })\n .catch( err => {\n console.log(err);\n });\n}", "function getUserById(user_id) {\n return User.findById(user_id);\n}", "async getUser (_id) {\n let user = await this.models.users.findOne({_id: _id, deletedAt: null}, {password: 0})\n .populate('tickets');\n if (!user) {\n throw new Error();\n }\n return user;\n }", "function getCurrentUser(id) {\n // SERVER_CALL Get information of user profile from server\n // For now return fake user we created\n user = patientList.filter(function(account) {\n return account.id == id;\n })[0];\n}", "async getUser(userId) {\n let userResult = await this.request(\"user/\" + userId);\n return userResult.user;\n }" ]
[ "0.8661759", "0.86072797", "0.8395371", "0.836435", "0.8360832", "0.82106304", "0.8157742", "0.81005263", "0.80803895", "0.8056137", "0.80060387", "0.79996574", "0.7998038", "0.7998009", "0.7985676", "0.7968348", "0.7964207", "0.7955948", "0.7938107", "0.79178125", "0.7895169", "0.7889011", "0.78637046", "0.78526694", "0.78003836", "0.7800272", "0.7775942", "0.77654445", "0.77642334", "0.7764067", "0.77360404", "0.7724048", "0.7705302", "0.76816165", "0.7677445", "0.7670786", "0.7645595", "0.76422286", "0.7632077", "0.7630998", "0.7623097", "0.75971663", "0.7546882", "0.7540076", "0.75303936", "0.7529645", "0.75248593", "0.7521776", "0.75163627", "0.7492546", "0.7479971", "0.74692756", "0.7458358", "0.7443729", "0.74382246", "0.74229217", "0.7411073", "0.740963", "0.73917663", "0.7356204", "0.7336217", "0.73300296", "0.7317931", "0.731107", "0.7309405", "0.7300409", "0.7298738", "0.72874814", "0.72863203", "0.7282454", "0.72782075", "0.7268723", "0.72681236", "0.7265639", "0.7254871", "0.72529453", "0.7241749", "0.7241036", "0.7235465", "0.72352076", "0.72331834", "0.7214197", "0.7212457", "0.7211653", "0.7211591", "0.7211219", "0.72109044", "0.7209652", "0.7204169", "0.72041154", "0.7193937", "0.7191287", "0.7181866", "0.7181866", "0.7181505", "0.71753085", "0.71728766", "0.7169988", "0.7164447", "0.71590996", "0.71543306" ]
0.0
-1
get users profile picture
getProfilePicture(){ Axios.get('/users/' + this.state.userId + '/picture', { method: 'GET', responseType: 'blob' }).then(res => { const file = new Blob([res.data]); const fileURL = URL.createObjectURL(file); this.setState({profileImageUrl: fileURL}); }) .catch(error => { //console.log(error); //alert('Error occured please try again!'); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getProfileFacebookImage(){\n var obj =getFacebookUserLocal();\n return getFacebookImage(obj);\n \n }", "function getProfilePic(username){\n ClientAccountService.getProfilePic(username)\n .then(\n function(d) {\n vm.userProfilePic =d;\n vm.picPath1 = '/user'+d.picPath;\n },\n function(errResponse){\n console.error('Error while getting profilePic');\n }\n );\n }", "function getPic(type, userid, size) {\n // If userid is current user\n if (typeof _session.user != \"undefined\" && userid == _session.user.userid) {\n //age = _session.user.age;\n //gender = _session.user.gender;\n picextension = _session.user.picextension;\n }else if (typeof _session.users.user[userid] != \"undefined\") {\n // If Object is present in the current streamMember cache\n //age = _session.users.user[userid].age;\n //gender = _session.users.user[userid].gender;\n picextension = _session.users.user[userid].picextension;\n }else{\n // If Object is not present in the current streamMember cache\n //age = 0;\n //gender = \"\"\n //picextension = \"\"\n }\n \n // If no profile pic exists\n if(typeof picextension == \"undefined\" || picextension == null || picextension.length == 0){\n // Display age appropriate Silohoutte *TODO: Get Age from results\n if(userid < 50){\n gender = \"M\";\n } else {\n gender = \"F\";\n }\n \n imgSrc = 'img/profiles/no-picture-' + gender.toLowerCase() + '.png';\n }else{\n imgSrc = _application.url.fetch[type] + userid + size + picextension;\n }\n \n return imgSrc;\n}", "function getProfilePicUrl() {\n return getAuth().currentUser.photoURL || '/images/profile_placeholder.png';\n}", "function getProfilePicture(req, res) {\n gfs.files.findOne({\n filename: req.params.name\n }, (err, file) => {\n if (!file || file.length === 0) return res.status(404).json({\n err: 'No file exists'\n });\n if (file.contentType === 'image/jpeg' || file.contentType === 'image/png') {\n const readstream = gfs.createReadStream(file.filename);\n readstream.pipe(res);\n } else {\n res.status(404).json({\n err: 'Not an image'\n });\n }\n });\n}", "function getProfilePicUrl() {\r\n if(isUserSignedIn()){\r\n return auth.currentUser.photoURL || '/assets/images/becoder.png';\r\n }\r\n}", "function getProfilePicUrl() {\n return (\n firebase.auth().currentUser.photoURL ||\n \"../../resources/images/profile_placeholder.png\"\n );\n}", "function getProfilePicUrl() {\n return firebase.auth().currentUser.photoURL || '/images/profile_placeholder.png';\n}", "function getProfilePicUrl() {\n return firebase.auth().currentUser.photoURL || '/images/profile_placeholder.png';\n}", "function getProfilePicUrl() {\n return firebase.auth().currentUser.photoURL || '/images/profile_placeholder.png';\n}", "function getProfilePicUrl() {\n return firebase.auth().currentUser.photoURL || '/images/profile_placeholder.png';\n}", "function getProfilePicUrl() {\n return firebase.auth().currentUser.photoURL || '/images/profile_placeholder.png';\n}", "function getProfilePicUrl() {\n return firebase.auth().currentUser.photoURL || '/images/profile_placeholder.png';\n}", "function getProfilePicUrl() {\n return firebase.auth().currentUser.photoURL || '/images/profile_placeholder.png';\n}", "function getProfilePicUrl() {\n return firebase.auth().currentUser.photoURL || '/images/profile_placeholder.png';\n}", "function getProfilePicUrl() {\n return firebase.auth().currentUser.photoURL || '/images/profile_placeholder.png';\n}", "function getProfilePicUrl() {\r\n return firebase.auth().currentUser.photoURL || '/images/profile_placeholder.png';\r\n}", "function getProfilePicture(userID) {\n try {\n\n var fileNames = fs.readdirSync(`${__dirname}/../ProfilePictures/`)\n var available;\n fileNames.forEach(file => {\n if (file == `${userID}.png`) { available = true }\n })\n\n if (available) {\n var img = fs.readFileSync(`${__dirname}/../ProfilePictures/${userID}.png`)\n var base64 = Buffer.from(img).toString('base64');\n base64 = 'data:image/png;base64,' + base64;\n return base64;\n }\n } catch (error) {\n console.error(error.stack);\n }\n}", "function getProfilePicUrl() {\n return firebase.auth().currentUser.photoURL || '/images/profile_placeholder.png';\n}", "function getProfilePicURL(){\n\treturn student.path;\n}", "function getProfilePic (req, res) {\n let pathToFile = path.join(__dirname, '/../../pictures/profile/profile-pic.txt')\n fs.readFile(pathToFile, (err, buff) => {\n if (err) {\n throw err\n }\n res.send(buff.toString())\n })\n}", "function getAvatar() {\n api.getAvatar().$promise.then(function (result) {\n UserService.avatar = result.pictures[0].picture;\n $location.path('/main');\n }, function () {\n window.alert('Not Logged In');\n $location.path('/');\n });\n }", "function getUserImage(username) {\n for (var i = 0, length = users.length; i < length; i++) {\n if (users[i].username == username) {\n if (!Methods.isNullOrEmpty(users[i].picture) && !Methods.isNullOrEmpty(users[i].picture.url)) {\n return users[i].picture.url;\n }\n else {\n return 'images/groups/' + username.slice(0, 1).toUpperCase() + '.png';\n }\n }\n }\n return 'images/other/Cat.png';\n }", "function getUserInfo(access_token) {\n\t FB.api('/me', function(response) {\n\t\t $(\"#reg_screenname\").val(response.name); \n\t\t $(\"#reg_email\").val(response.email); \t\n\t\t $(\"#facebook_id\").val(response.id);\n\t\t $(\"#access_token\").val(access_token);\n });\n\t\t\n\t\tFB.api('/me/picture?type=normal', function(response) {\n\n\t\t var str=response.data.url;\n\t \t document.getElementById(\"faceavatar\").src=str;\n\t \t \t \n });\n\t\t\n }//end of get user info", "function assignImage(user){\n if(!user) return \"\";\n if(user.image) return user.image;\n if(user.twitchData && user.twitchData.profile_image_url) return user.twitchData.profile_image_url;\n if(user.facebookData && user.facebookData.photos) return user.facebookData.photos[0].value;\n if(user.googleData && user.googleData.photos) return user.googleData.photos[0].value;\n return \"\";\n}", "async function showProfilePic() {\n const imageObj = await util.getProfilePicById(util.currentProfile);\n\n let profilePicSrc;\n !imageObj\n ? (profilePicSrc = './images/user.png')\n : (profilePicSrc = `./uploadedImages/${imageObj.img_id}.${imageObj.img_ext}`);\n\n document.querySelector('#profilePicElement').src = profilePicSrc;\n}", "_FB_getUserImage() {\n const _this = this;\n\n _this._FB_API('/me/picture', function(response) {\n _this.setState({\n FB_user_picture: response.data.url\n });\n })\n }", "function getInfo() {\n FB.api('/me', 'GET', {fields: 'email,first_name,last_name,name,id,picture.width(300).height(300)'},\n function(response) {\n document.getElementById('fbuserpicture').innerHTML = \"<img src='\" + response.picture.data.url + \"'>\";\n document.getElementById('fbemail').innerHTML = response.email;\n document.getElementById('fbusername').innerHTML = response.first_name + \" \" + response.last_name ;\n document.getElementById('fbuserid').innerHTML = response.id;\n });\n}", "getProfilePic() {\n return 'images/' + this.species.toLowerCase() + \".png\";\n }", "function loadImage(fileName){\n\talert(\"This is the page to load a saved Project but I only save an image to the users progfile right now. :(\");\n\tvar user = firebase.auth().currentUser;\nvar name, email, photoUrl, uid, emailVerified;\n name = user.displayName;\n email = user.email;\n photoUrl = user.photoURL;\n alert(email+\" \"+name+\" \"+photoUrl);\n user.updateProfile({\n photoURL: \"'../images/test.GIF'\"\n})\n photoUrl = user.photoURL;\n alert(photoUrl);\n}", "getProfile(uid) {\n this.props.firebase.pictures(`${uid}.png`).getDownloadURL().then((url) => {\n this.setState({ url })\n }).catch((error) => {\n // Handle any errors\n this.setState({ url: \"\"})\n })\n }", "function obtenerFotoPerfil(){\n FB.api('/me/picture?width=325&height=325', function(responseI) {\n var profileImage = responseI.data.url;\n var fbid=jQuery(\"#pictureP\").val(profileImage);\n\n\n //console.log(profileImage);\n });\n}", "function profilePicPathAttachment(obj) {\n return \"data/users/\" + obj.picture;\n }", "function getProfileData() {\n // obtener los datos del usuario al iniciar sesión\n IN.API.Raw(\"people/~:(first-name,last-name,id,num-connections,picture-url,location,positions,summary,public-profile-url)\").result(onSuccess).error(onError); \n }", "retrieveProfilePicture (id) {\n // getUserProfilePic(id)\n // .catch(e => console.log('PIC ERROR', e))\n // .then(r => {\n // this.state.img = r.data.url || 'default image'\n // this.setState(this.state)\n // })\n }", "function getUserPicture(id) {\n return $q(function(resolve, reject) {\n FacebookResource.apiCall(id+Constants.FACEBOOK_FRIEND_FIELDS).then(function (response) {\n var url = \"\";\n if(response.picture && response.picture.data)\n {\n url = response.picture.data.url;\n }\n \n return resolve(url);\n \n }, function (error) {\n return reject(error);\n });\n })\n }", "getAvatarUrl() {\n const { user } = this.state;\n return endpoint + '/core/avatar/' + user.id + '/' + user.avatar;\n }", "function profilepic(){\n\t\tvar ruta = \"/image/create\";\n\t\t$.ajax({\n\t\t\t\turl: ruta,\n\t\t\t\ttype: 'GET',\n\t\t\t\tdataType: 'json',\n\t\t\t\tdata: \"requested data\",\n\t\t\t\tsuccess: function(data){\n\t\t\t\t\t$(\"#profilepic\").attr('src', '/storage/' + data[1][0].picture);\n\t\t\t\t\t$(\"#profileaddress\").attr('href', '/profile/userprofile/' + data[1][0].profile_address);\n\t\t\t\t\tvar usertype = data[1][0].usertype;\n\t\t\t\t\tif (usertype == '1') {\n\t\t\t\t\t\t$(\"#profilevideos\").html(\" \");\n\t\t\t\t\t\t$(\"#dayoffsection\").html(\" \");\n\t\t\t\t\t\t$(\"#profilevideos\").hide();\n\t\t\t\t\t\t$(\"#dayoffsection\").hide();\n\t\t\t\t\t}else{\n\t\t\t\t\t\t$(\"#profilevideos\").attr('src', 'storage/' + data[0][0].video);\n\t\t\t\t\t\t$(\"#currentvid\").attr('value', data[0][0].video);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\terror: function(xhr){\n\t\t\t\t\tconsole.log(xhr.responseText);\n\t\t\t\t}\n\t\t\t});\n\t}", "getImageData (user) {\n // default crop\n if (!user.crop) {\n user.crop = {\n x: 0.5,\n y: 0.5,\n scale: 1\n }\n }\n let formData = new FormData()\n formData.append('file', user.img)\n let to_return = {\n formData: formData,\n type: 'profile_pic',\n x: user.crop.x,\n y: user.crop.y,\n scale: user.crop.scale,\n user_id: getCurrentUserId()\n }\n return to_return\n }", "function getCurrentProfilPicture() {\n $.ajax({\n url: ajaxurl,\n type: \"POST\",\n global: false,\n data: {\n 'action': 'load_user_picture',\n }\n }).done(function(response) {\n url = 'url(' + response + \")\";\n $('.icon-picture').css('background', url);\n $('.icon-picture').css('background-size', 'cover');\n $('.icon-picture').css('background-position', 'center');\n });\n }", "function view_user_profile_image(id) {\n $.ajax({\n url: 'users/' + id,\n type: 'get',\n success: function (data) {\n if (data) {\n hold_modal('viewUserImageModal', 'show')\n $('#user_profile_name').html(data.name)\n $('#v_load_view_user_profile').html(`<img src=\"/all/app-assets/images/profile/user-uploads/${data.profile}\"\n style=\"width: 370px; height: 370px; border-radius: 50px\" alt=\"Profile\">`)\n }\n },\n error: function () {\n alert('Failed!')\n }\n })\n}", "async function getProfilePic(player) {\n //takes in the player uid and uses that to get the profile pic from a URL\n await firebase\n .storage()\n .refFromURL(\"gs://brackot-app.appspot.com/\" + player + \"/profile\")\n .getDownloadURL()\n .then(function (url) {\n return String(url);\n })\n .catch((error) => {\n return \"../media/BrackotLogo2.jpg\";\n });\n}", "function getCustomerProfileAvatar(id) {\n return $http({\n method: 'GET',\n url: API_URL + CUSTOMER_PROFILE_AVATAR_URL + \"/\" + id\n }).then(function successCallback(response) {\n $log.log(\"successCallback getCustomerProfileAvatar result: \");\n $log.log(response);\n return response.data;\n }, function errorCallback(response) {\n $log.log(\"errorCallback getCustomerProfileAvatar result: \");\n $log.log(response);\n return response.data;\n });\n }", "function getUserAvatar() {\n\n var contract = {\n \"function\": \"sm_getAddressAvatar\",\n \"args\": JSON.stringify([gUserAddress])\n }\n\n return neb.api.call(getAddressForQueries(), gdAppContractAddress, gNasValue, gNonce, gGasPrice, gGasLimit, contract);\n\n}", "function getProPic(usr) {\n if (usr != null) {\n //prendo json dell'utente\n let jsonURL = \"https://www.instagram.com/\" + usr + \"/?__a=1\";\n let usrAcc = \"https://www.instagram.com/\" + usr;\n //request json\n request({\n url: jsonURL,\n json: true\n }, function (error, response, body) {\n\n if (!error && response.statusCode === 200) {\n //elemento json ritornato dalla richiesta\n //let a = body.user.profile_pic_url;\n //controllare errori es return 0 nelle funzioni sopra\n let finalURL = getCleanURLs(body.user.profile_pic_url);\n //console.log(finalURL);\n //image name per i senza immagine profilo\n if (finalURL.indexOf(\"11906329_960233084022564_1448528159\") !== -1) {\n bot.sendMessage(chat_id, \"<a href=\\\"\" + usrAcc + \"\\\">\" + usr + \"\\n\" + \"</a>\" + \"Non ha alcuna foto profilo\", parse_HTML);\n } else {\n bot.sendMessage(chat_id, \"<a href=\\\"\" + finalURL.toString() + \"\\\">Foto profilo </a>\" + \"di \" + \"<a href=\\\"\" + usrAcc + \"\\\">\" + usr + \"</a>\", parse_HTML);\n\n }\n\n }\n if (error || response.statusCode != 200) {\n bot.sendMessage(chat_id, \"Username inesistente\", reply);\n }\n })\n } else {\n bot.sendMessage(chat_id, \"Devi passarmi uno username\", reply);\n }\n }", "getUserImage(users) {\n return find(users, (user) => user.username === this.props.item.owner).image;\n }", "function userPicture(itemNo,idLoc) { \t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\tvar userPic = document.createElement(\"img\");\t\t\t\t\t\t\t\t\t\t\t// create element\n\t\tvar userID = gapi.hangout.data.getValue(\"listTxt\" + itemNo + \"listID\" + idLoc) || \"0\"; \t// Get Persons ID\n\t\tvar userObj = eval(gapi.hangout.getParticipantById(userID));\t\t\t\t\t\t\t// Get person object and JSON convert\n\t\tuserPic.src = userObj.person.image.url + \"sz=25\";\t\t\t\t\t\t\t\t\t\t// Use Avatar as image (+ resize to 50x50)\n\t\tuserPic.width = 25;\n\t\tuserPic.height = 25;\n\t\tuserPic.align = \"top\"; \n\t\treturn userPic;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// return button element\n\t}", "function getUserPictures() {\n let query = \"command=loadPictureList\";\n query += \"&username=\" + endabgabe2.globalUser;\n console.log(query);\n sendRequest(query, handlePictureListeResponse);\n }", "function getProfileData() {\n IN.API.Raw(\"/people/~\").result(onSuccess).error(onError);\n }", "function getProfileData() {\n IN.API.Raw(\"/people/~\").result(onSuccess).error(onError);\n }", "function getImageUrl(authData) {\n switch (authData.provider) {\n // case 'password':\n // return authData.password.email.replace(/@.*/, '');\n case 'twitter':\n /* jshint -W106 */\n return authData.twitter.cachedUserProfile.profile_image_url;\n // case 'facebook':\n // return authData.facebook.displayName;\n }\n }", "function getGoogleAvatar(index, googleId, callback) {\n gapi.client.load('plus','v1', function() {\n var request = gapi.client.plus.people.get({\n 'userId': googleId\n });\n request.execute(function(resp) {\n var img;\n if(resp.image) {\n if(!resp.image.isDefault) {\n img = resp.image.url.replace('?sz=50', '?sz=100');\n }\n }\n callback(index, img);\n });\n });\n}", "function getProfileData() {\n IN.API.Raw(\"/people/~\").result(onSuccess).error(onError);\n}", "function fetchAvatarUrl(userID) {\n return fetch(`https://catappapi.herokuapp.com/users/${userID}`)\n .then(response => response.json())\n .then(data => data.imageUrl)\n}", "function userpic_supplicant(user, src) {\n\tGM_xmlhttpRequest({ method: 'GET', url: src, \n\t\t\theaders: { 'User-Agent':'lj memento' },\n\t\t\tonerror: function(res) {\n\t\t\t\tGM_log('userpic error: ' + res) ;\n\t\t\t},\n\t\t\tonload: function(res) {\n\t\t\t\tvar parser ;\n\t\t\t\tvar dw = new XPCNativeWrapper(\n\t\t\t\t\t\twindow,\"DOMParser()\") ;\n\t\t\t\tparser = new dw.DOMParser() ;\n\n\t\t\t\tvar dom = parser.parseFromString(\n\t\t\t\t\t\tres.responseText,\n\t\t\t\t\t\t\"text/xml\") ;\n\t\t\t\tvar d_img = xpath('//image', dom) ;\n\t\t\t\tif(d_img.length == 0) {\n\t\t\t\t\tset_userpic_cached(user, NO_USERPIC) ;\n\t\t\t\t\tfill_userpic(user, NO_USERPIC) ;\n\t\t\t\t\treturn ;\n\t\t\t\t}\n\n\t\t\t\tvar nodes = xpath('//image/url/text()', dom) ;\n\t\t\t\tvar img_url = nodes[0].nodeValue ;\n//\t\t\t\timg_url.match(/userpic\\/(.*)$/) ;\n//\t\t\t\tvar userpic = RegExp.$1 ;\n\t\t\t\tset_userpic_cached(user, img_url) ;\n\n\t\t\t\tinstantiate_userpic(img_url, user) ;\n\t\t\t}\n\t\t}) ;\n\t}", "async function getProfie() {\n var tagline = await getTagline();\n var country = await getCountry();\n var profile = await getUrl();\n var featured = await getImages();\n res.render('pages/userProfile', {\n username: uname,\n icon: icon,\n tagline: tagline,\n country: country,\n link: profile,\n featured: featured,\n currentUser: currentUser\n });\n }", "function display_profile_image(image) {\n if (image) {\n return 'src = \"' + image + '\"';\n } else {\n return 'src = \"files\\\\profile\\\\img\\\\default.png\"';\n }\n}", "function getProfileData() {\n IN.API.Profile(\"me\").fields(\"id\", \"first_name\", \"last_name\", \"num-connections\", \"email-address\", \"industry\", \"location\", \"picture-url\", \"public-profile-url\").result(onSuccess).error(onError);\n}", "function userProfiles(){\n // Choose a random number for the image to use\n var imageNumber = randomIntegerInRange(1,AVAILABLE_IMAGES);\n // Create a string that points to the location of the image\n var imageSource = \"../images/profile\" + imageNumber + \".jpg\";\n // Build the image element\n var img = $('<img class=\"image\" src=\"' + imageSource + '\">');\n // Add the chosen image to corresponding div\n $('.random').append(img);\n }", "function displayProfilePicture(picture, imageID) {\n try {\n if(picture) {\n const path = '/userProfilePictures/' + picture;\n var img = document.getElementById(imageID);\n img.src = path;\n }\n } catch(err) {\n console.error(err);\n }\n}", "function showProfile(v){ \r\n //alert('showprofile: '+v);\r\n dispHeaderMode();\r\n document.getElementById('div_bar').style.display='block';\r\n var n = new Date().toLocaleTimeString('it-IT');\r\n var v_mphoto='main_gfx/avatar.png';\r\n \r\n if(DB_USER.length==0 || CURR_USER==null || CURR_USER==''){\r\n \r\n document.getElementById('bar_avatar').src=v_mphoto;\r\n document.getElementById('log_avatar').src=v_mphoto;\r\n document.getElementById('logger').innerHTML='';\r\n return;\r\n }\r\n\r\n //v_mphoto='upload/users/'+CURR_USER+'.jpg?'+n;\r\n v_mphoto=JBE_API+'upload/users/'+CURR_USER+'.jpg?'+n;\r\n if(!JBE_ONLINE){\r\n v_mphoto='data:image/png;base64,' + btoa(DB_USER[0]['photo']);\r\n }\r\n \r\n document.getElementById('bar_avatar').src=v_mphoto;\r\n document.getElementById('log_avatar').src=v_mphoto;\r\n document.getElementById('logger').innerHTML=CURR_NAME;\r\n \r\n}", "function getContactImg(uid,cb) {\n window.console.log('Uid to retrieve img for: ',uid);\n var img = contactList.querySelector('#c' + uid + ' img');\n\n // The contact was not previously loaded on the DOM\n if(img === null) {\n img = document.createElement('img');\n img.crossOrigin = \"Anonymous\";\n\n img.src = 'https://graph.facebook.com/' + uid + '/picture?type=square';\n // A timeout is setup just in case the photo is not loaded\n var timeoutId = window.setTimeout(function() {\n img.onload = null; cb(null); img.src = ''; },5000);\n\n img.onload = function() {\n window.clearTimeout(timeoutId);\n cb(img);\n }\n }\n else {\n cb(img);\n }\n }", "function getUserPhotoUrl(accountName, size) {\r\n var userPhotoBaseUrl = tryGetAlternativeUrl(USER_PHOTO_KEY) || DEFAULT_USER_PHOTO_BASE_URL;\r\n var sizeLetter;\r\n switch (size) {\r\n case 2 /* Medium */:\r\n sizeLetter = 'M';\r\n break;\r\n case 3 /* Large */:\r\n sizeLetter = 'L';\r\n break;\r\n default:\r\n // Default to small if size is not provided. Server will assume small either way, but having the\r\n // parameter explicitly will reduce variability in CDN, and will increase probability of the cache hit.\r\n sizeLetter = 'S';\r\n }\r\n var userPhotoUri = new Uri_1.default(userPhotoBaseUrl);\r\n userPhotoUri.setQueryParameter(USER_PHOTO_SIZE_PARAM, sizeLetter);\r\n // empty accountName will resolve to the default doughboy picture\r\n userPhotoUri.setQueryParameter(USER_PHOTO_ACCOUNT_NAME_PARAM, accountName || '');\r\n return userPhotoUri.toString();\r\n}", "function getUserPhotoUrl(accountName, size) {\r\n var userPhotoBaseUrl = tryGetAlternativeUrl(USER_PHOTO_KEY) || DEFAULT_USER_PHOTO_BASE_URL;\r\n var sizeLetter;\r\n switch (size) {\r\n case 2 /* Medium */:\r\n sizeLetter = 'M';\r\n break;\r\n case 3 /* Large */:\r\n sizeLetter = 'L';\r\n break;\r\n default:\r\n // Default to small if size is not provided. Server will assume small either way, but having the\r\n // parameter explicitly will reduce variability in CDN, and will increase probability of the cache hit.\r\n sizeLetter = 'S';\r\n }\r\n var userPhotoUri = new Uri_1.default(userPhotoBaseUrl);\r\n userPhotoUri.setQueryParameter(USER_PHOTO_SIZE_PARAM, sizeLetter);\r\n // empty accountName will resolve to the default doughboy picture\r\n userPhotoUri.setQueryParameter(USER_PHOTO_ACCOUNT_NAME_PARAM, accountName || '');\r\n return userPhotoUri.toString();\r\n}", "function getUserPhotoUrl(accountName, size) {\n var userPhotoBaseUrl = tryGetAlternativeUrl(USER_PHOTO_KEY) || DEFAULT_USER_PHOTO_BASE_URL;\n var sizeLetter;\n switch (size) {\n case 2 /* Medium */:\n sizeLetter = 'M';\n break;\n case 3 /* Large */:\n sizeLetter = 'L';\n break;\n default:\n // Default to small if size is not provided. Server will assume small either way, but having the\n // parameter explicitly will reduce variability in CDN, and will increase probability of the cache hit.\n sizeLetter = 'S';\n }\n var userPhotoUri = new Uri_1.default(userPhotoBaseUrl);\n userPhotoUri.setQueryParameter(USER_PHOTO_SIZE_PARAM, sizeLetter);\n // empty accountName will resolve to the default doughboy picture\n userPhotoUri.setQueryParameter(USER_PHOTO_ACCOUNT_NAME_PARAM, accountName || '');\n return userPhotoUri.toString();\n}", "function renderAvatar(user) {\n\tvar img = document.createElement('img')\n\timg.className = \"avatar\"\n\timg.src = user.avatarURL\n\timg.alt = \"\"\n\treturn img\n}", "getImg() {\n axios.get('/api/getPicture/' + this.state.profilePictureID.imgData)\n .then((res) => {\n this.setState({\n profilePicture: res.data.data\n });\n }, (error) => {\n console.error(\"Could not get uploaded profile image from database (API call error) \" + error);\n });\n }", "function getProfileData() {\n\tIN.API.Raw(\"/people/~:(email-address)\").result(onSuccess).error(onError);\n}", "SetProfilePicture(sex) {\r\n switch(sex.toUpperCase()) {\r\n case 'MALE':\r\n return 'http://res.cloudinary.com/onclicksell-com/image/upload/v1513504833/OnclickSell.com/Icons/Conceptional-Avatar-Male-Final-Design.png'\r\n case 'FEMALE':\r\n return 'http://res.cloudinary.com/onclicksell-com/image/upload/v1513504833/OnclickSell.com/Icons/Conceptional-Avatar-Female-Final-Design.png'\r\n }\r\n }", "function profilepicture(data) { \n\t\tvar number = (\"0000\" + data.mdl).slice(-4);\n\t\tif (data.mdl >= 41 && data.mdl <= 49) {\n\t\t var chicken = data.mdl - 40;\n\t\t var number = (\"0000\" + chicken).slice(-4);\n\t\t return \"http://mcshroom.com/pb2characters/pb2characters/chars_hero\" + number + \".jpg\";\n\t\t} else if (data.mdl === 61) {\n\t\t return \"http://mcshroom.com/pb2characters/pb2characters/chars_proxy.jpg\";\n\t\t} else {\n\t\t return \"http://mcshroom.com/pb2characters/pb2characters/chars\" + number + \".jpg\";\n\t\t}\n\t }", "function get_avatar(req, res) {\n\tvar image_file = req.params.image;\n\tvar path_file = './uploads/avatars/' + image_file;\n\n\tfs.exists(path_file, (exists) => {\n\t\tif (!exists) return res.status(404).send({ message: 'No existe la imagen' });\n\t\treturn res.status(200).sendFile(path.resolve(path_file));\n\t});\n}", "async loadProfilePic () {\n\n try {\n let responseData = await PortfolioApi.getPic('profilePic');\n this.setProfileImageState (responseData);\n } catch (err) {\n this.setState({error: \"error loading profile pic\", errorMessage: err})\n }\n }", "function getDataProfile() {\n loader(1);\n //alert(accessToken);\n\t\tvar term = null;\n\t\t$.ajax({\n\t\t\turl: 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' + accessToken,\n\t\t\ttype: 'GET',\n\t\t\tdata: term,\n\t\t\tdataType: 'json',\n\t\t\terror: function(jqXHR, text_status, strError) {\n //alert(JSON.stringify(jqXHR));\n //alert(JSON.stringify(text_status));\n //alert(JSON.stringify(strError));\n disconnectUser();\n\t\t\t},\n\t\t\tsuccess: function(data) {\n\t\t\t\tvar item;\n\t\t\t\tconsole.log(JSON.stringify(data));\n\t\t\t\t//alert(JSON.stringify(data));\n\t\t\t\t// Save the userprofile data in your localStorage.\n\t\t\t\t/* localStorage.gmailLogin = \"true\";\n\t\t\t\tlocalStorage.gmailID = data.id;\n\t\t\t\tlocalStorage.gmailEmail = data.email;\n\t\t\t\tlocalStorage.gmailFirstName = data.given_name;\n\t\t\t\tlocalStorage.gmailLastName = data.family_name;\n\t\t\t\tlocalStorage.gmailProfilePicture = data.picture;\n\t\t\t\tlocalStorage.gmailGender = data.gender; */\n\t\t\t\tdisconnectUser();\n\t\t\t\tGoogleName = data.given_name+' '+data.family_name;\n\t\t\t\tGoogleEmail = data.email;\n\t\t\t\tGoogleId = data.id;\n\t\t\t\tImgUser = data.picture;\n\t\t\t\tSignInDirect('google');\n\t\t\t}\n\t\t});\n\t}", "get sourceAvatar() {}", "function getProfilePicAndNameOfChat(chatsP, picDOMobject, user){\n\n db.collection(\"Vitaminders\").where(\"Gebruikersnaam\", \"==\", user).get().then(querySnapshot => {\n querySnapshot.forEach(doc => { \n\n const photo = doc.data().Profielfoto\n const userClean = doc.data().GebruikersnaamClean\n\n picDOMobject.src = photo\n chatsP.innerText = userClean\n });\n });\n}", "async function showAvatar() {\n\n // use await inside Promise (read data from right to left)\n let response = await fetch('/article/promise-chaining/user.json');\n let user = await response.json();\n\n return user;\n }", "grabAvatar(userId, avatarHash) {\n let Format = avatarHash.startsWith(\"a_\") ? \"gif\" : \"png\";\n return {\n \"hash\": avatarHash,\n \"format\": Format,\n \"url\": `https://cdn.discordapp.com/avatars/${userId}/${avatarHash}.${Format}?size=1024`\n };\n }", "function getFacebookImage(obj){\n try\n {\n \n \n if(obj.picture && obj.picture.data)\n {\n return obj.picture.data.url;\n }\n else\n return null;\n }\n catch(err)\n {\n return null;\n }\n }", "function getUserImg(type, userEmail) {\n if(type == \"SEARCH\") {\n for(var i = 0; i < searchList.length; i++) {\n var oneUser = searchList[i].local;\n if(oneUser.email == userEmail) {\n return oneUser.img;\n }\n }\n }\n else if(type == \"CONTACT\") {\n for(var i = 0; i < contactList.length; i++) {\n var oneUser = contactList[i];\n if(oneUser.email == userEmail) {\n return oneUser.img;\n }\n }\n }\n\n return \"\";\n}", "function userData() {\n let id = \"\"\n if (sessionStorage.getItem(\"loggedUserId\")) {\n id = JSON.parse(sessionStorage.getItem('loggedUserId'))\n }\n for (const user of users) {\n if (user._id == id) {\n document.querySelector('.avatar').src = user._avatar\n }\n }\n}", "function getContactPhoto(uid,cb) {\n var contactImg = getContactImg(uid,function(contactImg) {\n // Checking whether the image was actually loaded or not\n if(contactImg !== null) {\n canvas.width = contactImg.width;\n canvas.height = contactImg.height;\n\n canvas.getContext('2d').drawImage(contactImg,0,0);\n\n cb(canvas.toDataURL());\n }\n else {\n cb('');\n }\n });\n }", "getGalleryAvatarPict(uid) {\n let j = this.jQuery;\n let prefUrl = 'https://sonic-world.ru/files/public/avatars/av';\n if (uid == undefined) return false;\n j.ajax({\n url: prefUrl + uid +'.jpg',\n type:'HEAD',\n error:\n function(){\n j.ajax({\n url: prefUrl + uid +'.png',\n type:'HEAD',\n error:\n function(){\n j.ajax({\n url: prefUrl + uid +'.gif',\n type:'HEAD',\n error:\n function(){\n j('.sw_gallery_avatar_'+ uid)\n .css('background-color', '#E0E0E0');\n },\n success:\n function(){\n j('.sw_gallery_avatar_'+ uid)\n .css('background-image', 'url(../files/public/avatars/av'+ uid +'.gif)');\n }\n });\n },\n success:\n function(){\n j('.sw_gallery_avatar_'+ uid)\n .css('background-image', 'url(../files/public/avatars/av'+ uid +'.png)');\n }\n });\n },\n success:\n function(){\n j('.sw_gallery_avatar_'+ uid)\n .css('background-image', 'url(../files/public/avatars/av'+ uid +'.jpg)');\n }\n });\n }", "function AvatarURL( fn )\n{\n return 'https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/' + fn.substring( 0, 2 ) + '/' + fn + '.jpg';\n}", "function getUserProfile() {\n return $http.get('/api/user-profile').then(function (response) {\n return response.data;\n });\n }", "function getProfile(username) {\n return db.query(\n `SELECT first_name, last_name, age, email, bio, img_path FROM USERS WHERE username = \"${username}\";`\n );\n}", "function handleProfileImgLoad(event){\n updateElement('card-picture-img', {'className': 'card-picture-img card-show-profileImg'});\n displayProfileHome() // 파이어베이스에서 이미지가 완전히 로드된 후에 home 화면 보여주기\n // showAlert('succeed to fetch user information from server !', 500);\n \n // 초반에 'card-picture-img' DOM을 생성할때 src가 비어있어서 초기 렌더링시 error 이벤트가 발생하므로 \n // 이미지를 로드한 이후에 사진을 다시 숨겨버린다\n // 그러나 이미지 로드한 이후에는 더이상 사진을 숨길 필요가 없으므로 error 이벤트를 제거함\n // searchElement('card-picture-img').removeEventListener(\"error\", hideProfileImg);\n }", "function testAPI() {\n console.log('Welcome! Fetching your information.... ');\n FB.api('/me','GET',{fields:'first_name,last_name,name,id,picture.width(200).height(200)'}, function(response) {\n console.log('Successful login for: ' + response.name);\n document.getElementById('status').innerHTML =\n 'Thanks for logging in, ' + response.name + '!';\n console.log(\"last\",response)\n document.getElementById('img').innerHTML ='<img src=\"'+response.picture.data.url+'\"/>'\n\n });\n }", "async function getProfile() {\n const resp = await fetch(window.location.origin + '/profiles/me', {\n method: \"GET\",\n mode: \"cors\",\n cache: \"no-cache\",\n credentials: \"same-origin\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n redirect: \"follow\",\n });\n return resp.json();\n}", "function loadProfile(){\n var request = gapi.client.plus.people.get( {'userId' : 'me'} );\n request.execute(loadProfileCallback);\n }", "async function getProfileData(auth) {\n const service = google.people({version: 'v1', auth});\n const options = {\n resourceName: 'people/me',\n personFields: 'names,emailAddresses,photos'\n }\n return service.people.get(options);\n}", "getUser(){\n Axios.get('/users/'+this.state.userId)\n .then(res => {\n this.setState({user: res.data});\n this.getProfilePicture()\n })\n .catch(error => {\n // console.log(error)\n })\n }", "function getUser(i) {\n return new Just({\n getAvatar: function() {\n if(i <= 2) return Nothing\n else return new Just({url: 'http://aws.me/av.jpg'})\n }\n })\n }", "fetchUser() {\n return new Promise((resolve) => {\n window.FB.api('/me', { fields: 'first_name,last_name,picture.type(large),email' }, (response) => {\n resolve(response);\n });\n });\n }", "function loadProfile() {\n if(!supportsHTML5Storage()) { return false; }\n // we have to provide to the callback the basic\n // information to set the profile\n getLocalProfile(function(profileImgSrc, profileName, profileReAuthEmail) {\n //changes in the UI\n $(\"#profile-img\").attr(\"src\",profileImgSrc);\n $(\"#profile-name\").html(profileName);\n $(\"#reauth-email\").html(profileReAuthEmail);\n $(\"#inputEmail\").hide();\n $(\"#remember\").hide();\n });\n }", "function getGitHubProfile() {\n return getGitHubResource('user');\n}", "function loadProfile() {\n if (!supportsHTML5Storage()) { return false; }\n // we have to provide to the callback the basic\n // information to set the profile\n getLocalProfile(function(profileImgSrc, profileName, profileReAuthEmail) {\n //changes in the UI\n $(\"#profile-img\").attr(\"src\", profileImgSrc);\n $(\"#profile-name\").html(profileName);\n $(\"#reauth-email\").html(profileReAuthEmail);\n $(\"#inputEmail\").hide();\n $(\"#remember\").hide();\n });\n}", "function getFeed() {\n // load user's name and image and posts\n $.ajax({\n type: 'POST',\n url:'fetchUserProfile',\n success: function(response) {\n console.log(response);\n // set up user's profile pic\n document.getElementById(\"bigProfilePic\").src = response.profilePic;\n // set up user's username\n document.getElementById(\"userBtn\").innerHTML = response.username;\n }\n });\n}", "function getLocalProfile(callback) {\n var profileImgSrc = localStorage.getItem(\"PROFILE_IMG_SRC\");\n var profileName = localStorage.getItem(\"PROFILE_NAME\");\n var profileReAuthEmail = localStorage.getItem(\"PROFILE_REAUTH_EMAIL\");\n\n if (profileName !== null &&\n profileReAuthEmail !== null &&\n profileImgSrc !== null) {\n callback(profileImgSrc, profileName, profileReAuthEmail);\n }\n}", "function getProfileData() {\n IN.API.Profile(\"me\").fields(\"firstName\", \"lastName\", \"id\").result(onSuccess).error(onError);\n}", "function showMyProfile(response){\n\n\n var userId = response.id; //saving userid for accessing their profile picture\n pictureUrl = \"https://graph.facebook.com/\"+ userId + \"/picture?type=large\"; //saving url of profile picture of user\n\n $(\"img#profile\").attr(\"src\",pictureUrl); //displaying profile picture\n setField( $(\"h2#full-name\"), response.first_name); //displaying first name of user\n setField( $(\"h2#full-name\"), response.last_name); //displaying last name of user\n setField( $(\"p#info\"), response.birthday, \"Birthday: \"); //displaying birthday of user\n $(\"p#info\").append(\"<br />\"); //adding a line break to append new information from next line\n setField( $(\"p#info\"), response.email, \"Email: \"); //displaying email of user\n $(\"p#info\").append(\"<br />\");\n setField( $(\"p#info\"), response.gender, \"Gender: \"); //displaying gender of user\n $(\"p#info\").append(\"<br />\");\n setField( $(\"p#info\"), response.location.name, \"Current place: \"); //displaying current city of user\n $(\"a#visit-profile\").attr(\"href\",response.link);\n\n setField( $(\"div#right-side h2#work\"),response.work,\"WORK\");\n if($(\"div#right-side h2#work\").text() == \"WORK\"){ //to only access details of work object if it is present\n setWork( $(\"div#fb-work\"),response.work);\n }\n\n\n setField( $(\"div#right-side h2#edu\"),response.work,\"EDUCATION\");\n if($(\"div#right-side h2#edu\").text() == \"EDUCATION\"){\n setEdu( $(\"div#fb-edu\"),response.education);\n }\n\n }" ]
[ "0.81914055", "0.8116384", "0.7892072", "0.78855824", "0.7751536", "0.77508944", "0.7722199", "0.7655805", "0.7655805", "0.7655805", "0.7655805", "0.7655805", "0.7655805", "0.7655805", "0.7655805", "0.7655805", "0.7647456", "0.762509", "0.7617208", "0.7606125", "0.7603479", "0.73929536", "0.7349929", "0.7293644", "0.72261786", "0.7204173", "0.72026706", "0.71983016", "0.71631104", "0.7135511", "0.71273696", "0.7106832", "0.7099631", "0.7099264", "0.7075848", "0.7031061", "0.7014465", "0.7001827", "0.6948515", "0.69407076", "0.6904604", "0.6868023", "0.6851029", "0.6847831", "0.6835478", "0.68149585", "0.6806226", "0.680065", "0.6777259", "0.6777259", "0.6763892", "0.6762232", "0.6760621", "0.67588925", "0.6746972", "0.6690216", "0.6664634", "0.6659432", "0.6653433", "0.6652904", "0.66015613", "0.65948296", "0.65887743", "0.65887743", "0.6586923", "0.6577155", "0.65654397", "0.6560065", "0.65519106", "0.65342164", "0.65322214", "0.65252763", "0.6508073", "0.65072495", "0.6503644", "0.64814746", "0.6478834", "0.6467205", "0.6457145", "0.6424578", "0.6419924", "0.6394493", "0.6391762", "0.63823336", "0.6372313", "0.6371024", "0.63642067", "0.6358066", "0.63548034", "0.6354121", "0.6353336", "0.63517183", "0.6348835", "0.63383657", "0.6334683", "0.63258946", "0.6323486", "0.6306402", "0.629419", "0.62925756" ]
0.6587117
64
Gets video items from feed api endpoint
async function getFeed() { const updates = await appApi.getFeed(); setFeed(updates); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async function getLatestVideos(upId, vidCount){\n const getReqTemp = `https://www.googleapis.com/youtube/v3/playlistItems?playlistId=${upId}&key=${keys.apiKey}&part=snippet,contentDetails&maxResults=${vidCount}`\n\n const response = await fetch(getReqTemp)\n const data = await response.json()\n const videos = data.items\n\n return videos\n\n}", "function getVideoById (feedId) {\n let getVideoByIdUrl = `https://app.ganji.com/api/v1/msc/v1/jn/feed/info/${feedId}?&user_id=732539543&longitude=104.041918&latitude=30.585407&location=45`\n\n request\n .get({\n url: getVideoByIdUrl,\n headers: headers,\n gzip: true\n }, (err, httpResponse, body) => {\n if (err) console.log(err)\n console.log(body) // 200\n })\n}", "async function getVideos() {\n try {\n setSpinner(true);\n\n const params = {\n part: \"snippet\",\n regionCode: \"UY\",\n maxResults: 4,\n q: filter ?? \"\",\n type: \"video\",\n key: process.env.REACT_APP_YOUTUBE_API_KEY,\n };\n\n const responseItems = await requestVideos(params);\n\n // If there is a response, the first item is set as the \"selectedVideo\"\n setFilteredVideos(responseItems);\n if (responseItems?.length > 0) {\n setSelectedVideo(responseItems[0]);\n }\n } catch (e) {\n setResponseError(e.message);\n } finally {\n setSpinner(false);\n }\n }", "async function getChannelVideos(req, res) {\n console.log('PRINTS TO NODEMON SERVER getChannelVideos called in controllers');\n const url = `${BASE_URL}activities?part=snippet,contentDetails&channelId=${CHANNEL_ID}&key=${process.env.YOUTUBE_API_KEY}&maxResults=50`;\n return res.json(await fetch(url).then(res => res.json()));\n}", "function videoHttp() {\n\t\t\tVideoFac.getDataByUrl('videos')\n\t\t\t.then(function(response) {\t\n\t\t\t\t$scope.model.videos=response;\t\t\n\t\t\t\t$scope.totalItems=$scope.model.videos.length;\n\t\t\t\tvar begin = (($scope.currentPage - 1) * $scope.numPerPage)\n\t\t\t\tvar end = begin + $scope.numPerPage;\t\t\t\t\n\t\t\t\t$scope.filteredVideos = $scope.model.videos.slice(begin, end);\n\t\t\t})\n\t\t\t.catch(function(e) {\n\t\t\t\tconsole.log(e);\n\t\t\t})\t\n\t\t\treturn $scope.model.videos\n\t\t}", "function loadVideo() {\n $.getJSON(URL, options, function(data){\n console.log(data)\n var id = data.items[0].snippet.resourceId.videoId;\n mainVideo(id);\n resultsLoop(data);\n });\n }", "function getVideos() {\n //GET THE USER ID\n\n getAllVideos(id)\n .then(res => {\n setVideoList(res.video);\n })\n .catch(err => console.log(err));\n }", "async getVideo(product_id) {\n const endpoint = `${ApplicationMainHost}/api/product/videos/?product_id=${product_id}`;\n let response = await apiService(endpoint);\n this.productVideos = response.results;\n }", "async search10(listOption, videos) {\n let publishedAt\n\n let body = await this.retryRequest(listOption)\n\n // push video id on videos array\n for (let item of body.items){\n if (item !== undefined && item.id.videoId !== undefined){\n videos.push(item.id.videoId)\n console.log('video ' + item.id.videoId + ' fetched')\n }\n }\n\n }", "function getVids(playlist){\n //get videos from selected playlist\n $.get(\n \"https://www.googleapis.com/youtube/v3/playlistItems\", {\n part:'snippet',\n maxResults: 5,\n playlistId: playlist,\n key: apiKey\n },\n function(data){\n //parse data from api\n var output;\n $.each(data.items, function(i, item){\n console.log(item);\n var vidTitle = item.snippet.title;\n var videoId = item.snippet.resourceId.videoId;\n var videoDate = item.snippet.publishedAt;\n var prettyVideoDate = new Date(videoDate).toDateString();\n var videoDesc = item.snippet.description;\n //collect result\n output = '<p><h1>'+vidTitle+'</h1><p>'+videoDesc+'</p><p>'+prettyVideoDate+'</p><iframe height=\"'+vidHeight+'\" width=\"'+vidWidth+'\"src=\\\"//www.youtube.com/embed/'+videoId+'\\\"></iframe></p><hr>';\n\n //append result to content div \n $('#content').append(output);\n\n });// end .each\n }\n );//end get\n }", "getVideos(args) {\n\t\targs = args || {};\n\t\tconst accountId = _.get(args, 'accountId', this.accountId);\n\t\tconst skipScheduleCheck = _.get(args, 'skipScheduleCheck', this.skipScheduleCheck);\n\n\t\tif (!_.isString(accountId)) {\n\t\t\tthrow new Error('An accountId string is required for getVideos()');\n\t\t}\n\n\t\treturn this.getAccessToken(args).then(auth => {\n\t\t\targs = Object.assign({}, args, {\n\t\t\t\tmethod: 'GET',\n\t\t\t\tbaseUrl: Client.CMS_API_BASE_URL,\n\t\t\t\tpath: `/accounts/${accountId}/videos`,\n\t\t\t\tcontentType: Client.DEFAULT_CONTENT_TYPE,\n\t\t\t\tauthorization: this.getBearerAuthorization(auth.access_token),\n\t\t\t\tquery: Object.assign({}, args.query)\n\t\t\t});\n\n\t\t\treturn this\n\t\t\t\t\t\t\t.makeRequest(args)\n\t\t\t\t\t\t\t.then(videos => {\n\t\t\t\t\t\t\t\tif (!_.isEmpty(videos) && !skipScheduleCheck) {\n\t\t\t\t\t\t\t\t\t// using the Client.resolveIfScheduled, resolve with only published videos\n\t\t\t\t\t\t\t\t\treturn Promise.reduce(videos.map(Client.resolveIfScheduled), (published, video) => {\n\t\t\t\t\t\t\t\t\t\tif (video) {\n\t\t\t\t\t\t\t\t\t\t\tpublished.push(video);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\treturn Promise.resolve(published);\n\t\t\t\t\t\t\t\t\t}, []);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tdebug('not checking schedule for videos');\n\t\t\t\t\t\t\t\treturn Promise.resolve(videos);\n\t\t\t\t\t\t\t});\n\t\t});\n\t}", "function getVideos(query, fromPublishedDate, toPublishedDate){\n var today = new Date();\n if (fromPublishedDate === ''){\n fromPublishedDate = \"2019-01-01\";\n }\n\n if (toPublishedDate === ''){\n toPublishedDate = today.getFullYear() + '-' + (today.getMonth()+1) + '-' + today.getDate();\n }\n\n var params = {\n \"q\": query,\n \"key\": keyYoutube,\n \"part\": \"snippet\",\n \"type\": \"video\",\n \"videoCategoryId\": 25,\n \"maxResults\": 15,\n \"publishedAfter\": fromPublishedDate + 'T00:00:00Z',\n \"publishedBefore\": toPublishedDate + 'T23:59:59Z'\n }\n\n const queryString = formatQueryParams(params);\n const url = youtubeUrl + '?' + queryString;\n\n fetch(url)\n .then(response => {\n if(response.ok){\n $('.video-section-title').removeClass('hidden');\n return response.json();\n }\n throw new Error(response.statusText);\n })\n .then(responseJson => displayYoutubeResults(responseJson))\n .catch (err => {\n console.log(`${err.message}`)\n })\n}", "function getVideo(){\n // fetching the api using fetch method\n fetch('https://youtube.googleapis.com/youtube/v3/search?part=snippet&q='+query.value+'&type=video&maxResults=20&key='+api_key)\n // retriving the data using \n .then((response)=>{\n return response.json();\n })\n .then((data)=>{\n console.log(data);\n // we will looping on the data.items\n data.items.forEach((item)=>{\n let vid =\n `<iframe type='text/html' width=\"350\" height=\"200\" src='https://www.youtube.com/embed/${item.id.videoId}' frameborder='0' allowFullScreen>\n </iframe>`;\n video.insertAdjacentHTML(\"afterend\",vid);\n }) \n })\n}", "youtubeVideo(id) {\n return ytRequest('/videos', id)\n .then(res => {\n let item = null;\n if (res.items.length) {\n item = Item.fromApi(ITEM_TYPE.YOUTUBE, {\n title: res.items[0].snippet.title,\n url: `http://youtube.com/watch?v=${id}`,\n srcId: id,\n });\n }\n return item;\n });\n }", "function get_api_data(callback){\n\t\n\t // don't call if api is null\n\t if(api!=null)\n\t\t$.get(api, function(data) {\n\t\t\t\n\t\t\tvar video_list=\"\";\n\t\t\tvar i=0;\n\t\t\t//iterate over each items or vidoes\n\t\t\tdata.items.forEach(function(vd) {\n\t\t\t video_id=vd.id.videoId;\n\t\t\t \n\t\t\t //getCountInMillions(video_id);\n\t\t\t //console.log(\"Views:: \"+viewCount);\n\t\t\t \n\t\t\t title=vd.snippet.title;\n\t\t\t img_url=vd.snippet.thumbnails.medium.url;\n\t\t\t img_url=img_url+\"?campaign\";\n\t\t\t //description=vd.snippet.description;\n\t\t\t channelTitle=vd.snippet.channelTitle;\n\n\t\t\t // create a html element for each vds, Note +=\n\t\t\t video_list+=' \t\\\n\t\t\t <!-- <a id=\"thumbnail\" href=\"https://www.youtube.com/watch?v='+video_id+'\" onclick=\"javascript:openWindow(this.href);return false;\" > --> \\\n\t\t\t <div class=\"panel panel-default\"> \\\n\t\t\t\t<div class=\"panel-body\">\\\n\t\t\t\t <div class=\"row\">\\\n\t\t\t\t\t<div class=\"col-md-8\">\\\n\t\t\t\t\t <div class=\"stats\">\\\n\t\t\t\t\t\t\t<div class=\"media\">\\\n\t\t\t\t\t\t\t <a name=\"thumbnail'+video_id+'\" href=\"https://www.youtube.com/watch?v='+video_id+'\"> \\\n\t\t\t\t\t\t\t <img class=\"mr-3\" src=\"'+img_url+'\" alt=\"Image\">\\\n\t\t\t\t\t\t\t\t<h5 class=\"mt-0\">'+title+'</h5>\\\n\t\t\t\t\t\t\t\t</a> '+channelTitle+'\\\n\t\t\t\t\t\t\t</div>\\\n\t\t\t\t\t </div>\\\n\t\t\t\t\t</div>\\\n\t\t\t\t </div>\\\n\t\t\t\t</div>\\\n\t\t\t </div>\t\\ '\n\t\t\t}); // end of forEach loop\n\n\t\t\t\t//video_list+='<h2>Results:</h2>'+video_list;\n\t\t\t//assigning the created elements to innerHTML\n\t\t\tdocument.getElementById(\"demo\").innerHTML =video_list;\n\t\n\t\t//end of get\n\t\t}).then(function() {\n\t\t\t\n\t\t\tvar a = document.anchors;\n\t\t\t//console.log(document.anchors.length);\n\t\t\tvar i;\n\t\t\tfor (i = 0; i < a.length; i++) {\n\t\t\t\ta[i].addEventListener(\"click\", function() {\n\t\t\t\tif(tab!=null){\n\t\t\t\t\tchrome.tabs.executeScript(tab.id,{\n \t\t\t\t\tcode: \"window.location.assign('\"+this.href+\"');\"\n \t\t\t\t\t});\n\t\t\t\t} \n\t\t\t\telse{\n\t\t\t\t\tchrome.tabs.create({url: this.href}); \n\t\t \t\treturn(false);\n\t\t\t\t} // end of else\n\t \t\t}); //end of event listener\n\n\t\t\t} // end of for\n\t\t}); // end of then fn.\n\n\t\n\n\t} // end of get_api_data", "function get_ChannelVideos( videosContainer , nextPageToken , baseUrl , callBack) {\n if(typeof nextPageToken != \"undefined\")\n {\n $.getJSON( baseUrl + \"&pageToken=\" + nextPageToken ,\n function( data ) {\n for (i = 0; i < data.items.length; i++) {\n videosContainer.push(\n new VideoObj(\n data.items[i].id.videoId,\n data.items[i].snippet.title,\n data.items[i].snippet.thumbnails.default.url,\n data.items[i].snippet.description,\n data.items[i].snippet.thumbnails.medium.url,\n data.items[i].snippet.publishedAt\n ));\n }\n get_ChannelVideos(videosContainer , data.nextPageToken , baseUrl , callBack );\n }\n );\n }else\n {\n /* Recursion done all videos are retrieved */\n callBack();\n }\n }", "getVideoSources(args) {\n\t\targs = args || {};\n\t\tconst accountId = _.get(args, 'accountId', this.accountId);\n\t\tconst videoId = args.videoId;\n\n\t\tif (!_.isString(accountId)) {\n\t\t\tthrow new Error('An accountId string is required for getVideo()');\n\t\t}\n\n\t\tif (!_.isString(videoId)) {\n\t\t\tthrow new Error('A videoId string is required for getVideo()');\n\t\t}\n\n\t\treturn this.getAccessToken(args).then(auth => {\n\t\t\targs = Object.assign({}, args, {\n\t\t\t\tmethod: 'GET',\n\t\t\t\tbaseUrl: Client.CMS_API_BASE_URL,\n\t\t\t\tpath: `/accounts/${accountId}/videos/${videoId}/sources`,\n\t\t\t\tcontentType: Client.DEFAULT_CONTENT_TYPE,\n\t\t\t\tauthorization: this.getBearerAuthorization(auth.access_token),\n\t\t\t\tquery: {}\n\t\t\t});\n\n\t\t\treturn this.makeRequest(args);\n\t\t});\n\t}", "async function getVideo(req, res) {\n const url = `${BASE_URL}videos?part=snippet&id=${req.body.videoId}&key=${process.env.YOUTUBE_API_KEY}`;\n return res.json(await fetch(url).then(res => res.json()));\n}", "function getvideodata(vid, callback) {\n console.log(vid);\n var request = require(\"request\");\n var options = {\n method: \"GET\",\n url: \"https://api.vimeo.com/videos/\" + vid,\n headers: {\n Authorization: \"bearer c59cf735b2ba123e00c4938e74b2238a\",\n \"Content-Type\": \"application/json\",\n Accept: \"application/vnd.vimeo.*+json;version=3.4\",\n },\n };\n request(options, function (error, response) {\n if (error) throw new Error(error);\n // console.log(response.body);\n console.log(\"ok\");\n callback(response.body);\n });\n}", "function loadVideo(){\n\t\tvar myKey = 'AIzaSyB8DNIkjWjz5kOXkGsYIl4zzLNy6-S481I',\n\t\t\tmaxResults = 10,\n\t\t\torder = 'date',\n\t\t\ttype = 'video',\n\t\t\tvideoCaption = 'any',\n\t\t\tvideoCategoryId = 24,\n\t\t\tq = 'movie teaser',\n\t\t\tvideoEmbeddable = true;\n\n\t\tvar request = 'https://www.googleapis.com/youtube/v3/search?part=snippet&q=' + q + '&maxResults=' + maxResults + '&type=' + type + '&videoCaption=' + videoCaption + '&videoCategoryId=' + videoCategoryId + '&videoEmbeddable=' + videoEmbeddable + '&key=' + myKey;\n\n\t\t$.ajax({\n\t\t\turl: request,\n\t\t\tsuccess:function(data){\n\t\t\t\t// handle data from your request here\n\t\t\t\t//data.items[0].videoId\n\t\t\t\tvideoArray = data.items;\n\t\t\t\tplayVideo();\n\n\t\t\t}\n\t\t});\n\t}", "function get_VideosForChannel(APIKey, channel_id, results , callBackFunction , orderBy = \"viewCount\" ) {\n videoContainer = [];\n var count=0;\n var queriesCount = 0;\n \n if(results > 50)\n queriesCount = 50;\n else\n queriesCount = results;\n\n /* order : rating , viewCount , videoCount , title*/\n var baseUri = \"https://www.googleapis.com/youtube/v3/search?part=snippet,id&fields=etag%2Citems%2Ckind%2CnextPageToken%2CpageInfo&order=\" + orderBy + \"&type=video&key=\" + APIKey + \"&channelId=\" + channel_id + \"&maxResults=\" + queriesCount;\n $.getJSON( baseUri ,\n function( data ) {\n for (i = 0; i < data.items.length; i++) {\n videoContainer.push(\n new VideoObj(\n data.items[i].id.videoId,\n data.items[i].snippet.title,\n data.items[i].snippet.thumbnails.default.url ,\n data.items[i].snippet.description,\n data.items[i].snippet.thumbnails.medium.url,\n data.items[i].snippet.publishedAt\n ));\n count++;\n if(count == results)\n {\n get_Video_Stats(APIKey, videoContainer , 0 , callBackFunction );\n return;\n }\n }\n get_ChannelVideos( videoContainer , data.nextPageToken , baseUri , function() { get_Video_Stats(APIKey , videoContainer, 0 , callBackFunction ); }) ;\n }\n );\n}", "function getDataFromApi(searchTerm, callback) {\n const query = {\n maxResults: 5,\n part: 'snippet',\n key: 'AIzaSyBq5kuZ-vFnYlPDd4ikXepEDYYPEsk6cd4',\n q: `${searchTerm}`,\n type: 'video',\n };\n $.getJSON(YOUTUBE_SEARCH_URL, query, callback);\n}", "function requestVideos() {\n return {\n type: \"REQUEST_VIDEOS\"\n }\n}", "function getallvideo(req, res) {\n var axios = require(\"axios\");\n\n var config = {\n method: \"get\",\n url: \"https://api.vimeo.com/me/videos?fields=name,uri,embed.html&per_page=100\",\n headers: {\n Authorization: \"bearer c59cf735b2ba123e00c4938e74b2238a\",\n \"Content-Type\": \"application/json\",\n Accept: \"application/vnd.vimeo.*+json;version=3.4\",\n },\n };\n\n axios(config)\n .then(function (response) {\n // console.log(JSON.stringify(response.data));\n res.send(response.data);\n })\n .catch(function (error) {\n console.log(error);\n });\n}", "function getVideos(id, videoUl) {\n fetch(videosUrl).then(resp => resp.json())\n .then(result => result.map(video => {\n if (video.language.id === id) {\n listVideos(video, videoUl)\n }\n }))\n}", "function findAndPlayVideo() {\n var word = getSearchSeed();\n var requestStr = 'https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&q=' + word + '&type=video&maxResults=50&key=AIzaSyAHu80T94GGhKOzjBs9z5yr0KU8v48Zh60';\n $.ajax({\n type: \"GET\",\n url: requestStr,\n dataType: \"jsonp\",\n contentType: \"application/json; charset=utf-8\",\n jsonpCallback: 'findAndPlayVideoHelper'\n });\n}", "function fetchVideos(searchTerm){\n const videos = axios.get(`https://www.googleapis.com/youtube/v3/search?q=${searchTerm}&part=snippet&key=${API_KEY}`)\n return {\n type: \"FETCH_VIDEOS\",\n payload: videos\n }\n}", "function getAndDisplayVideos() {\n\tgetCategoryVideos(displayCategoryVideos);\n}", "function getCategoryVideos(callbackFn) {\n\t$.ajax('../videos', {\n type: 'GET',\n dataType: 'json'\n })\n .done(function(data){\n callbackFn(data);\n });\n}", "async function getMovies() {\n // TODO: fetch movies from wp headless and call appendMovies\n // https://movie-api.cederdorff.com/wp-json/wp/v2/posts?_embed\n}", "function getAllVideos(){\n var contents = Contents_Live.find({ \"code\": Session.get(\"UserLogged\").code });\n var videosArray = [];\n contents.forEach(function(doc){\n var res = doc.contentType.split(\"/\");\n if(res[0] == \"video\"){\n var obj = {\n '_id': doc._id,\n 'videoName': doc.contentName\n };\n videosArray.push(obj);\n }\n });\n if(videosArray.length > 0){\n return videosArray;\n }else{\n return null;\n }\n}", "async function getVideos() {\n if (user.length === 0) {\n history.push('/')\n toast.error('You need to log in first. Click on the google button on the nav bar to proceed')\n } else {\n const newDoc = await getUserVideos(user);\n const mappedData = newDoc.docs.map(doc => doc.data());\n dispatch(fetchUserVideoAction(mappedData))\n }\n\n }", "async function handleGetVideos(req, res) {\n try {\n const channelIdArr = req.url.split(\"/\");\n const channelId = channelIdArr[channelIdArr.length - 1];\n\n logService.log(`About to fetch videos for channel id - ${channelId}`);\n\n if (!channelId) {\n const noChannelIdError = { \n statusCode: 400, \n message: \"Channel Id not specified\" \n };\n handleError(noChannelIdError);\n }\n\n const videosOnChannel = await apiService.fetchVideos(channelId);\n\n logService.log(`Returning videos for channel - ${channelId}`);\n\n res.end(JSON.stringify(videosOnChannel));\n } catch (err) {\n handleError(err, req, res);\n }\n}", "getVideo(args) {\n\t\targs = args || {};\n\t\tconst accountId = _.get(args, 'accountId', this.accountId);\n\t\tconst videoId = args.videoId;\n\t\tconst skipScheduleCheck = _.get(args, 'skipScheduleCheck', this.skipScheduleCheck);\n\t\tif (!_.isString(accountId)) {\n\t\t\tthrow new Error('An accountId string is required for getVideo()');\n\t\t}\n\n\t\tif (!_.isString(videoId)) {\n\t\t\tthrow new Error('A videoId string is required for getVideo()');\n\t\t}\n\n\t\treturn this.getAccessToken(args).then(auth => {\n\t\t\targs = Object.assign({}, args, {\n\t\t\t\tmethod: 'GET',\n\t\t\t\tbaseUrl: Client.CMS_API_BASE_URL,\n\t\t\t\tpath: `/accounts/${accountId}/videos/${videoId}`,\n\t\t\t\tcontentType: Client.DEFAULT_CONTENT_TYPE,\n\t\t\t\tauthorization: this.getBearerAuthorization(auth.access_token),\n\t\t\t\tquery: {}\n\t\t\t});\n\n\t\t\treturn this\n\t\t\t\t\t\t\t.makeRequest(args)\n\t\t\t\t\t\t\t.then(video => {\n\t\t\t\t\t\t\t\tdebug(`video \"${videoId}\" exists: ${Boolean(video)} skipScheduleCheck: ${skipScheduleCheck}`);\n\t\t\t\t\t\t\t\tif (video && !skipScheduleCheck) {\n\t\t\t\t\t\t\t\t\t// using the Client.resolveIfScheduled, resolve with only published videos\n\t\t\t\t\t\t\t\t\treturn Client.resolveIfScheduled(video);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\treturn Promise.resolve(video);\n\t\t\t\t\t\t\t});\n\t\t});\n\t}", "function getYouTubeVideos(query, maxResults = 10) {\n const params = {\n key: apiKey,\n q: query,\n part: \"snippet, id\",\n maxResults,\n type: \"video\"\n };\n const queryString = formatQueryParams(params);\n const url = searchURL + \"?\" + queryString;\n\n console.log(url);\n\n fetch(url)\n .then(response => {\n if (response.ok) {\n return response.json();\n }\n throw new Error(response.statusText);\n })\n .then(responseJson => displayYoutube(responseJson))\n .catch(err => {\n $(\"#js-error-message\").text(`Something went wrong: ${err.message}`);\n });\n}", "getVideoInformation(link) {\n\t\t\n\t\tif(YoutubeHelper.checkURL(link)) {\n\t\t\t//checking the URL\n\t\t\tlet youtubeID = YoutubeHelper.checkURL(link)\n\t\t\t\n\t\t\t//fetching data from the youtube api after vaidation froma the given ID\n\t\t\txhr(`https://www.googleapis.com/youtube/v3/videos?id=${youtubeID}&key=AIzaSyBgMSJtrr13Q4qTdyOrGktD0Rl0OuOCoag&&&part=snippet,contentDetails`,\n\t\t\t\t\n\t\t\t\t(err, req, body) => {\n\t\t\t\t\t\tbody = JSON.parse(body)\n\t\t\t\t\t\tconsole.log(body.items)\n\n\t\t\t\t\t\tlet title, duration\n\t\t\t\t\t\ttitle = body.items['0'].snippet.title\n\t\t\t\t\t\tduration = YoutubeHelper.convertToSeconds(body.items['0'].contentDetails.duration)\n\n\t\t\t\t\t\t\n\n\t\t\t\t\t\t//Sending to be added to the list\n\t\t\t\t\t\tapp.me.addVideo(title, youtubeID, duration)\n\t\t\t\t\t}\n\t\t\t\t)\n\n\n\t\n\t\t}\n\n\n\t}", "async function getTVShows(url) {\r\n const response = await fetch(url);\r\n const information = await response.json(); \r\n \r\n getPosters(information.results);\r\n \r\n}", "function getCommentbyVid (feedId) {\n let getCommentbyVidUrl = `https://app.ganji.com/api/v1/msc/v1/jn/comment/post/${feedId}/type/1/list?page=1&user_id=732539543`\n return new Promise((resolve, reject) => {\n request\n .get({\n url: getCommentbyVidUrl,\n headers: headers,\n gzip: true\n }, (err, httpResponse, body) => {\n if (err) reject(err)\n // console.log(body) // 200\n\n resolve(JSON.parse(body))\n // body.data.hotList.forEach((item) => {\n // console.log('item', item.comment_id)\n // })\n })\n })\n}", "function getVideo(userSearchName, searchTitle) {\n\tvar q = userSearchName + \" \" + searchTitle + \" karaoke\";\n\n\taddVideoCard(searchTitle);\n\n\t// Run GET Request on API\n\t$.get(\n\t\t\"https://www.googleapis.com/youtube/v3/search\", {\n\t\t\tpart: 'snippet, id',\n\t\t\tq: q,\n\t\t\ttype: 'video',\n\t\t\tmaxResults: 4,\n\t\t\tvideoSyndicated: true,\n\t\t\tvideoEmbeddable: true,\n\t\t\tvideoLicense: 'creativeCommon',\n\t\t\tkey: 'AIzaSyBEw_OnLrWKAKGIzxb2ee5WtfnRR0md67Q'\n\t\t},\n\t\tfunction (data) {\n\n\t\t\t// Log Data\n\t\t\tconsole.log(data);\n\n\t\t\t$.each(data.items, function (i, item) {\n\t\t\t\t// Get Output\n\t\t\t\tvar output = getOutput(item);\n\t\t\t\t//set the new videos to the correct card\n\t\t\t\t//by referencing the card Id created for the card\n\t\t\t\t$('#c-' + cardCount + ' .col-rhs ul').append(output);\n\t\t\t\t$('.card-videos').sortable({ handle: '.video-title', placeholder: 'drop-zone' });\n\t\t\t\t$('.card-videos').disableSelection();\n\t\t\t});\n\t\t}\n\t);\n}", "function getAllVideos(data){\n var videos = [];\n for (var i = 0; i < data.length; i++) {\n for (var j = 0; j < data[i].videos.length; j++) {\n videos.push(data[i].videos[j].id);\n }\n }\n return videos;\n}", "function getYoutubeVideoInfo(id){\r\n var youtubeApiUrl = \"https://gdata.youtube.com/feeds/api/videos/\"; \r\n var v2Parameter = \"?v=2\";\r\n var jsonParameter = \"&alt=json\";\r\n var response = CQ.utils.HTTP.get(youtubeApiUrl + id + v2Parameter + jsonParameter);\r\n return response;\r\n}", "getVideosByPlaylist(args) {\n\t\targs = args || {};\n\t\tconst accountId = _.get(args, 'accountId', this.accountId);\n\t\tconst playlistId = args.playlistId;\n\t\tconst skipScheduleCheck = _.get(args, 'skipScheduleCheck', this.skipScheduleCheck);\n\t\tconst sortByReleaseDate = _.get(args, 'sortByReleaseDate') || false;\n\n\t\tif (!_.isString(accountId)) {\n\t\t\tthrow new Error('An accountId string is required for getVideosByPlaylist()');\n\t\t}\n\n\t\tif (!_.isString(playlistId)) {\n\t\t\tthrow new Error('A playlistId string is required for getVideosByPlaylist()');\n\t\t}\n\n\t\treturn this.getAccessToken(args).then(auth => {\n\t\t\targs = Object.assign({}, args, {\n\t\t\t\tmethod: 'GET',\n\t\t\t\tbaseUrl: Client.CMS_API_BASE_URL,\n\t\t\t\tpath: `/accounts/${accountId}/playlists/${playlistId}/videos`,\n\t\t\t\tcontentType: Client.DEFAULT_CONTENT_TYPE,\n\t\t\t\tauthorization: this.getBearerAuthorization(auth.access_token),\n\t\t\t\tquery: Object.assign({}, args.query)\n\t\t\t});\n\n\t\t\treturn this\n\t\t\t\t.makeRequest(args)\n\t\t\t\t.then(videos => {\n\t\t\t\t\tif (!_.isEmpty(videos) && !skipScheduleCheck) {\n\t\t\t\t\t\t// using the Client.resolveIfScheduled, resolve with only published videos\n\t\t\t\t\t\treturn Promise.reduce(videos.map(Client.resolveIfScheduled), (published, video) => {\n\t\t\t\t\t\t\tif (video) {\n\t\t\t\t\t\t\t\tpublished.push(video);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn Promise.resolve(published);\n\t\t\t\t\t\t}, []);\n\t\t\t\t\t}\n\n\t\t\t\t\tdebug(`not checking schedule for playlist \"${playlistId}\"`);\n\t\t\t\t\treturn Promise.resolve(videos);\n\t\t\t\t})\n\t\t\t\t.then(videos => {\n\t\t\t\t\tif (!_.isEmpty(videos) && sortByReleaseDate) {\n\t\t\t\t\t\treturn Promise.resolve(videos.sort((a, b) => {\n\t\t\t\t\t\t\tlet aDate = new Date(a.published_at);\n\t\t\t\t\t\t\tlet bDate = new Date(b.published_at);\n\n\t\t\t\t\t\t\tif (_.has(a, 'schedule') &&\t!_.isNull(a.schedule) && !_.isUndefined(a.schedule)) {\n\t\t\t\t\t\t\t\tconst startsAt = _.get(a, 'schedule.starts_at');\n\t\t\t\t\t\t\t\tif (!_.isNaN(Date.parse(startsAt))) {\n\t\t\t\t\t\t\t\t\taDate = new Date(startsAt);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (_.has(b, 'schedule') &&\t!_.isNull(b.schedule) && !_.isUndefined(b.schedule)) {\n\t\t\t\t\t\t\t\tconst startsAt = _.get(b, 'schedule.starts_at');\n\t\t\t\t\t\t\t\tif (!_.isNaN(Date.parse(startsAt))) {\n\t\t\t\t\t\t\t\t\tbDate = new Date(startsAt);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// sort newest to oldest\n\t\t\t\t\t\t\treturn bDate - aDate;\n\t\t\t\t\t\t}));\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Promise.resolve(videos);\n\t\t\t\t});\n\t\t});\n\t}", "getVideos(courseId, filters) {\n return axios\n .get(this.apiUrl() + `/api/video-analytics/${courseId}/` + this.getQueryParams(filters), {\n headers: this.authHeader(),\n })\n }", "function getPopularMovies(){\n var url = \"https://api.themoviedb.org/3/movie/popular?api_key=\" + api_key + \"&language=fr\";\n return get(url);\n}", "async getYouTubeVideos(searchQuery, vidLength, resultsPage) { // Search for youtube-trailers by movie name and year\n const baseURL = \"https://www.googleapis.com/youtube/v3/search?\"\n let queryString = Helpers.encodeQueryParams(Helpers.buildYouTubeQueryParams(searchQuery, vidLength, resultsPage));\n let requestURL = baseURL + queryString;\n \n let requestData = await fetch(requestURL) // Fetch data\n .then(response => Helpers.handleErrors(response)) // Check data\n .then(responseJSON => {\n return responseJSON // return JSON\n })\n .catch(e => alert(e));\n let returnObject = { // build returnObject\n urls: [],\n snippets: []\n } \n if (requestData !== undefined) {\n for (let i = 0; i < requestData.items.length; i++) {\n returnObject.urls[i] = requestData.items[i].id.videoId;\n returnObject.snippets[i] = requestData.items[i].snippet;\n }\n }\n \n return returnObject;\n }", "function getYouTubeVideos(query, maxResults=5) {\n const youtubeParams = {\n part: 'snippet', \n maxResults,\n key: apiKey,\n q: query,\n };\n const youtubeQueryString = formatYoutubeQueryParams(youtubeParams)\n const url = `${searchYoutubeURL}?${youtubeQueryString}`;\n\n console.log(url);\n\n fetch(url)\n .then(response => {\n console.log(response)\n if (response.ok) {\n return response.json();\n }\n throw new Error(response.statusText);\n })\n .then(responseJson => displayYoutubeResults(responseJson))\n .catch(err => {\n $('#err').text(`Something went wrong: ${err.message}`);\n });\n}", "function callApi(searchTerm, pageToken, callback){\n const query = {\n type: 'video',\n q: searchTerm,\n maxResults: 6,\n part: 'snippet',\n key: API_KEY,\n pageToken: pageToken\n };\n searchedTerm = searchTerm;\n $.getJSON(URL, query, callback)\n}", "async episodesByFeedUrl(url, options = {}) {\n const { since, ...rest } = options;\n return await this.fetch(\"/episodes/byfeedurl\", {\n ...rest,\n since: toEpochTimestamp(since),\n url,\n });\n }", "function loadVideos(videos) {\r\n $.get(\"https://www.googleapis.com/youtube/v3/playlistItems\", {\r\n part: 'snippet',\r\n maxResults: 8,\r\n playlistId: videos,\r\n key: 'AIzaSyD19Hdf1oKt_cwvfQHnhV51aIW8O4caago'\r\n },\r\n //Looping out the title with label tags and the videos into iframe tags in the HTML page where the id videos exists\r\n function (data) {\r\n var data;\r\n $.each(data.items, function (i, item) {\r\n var video = item.snippet.resourceId.videoId;\r\n var title = item.snippet.title;\r\n $(\"#videos\").append(\"<div><label>\" + title + \"</label><iframe src='//www.youtube.com/embed/\" + video + \"'></iframe></div>\");\r\n });\r\n });\r\n }", "async getVideo() {\n return (await this._client.helix.videos.getVideoById(this._data.video_id));\n }", "function displayVideos(response, search) {\n let results = document.querySelector(\".results\");\n results.innerHTML = \"\";\n response.items.forEach((element) => {\n let videoLink = `https://www.youtube.com/watch?v=${element.id.videoId}`;\n let videoImage = element.snippet.thumbnails.medium.url;\n let videoTitle = element.snippet.title;\n results.innerHTML += `\n <div class=\"segment\">\n <a href = ${videoLink} target=\"_blank\">\n\t\t\t\t\t\t<img src = ${videoImage} alt=\"videoThumbnail\">\n\t\t</a> \n <a href = ${videoLink} target=\"_blank\">\n <p>${videoTitle}</p>\n </a>\n </div>\n `;\n });\n\n // Selecting the buttons through the DOM\n let next = document.querySelector(\"#next\");\n let prev = document.querySelector(\"#previous\");\n\n //Removing the hidden attribute of the next button when doing the first search\n next.removeAttribute(\"hidden\");\n\n //Adding the attribute of the nextPageToken to reuse it when next button is pressed\n next.setAttribute(\"value\", response.nextPageToken);\n\n //Event listener of the next button\n next.addEventListener(\"click\", (event) => {\n event.preventDefault();\n //Fetch call using the attribute of the nextPageToken added to the button\n fetchVideos(search, next.getAttribute(\"value\"));\n //Removing the hidden attribute of the prev button\n prev.removeAttribute(\"hidden\");\n //Setting the new attributes of the prev and next tokens\n next.setAttribute(\"value\", response.nextPageToken);\n prev.setAttribute(\"value\", response.prevPageToken);\n });\n\n //Event listner of the previous button\n prev.addEventListener(\"click\", (event) => {\n event.preventDefault();\n //Fetch call using the attribute of the prevPageToken added to the button\n fetchVideos(search, response.prevPageToken);\n //Updating the previous token\n prev.setAttribute(\"value\", response.prevPageToken);\n });\n}", "function showVideos(){\n\tvar ign;\n\tvar xhr = new XMLHttpRequest();\n\txhr.open(\"GET\", \"/api2\", true);\n\txhr.onreadystatechange = function() {\n \t\tif (xhr.readyState == 4) {\n \t\t\tvidLoader(xhr.responseText);\n \t\t}\n\t}\n\txhr.send();\n}", "function getChannelVideos({\n channelId\n}) {\n console.log({\n channelId\n })\n return collection.find({\n channelId: channelId\n }, {\n sort: {\n publishedAt: -1\n }\n });\n}", "async episodesByFeedId(id, options = {}) {\n const { since, ...rest } = options;\n const parsedId = Array.isArray(id) ? id.join(\",\") : id;\n return await this.fetch(\"/episodes/byfeedid\", {\n ...rest,\n since: toEpochTimestamp(since),\n id: parsedId,\n });\n }", "function displayInstagramVideos(api, count) {\n\n getInstagramApiData(api)\n .then(filterForVideos)\n .catch(handleError);\n\n function filterForVideos(res) {\n\n $.each(res.data, function (index, data) {\n if (data.type === 'video') {\n //hides the unavailable panel once a video is found\n $('.videos-section .video-unavailable').hide();\n\n addVideoToPage(data, count);\n count++;\n }\n // checks if the next batch of paginated data is needed to complete 10 videos, if so runs again with new next_url\n if ((index + 1) === res.data.length && count < 10 && res.pagination.next_url) {\n displayInstagramVideos(res.pagination.next_url, count);\n }\n\n // ensures number of videos doesn't exceed 10\n return count < 10;\n });\n }\n\n function handleError(error) {\n console.error(error.responseJSON.meta.error_message);\n }\n }", "function searchVideos(requestUrl) {\n fetch(requestUrl)\n .then(function (response) {\n console.log(response);\n return response.json();\n })\n .then(function (data) {\n var outcome = data.items;\n console.log(outcome);\n console.log(data);\n // created an array to stored the incoming data and use it later\n var youtubeIdArr = [];\n // for loop to get the video id from the data that the above function renders\n for (var i=0; i < 6; i++){\n var youtubeId = outcome[i].id.videoId;\n youtubeIdArr[i]= youtubeId;\n }\n console.log(youtubeIdArr);\n // variable to add videoId to the youtube embeded link\n var embededId= 'https://www.youtube.com/embed/';\n console.log(embededId);\n \n // creating for loop to populate video's list\n var iframeEl =$('#videoPlayer').find('iframe');\n for (var d=0; d < 6 && d < youtubeIdArr.length; d++){\n var embededId= 'https://www.youtube.com/embed/';\n // adding the youtube url and id to our iframes on html\n $(iframeEl[d]).attr('src',embededId+youtubeIdArr[d]);\n\n console.log(youtubeIdArr[d]);\n \n }\n })\n }", "getVideo(videoResolvable) {\n return __awaiter(this, void 0, void 0, function* () {\n const id = yield this.getId(videoResolvable, 'video');\n return this.getItemById(entities_1.Video, id);\n });\n }", "function findAndStoreVideo() {\n var word = getSearchSeed();\n var requestStr = 'https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&q=' + word + '&type=video&maxResults=50&key=AIzaSyAHu80T94GGhKOzjBs9z5yr0KU8v48Zh60';\n $.ajax({\n type: \"GET\",\n url: requestStr,\n dataType: \"jsonp\",\n contentType: \"application/json; charset=utf-8\",\n jsonpCallback: 'findAndStoreVideoHelper'\n });\n}", "function fetchVideos(search, page) {\n console.log(search);\n let url =\n link +\n YouTubeKey +\n type +\n part +\n maxResults +\n token +\n page +\n order +\n \"&\" +\n \"q=\" +\n search;\n console.log(url);\n fetch(url)\n .then((response) => {\n if (response.ok) {\n return response.json();\n }\n throw new Error(response.statusText);\n })\n .then((responseJSON) => {\n displayVideos(responseJSON, search);\n })\n .catch((err) => {\n console.log(err.message);\n });\n}", "async function fetchMovies() {\r\n let response = await fetch(' https://api.themoviedb.org/3/movie/popular?api_key=f485e5c815c3b8ee3e79e1f1309aa1b1&language=en-US&page=1');\r\n\r\n\r\n if (response.status === 200) {\r\n let data = await response.json();\r\n\r\n console.log(data.results);\r\n showMovise(data.results);\r\n\r\n } else {\r\n\r\n\r\n console.log(response.status); // 400\r\n console.log(response.statusText); // Not Found\r\n\r\n }\r\n}", "async function fetchData() {\n\t\t\tconst request = await axios.get(\n\t\t\t\t`https://api.themoviedb.org/3/movie/upcoming?api_key=${api_key}&language=en-US`\n\t\t\t);\n\t\t\t// gets base url from axios.js and parse the extension from requests.js\n\t\t\tsetListing(request.data.results);\n\t\t\tconsole.log(request.data.results);\n\t\t}", "async function getChannelVideos_expensive(channelId) {\n\tconst params = {\n\t\tkey: 'AIzaSyCZUzsEt22XubrBqE5-iQ7nGPoudRSBWEM',\n\t\tpart: 'snippet',\n\t\tchannelId,\n\t\tmaxResults: 50,\n\t\ttype: 'video'\n\t};\n\n\tconst videos = [];\n\tlet res = null;\n\tdo {\n\t\tres = await get('https://www.googleapis.com/youtube/v3/search', params);\n\t\tfor(let item of res['items'])\n\t\t\tvideos.push(item);\n\t\tparams['pageToken'] = res['nextPageToken'];\n\t} while(params['pageToken']);\n\n\treturn videos;\n}", "function loadVideos() {\n BCMAPI.callback = getProcessVideosDelegateName();\n BCMAPI.find(\"find_videos_by_ids\", {\"video_ids\": config.videoIDs});\n }", "function getChannelVideoIds(channelName, channelId, nextPageToken = \"\", videosCollected = 0) {\n axios.get(`https://www.googleapis.com/youtube/v3/search?key=${YOUTUBE_API_KEY}&channelId=${channelId}&part=snippet,id&order=date&maxResults=${maxResults}&pageToken=${nextPageToken}`)\n .then(async (res) => {\n // if (videosCollected < resultsLimit) {\n // getChannelVideoIds(channelName, channelId, res.data.nextPageToken, videosCollected += maxResults);\n // }\n\n for (let item of res.data.items) {\n const videoId = item.id.videoId;\n const title = item.snippet.title;\n const createdAt = Date.now();\n const params = {\n TableName: \"Videos\",\n Item: {\n videoId,\n channelId,\n channelName,\n title,\n createdAt\n }\n };\n\n try {\n await dynamoDbLib.call(\"put\", params);\n success(params.Item);\n } catch (e) {\n failure({ status: false });\n }\n }\n })\n .catch(err => {\n console.log(err);\n });\n }", "function getYouTubeVideos(query, maxResults) {\n let tempMaxResults = $('#js-max-results').val();\n\n hide('.error-message');\n\n if( !(isNaN(tempMaxResults)) ){\n if(tempMaxResults>1 && tempMaxResults<=50){\n maxResults = tempMaxResults;\n }\n else if(tempMaxResults<0 || tempMaxResults>50){\n $('#js-error-message').text(`Invalid Entry: out of range.`);\n clearList();\n show('.error-message');\n return;\n\n }\n else if(tempMaxResults==1){\n $('#js-error-message').text(`Invalid Entry: enter more than one.`);\n clearList();\n show('.error-message');\n return;\n }\n \n }\n else{\n $('#js-error-message').text(`Invalid Entry: not a number.`);\n clearList();\n show('.error-message');\n return;\n }\n\n //setting the parameters\n const params = {\n key: YVAC_STORE.apiKey,\n q: query,\n part: 'snippet',\n maxResults,\n type: 'video'\n };\n const queryString = formatQueryParams(params)\n const url = YVAC_STORE.searchURL + '?' + queryString; \n\n fetch(url)\n .then(response => {\n if (response.ok) {\n return response.json();\n }\n throw new Error(response.statusText);\n })\n .then(responseJson => displayResults(responseJson))\n .catch(err => {\n $('#js-error-message').text(`Something went wrong: ${err.message}`);\n });\n}", "function getDataFromApi(searchTerm, callback) {\n console.log(page);\n const query = {\n q: searchTerm,\n key: 'AIzaSyDFTWYdlQDBnJkoLoucEOBenpdnNCYy3wA',\n part: 'snippet',\n fields: 'nextPageToken,items(snippet(thumbnails),id)' , \n maxResults: 6,\n pageToken: page,\n }\n $.getJSON(YOUTUBE_SEARCH_URL, query, callback)\n .fail(showErr);\n }", "function topGlobal()\n{\n return fetch('https://www.googleapis.com/youtube/v3/videos?part=snippet'\n + '&maxResults=50'\n + '&chart=mostPopular' \n + '&videoCategoryId=10'\n + '&key=' + \"AIzaSyCDLBp4ecF3bkrq_rJWb47Gu9hdtw58YrU\",{\n method: 'get'\n })\n .then(res => res.json())\n .catch(error => console.log(error))\n}", "function getVideo(searchQuery) {\n\n $.ajax({\n type: 'GET',\n url: 'https://www.googleapis.com/youtube/v3/search',\n data: {\n key: APIKeyArr[randomNumber],\n q: searchQuery,\n part: 'snippet',\n maxResults: 1,\n type: 'video',\n videoEmbeddable: true,\n },\n success: function (data) {\n embedVideo(data)\n },\n error: function (response) {\n console.log(\"Request Failed\");\n }\n });\n}", "function showNextPage() {\n var token = $(\"#next-button\").data('token');\n var q = $('#next-button').data('query');\n \n $(\"#videos-view\").empty();\n $(\"#buttons\").empty();\n\n var params = $.param({\n part: 'snippet, id',\n maxResults: '1',\n q: keyword,\n pageToken: token,\n type: 'video', \n key: 'AIzaSyBbcLfQsPms45781ZJd_5pwv-V3sj6G9C0'\n });\n var url = \"https://www.googleapis.com/youtube/v3/search?\" + params;\n console.log(url);\n\n q = $(\".input\").val();\n\n $.ajax({\n url: url,\n method: \"GET\"\n }).then(function(data) {\n\n var nextPageToken = data.nextPageToken;\n var prevPageToken = data.prevPageToken;\n\n console.log(\"Response length: \" + data.items.length)\n \n $.each(data.items, function(i, item){ \n\n var result = showVideos(item);\n\n $(\"#videos-view\").append(result)\n });\n\n var buttons = showButtons(prevPageToken, nextPageToken);\n\n $(\"#buttons\").append(buttons);\n\n});\n}", "function getRequest(searchTerm) {\n var url = \"https://www.googleapis.com/youtube/v3/search\";\n var params = {\n part: 'snippet',\n q: searchTerm,\n type: 'video',\n lr: 'en',\n maxResults: 40,\n fields: \"items(id,snippet(title))\",\n key: \"AIzaSyBlEuyTfWft-SGXTn0gYJ_cT6WJVJrtKdg\"\n };\n \n $.getJSON(url, params, function(data) {\n console.log(data);\n showResults(data.items);\n });\n}", "async function getVideos(playlistId) {\r\n const videos = [];\r\n try {\r\n let pageToken = \"\";\r\n while (true) {\r\n const { data } = await service.playlistItems.list({\r\n part: [\"snippet\"],\r\n playlistId,\r\n maxResults: 5,\r\n pageToken,\r\n });\r\n videos.push(...data.items);\r\n\r\n if (!data.nextPageToken) break;\r\n pageToken = data.nextPageToken;\r\n }\r\n } catch (err) {\r\n console.error(`Failed to get videos. ${err.message}`);\r\n }\r\n\r\n return videos;\r\n}", "function search() {\n\tvar request = gapi.client.youtube.search.list({\n\t part: \"snippet\",\n\t type: \"video\",\n\t q: encodeURIComponent($(\"#search\").val()).replace(/%20/g, \"+\"),\n\t maxResults: 4,\n\t order: \"viewCount\",\n\t publishedAfter: \"2016-01-01T00:00:00Z\"\n\t});\n\n \trequest.execute(function(response) {\n \tvar str = JSON.stringify(response.result);\n \tvar htmlStr = \"\";\n \t$.each(response.result.items, function(index, item) {\n\t htmlStr += \"<div class='video'>\";\n\t htmlStr += \"<a href='add/\" + item.id.videoId + \"'>Add</a><br>\";\t \n\t htmlStr += \"<img src='https://i.ytimg.com/vi/\" + item.id.videoId + \"/default.jpg' id=\" + item.id.videoId + \" alt='\" + item.snippet.title + \"'>\";\n\t htmlStr += \"</div>\";\n\t \t});\n\n \t// $('#results').html('<h1>' + response.result.items[0].id.videoId + '</h1>');\n \t$('#results').html(htmlStr);\n\n });\n}", "function getNowPlayingMovies() {\n\n const path = '/movie/now_playing';\n\n const url = generateUrl(path);\n\n const render = renderMovies.bind({title: 'Now Playing Movies'});\n\n sectionMovies(url, render, handleError);\n\n\n}", "function get_playlists(APIKey , channelid , maxResults , callBackFunction ) {\n $.getJSON( \"https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=\" + channelid + \"&maxResults=\" + maxResults + \"&fields=etag%2Citems%2Ckind%2CnextPageToken%2CpageInfo&key=\" + APIKey ,\n //callback\n function(data) {\n var playlistContainer = [];\n data.items.forEach( function (element){\n playlistContainer.push(new PlayListObj(element.id , element.snippet.title, element.snippet.description , element.snippet.publishedAt , element.snippet.thumbnails.default.url));\n }, this);\n\n callBackFunction(playlistContainer);\n });\n}", "searchMovie() {\n axios\n .get('https://api.themoviedb.org/3/search/movie?', {\n params: {\n 'api_key': '5081a73eac2719896b2d02d515f944ac',\n 'query': this.userInput,\n \n }\n })\n .then((response) => { \n this.movieCollection = response.data.results\n \n });\n\n axios\n .get('https://api.themoviedb.org/3/search/tv?', {\n params: {\n 'api_key': '5081a73eac2719896b2d02d515f944ac',\n 'query': this.userInput,\n \n }\n })\n .then((response) => { \n this.tvCollection = response.data.results\n \n });\n }", "function requestUserUploadsPlaylistId() {\n var request = gapi.client.youtube.videos.list({\n part: 'snippet',\n chart: 'mostPopular',\n // myRating: 'like',\n maxResults: 20,\n });\n request.execute(function(response) {\n var foo = response.items;\n for(var i=0; i<foo.length; i++) {\n var str = response.items[i].id;\n $('#video-container').append(\"<iframe width='640' height='320' src='https://www.youtube.com/embed/\"+str+\"'>\");\n }\n })\n}", "async function getVideoInfo() {\n\tlet videos = document.querySelectorAll(\n\t\t'ytd-browse #contents #contents #items ytd-thumbnail .yt-simple-endpoint.inline-block.style-scope.ytd-thumbnail'\n\t);\n\tlet titleEles = document.querySelectorAll('#contents #contents #items #video-title');\n\n\tlet srcAry = [];\n\n\tfor (let i = 0; i < videos.length; i++) {\n\t\tlet titleEle = titleEles[i];\n\t\tlet videoTitle = titleEle.innerText;\n\t\tlet videoInfo = {};\n\t\tlet video = videos[i];\n\t\tlet href = video.getAttribute('href');\n\t\tlet vars = href.split('?')[1];\n\t\tlet src = vars.split('v=')[1];\n\n\t\tvideoTitle ? (videoInfo.title = videoTitle) : '';\n\t\tsrc ? (videoInfo.id = src) : '';\n\t\tsrcAry.push(videoInfo);\n\t}\n\n\treturn srcAry;\n}", "function searchVideo(keyword, callback, startIndex) {\r\n var url = 'http://gdata.youtube.com/feeds/api/videos/-/' + keyword\r\n + '?v=2' \r\n + '&alt=json' \r\n + '&max-results=10'\r\n callApi(url, callback, parseJson);\r\n }", "function requestVideoPlaylist(playlistId, pageToken) {\n document.getElementById('video-container').innerHTML = \"\";\n //$('#video-container').html('');\n var requestOptions = {\n playlistId: playlistId,\n part: 'snippet',\n maxResults: 10\n };\n if (pageToken) {\n requestOptions.pageToken = pageToken;\n }\n var request = gapi.client.youtube.playlistItems.list(requestOptions);\n request.execute(function(response) {\n nextPageToken = response.result.nextPageToken;\n var nextVis = nextPageToken ? 'visible' : 'hidden';\n //$('#next-button').css('visibility', nextVis);\n document.getElementById('next-button').style.visibility = nextVis;\n prevPageToken = response.result.prevPageToken;\n var prevVis = prevPageToken ? 'visible' : 'hidden';\n //$('#prev-button').css('visibility', prevVis);\n document.getElementById('prev-button').style.visibility = prevVis;\n var playlistItems = response.result.items;\n if (playlistItems) {\n playlistItems.forEach(function(item){\n displayResult(item.snippet);\n });\n } else {\n document.getElementById('video-container').innerHTML = 'Sorry you have no uploaded videos';\n //$('#video-container').html('Sorry you have no uploaded videos');\n }\n });\n}", "function getVideosInPlaylist(name) {\r\n\tvar data = {};\r\n\tdata[\"playlistName\"] = name;\r\n\tvar js = JSON.stringify(data);\r\n\t\r\n\tvar xhr = new XMLHttpRequest();\r\n\txhr.open(\"POST\", getVideosInPlaylistURL, true);\r\n\txhr.send(js);\r\n\t\r\n\txhr.onloadend = function () {\r\n\t\tif (xhr.readyState == XMLHttpRequest.DONE) {\r\n\t\t\tconsole.log (\"XHR:\" + xhr.responseText);\r\n\t\t\tclearPlaylistVideos();\r\n\t\t\tprocessPlaylistVideos(xhr.responseText);\r\n\t\t} else {\r\n\t\t}\r\n\t};\r\n}", "function getVideos(fn){\r\n\tMongoClient.connect(uri, function(err, db) {\r\n\t\r\n\t\tif(err) throw err;\r\n\t\t\r\n\t\tvar collection = db.collection('video');\r\n\t\t//gets all available videos and sends them to user\r\n\t\tcollection.find().toArray(function(err, results) {\r\n\t\t\tfn(results);\r\n\t\t\tdb.close();\r\n\t\t});\r\n\t\t\r\n\t});\r\n}", "function GetVideoByCategoryId(id) {\n return $resource(_URLS.BASE_API + 'get_video_by_category_id/' + id + _URLS.TOKEN_API + $localStorage.token).get().$promise;\n }", "getTitle(videoId) {\n return fetch (VIDEO_ENDPOINT + videoId)\n .then(response => response.json())\n .catch (error => \n console.error(error)\n )\n }", "function search_videos(APIKey , Keywords , MaxResults , OrderBy , callBackFunction ){\n \n if( MaxResults > 50 )\n MaxResults = 50;\n\n Keywords = \"&q=\" + Keywords;\n \n var myurl = \"https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=\" + MaxResults + \"&order=\" + OrderBy + Keywords + \"&type=video&fields=etag%2Citems%2Ckind%2CnextPageToken%2CpageInfo%2CregionCode&key=\" + APIKey;\n $.getJSON( myurl , function(data) {\n /*On success callback*/\n var videosContainer = [];\n var video;\n\n data.items.forEach(function(element) {\n video = new VideoObj(element.id.videoId, element.snippet.title,element.snippet.thumbnails.default.url,element.snippet.description, element.snippet.thumbnails.medium.url,element.snippet.publishedAt);\n video.channelid = element.snippet.channelId;\n video.channeltitle = element.snippet.channeltitle;\n videosContainer.push(video);\n }, this);\n\n get_Video_Stats(APIKey , videosContainer , 0 , callBackFunction);\n });\n}", "moviesList(){\n for (let i = 0; i < this.homeMovies.length; i++) {\n axios.get(`https://api.themoviedb.org/3/movie/${this.homeMovies[i].url}`, {\n params: {\n 'api_key': API_KEY,\n language: this.language,\n page: this.homeIndex,\n\n }\n }).then(now => {\n this.homeMovies[i].movies = now.data.results;\n });\n }\n }", "function requestPlaylist() {\n var request = gapi.client.youtube.playlists.list({\n channelId : channelId,\n part: 'contentDetails',\n maxResults: 50\n });\n request.execute(function(response) {\n console.log(response);\n var playlistArr = response.result.items;\n for(var i = 0 ; i < playlistArr.length ; i++){\n var item = playlistArr[i];\n var playlistId = item.id;\n requestVideoPlaylist(playlistId);\n }\n \n });\n}", "async function fetchUpcomingMovies() {\n let response = await fetch(props.baseUrl + \"movies/?&status=PUBLISHED\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"no-cache\",\n }\n })\n response = await response.json();\n setUpcomingMovies(response.movies);\n }", "async fetchPopularFilms() {\n let popularFilms = 'trending/movie/week?';\n try {\n const response = await axios.get(\n BASE_URL +\n popularFilms +\n API_KEY +\n '&language=en-US&page=' +\n `&page=${this.localService.getPaginationPage()}`,\n );\n this.localService.setLocalTotalCards(response.data.total_results);\n this.localService.setPaginationPage(response.data.page);\n return response.data;\n } catch (error) {\n return error;\n }\n }", "function GetVideosByTitle(title) {\n return $resource(_URLS.BASE_API + 'get_videos_by_title/' + title + _URLS.TOKEN_API + $localStorage.token).get().$promise;\n }", "function GetVideosByTitle(title) {\n return $resource(_URLS.BASE_API + 'get_videos_by_title/' + title + _URLS.TOKEN_API + $localStorage.token).get().$promise;\n }", "function getVidDeets(id,what){\n\t \n\t\t\tvar toReturn;\n\t\t\tvar getURL =\"https://www.googleapis.com/youtube/v3/videos?part=id%2Csnippet&id=\"\n\t+ id + \"&key=\" + ytApiKey;\n\t\n\t\n\t\n\t\n\t$.ajaxSetup({async: false});\n\tif(what == 'title'){ // when what i want is a title return the title relating to the id\n\t\tvar vidData = $.get(getURL, function(data) {\n\t\t\ttoReturn = data.items[0].snippet.title;\n\t\t});\n\t}\n\t\n\telse if(what == 'tn'){ // when what i want is a thumbnail return the thumbnail relating to the id\n\t\tvar vidData = $.get(getURL, function(data) {\n\t\t\ttoReturn = data.items[0].snippet.thumbnails.medium.url;\n\t\t\t\n\t\t});\n\t}\n\telse if(what == 'ltn'){// when what i want is a high quality thumbnail return the thumbnail relating to the id\n\t\t\t\tvar vidData = $.get(getURL, function(data) {\n\t\t\t\t\ttoReturn = data.items[0].snippet.thumbnails.high.url;\n\t\t\t\t\t\n\t\t\t\t});\n\t\t\t}\n\t$.ajaxSetup({async: true});\n\treturn toReturn;\n}", "function getEpisodes() {\n let api = \"../api/Episodes/Admin\";\n\n ajaxCall(\"GET\", api, \"\", getEpisodesSuccessCB, getErrorCB);\n}", "function getMovieList(callback){\n\tconst query = {\n\t\tapi_key: TMDB_API_AUTH.KEY,\n\t\tsort_by: \"release_date.desc\",\n\t\tpage: pageCounter\n\t};\n\t$.getJSON(TMDB_SEARCH_URL_MOVIES_LIST, query, callback);\n}", "function GetVideoById(id) {\n return $resource(_URLS.BASE_API + 'get_video_by_id/' + id + _URLS.TOKEN_API + $localStorage.token).get().$promise;\n }", "function relatedVideos(data) {\n console.log(data);\n\n var monthNames = [ \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n \"July\", \"August\", \"September\", \"October\", \"November\", \"December\" ];\n var contentAV = '<div class=\"related-audio-video\">';\n\n var current_url = $.param.fragment();\n\n $.each(data.media, function(rInd, rElm) {\n contentAV += '<div class=\"shanti-thumbnail video col-lg-2 col-md-3 col-sm-4 col-xs-12\">';\n contentAV += '<div class=\"shanti-thumbnail-image shanti-field-video\">';\n contentAV += '<a href=\"#' + current_url + '&nid=' + rElm.nid + '\" class=\"shanti-thumbnail-link\">';\n contentAV += '<span class=\"overlay\">';\n contentAV += '<span class=\"icon\"></span>';\n contentAV += '</span>';\n contentAV += '<img src=\"' + rElm.thumbnail + '/width/360/height/270/type/2/bgcolor/000000' + '\" alt=\"Video\" typeof=\"foaf:Image\" class=\"k-no-rotate\">';\n contentAV += '<i class=\"shanticon-video thumbtype\"></i>';\n contentAV += '</a>';\n contentAV += '</div>';\n contentAV += '<div class=\"shanti-thumbnail-info\">';\n contentAV += '<div class=\"body-wrap\">';\n contentAV += '<div class=\"shanti-thumbnail-field shanti-field-created\">';\n contentAV += '<span class=\"shanti-field-content\">';\n var date = new Date(parseInt(rElm.created) * 1000);\n contentAV += date.getDate() + ' ' + monthNames[date.getMonth()] + ' ' + date.getFullYear();\n contentAV += '</span>';\n contentAV += '<div class=\"shanti-thumbnail-field shanti-field-title\">';\n contentAV += '<span class=\"field-content\">';\n contentAV += '<a href=\"#' + current_url + '&nid=' + rElm.nid + '\" class=\"shanti-thumbnail-link\">';\n contentAV += rElm.title;\n contentAV += '</a>';\n contentAV += '</span>';\n contentAV += '</div>';\n contentAV += '<div class=\"shanti-thumbnail-field shanti-field-duration\">';\n contentAV += '<span class=\"field-content\">' + rElm.duration.formatted + '</span>';\n contentAV += '</div>';\n contentAV += '</div>';\n contentAV += '</div>';\n contentAV += '<div class=\"footer-wrap\">';\n contentAV += '</div>';\n contentAV += '</div>';\n contentAV += '</div>';\n });\n\n contentAV += '</div>';\n\n var avURL = Settings.mediabaseURL + '/services/' + Settings.app + '/' + Settings.hash_obj.id + '?rows=12';\n var total_pages = parseInt(data.total / data.rows);\n\n contentAV += '<ul id=\"photo-pagination\">';\n contentAV += '<li class=\"first-page\"><a href=\"' + avURL + '&pg=1' + '\">&lt;&lt;</a></li>';\n contentAV += '<li class=\"previous-page\"><a href=\"' + avURL + '&pg=1' + '\">&lt;</a></li>';\n contentAV += '<li>PAGE</li>';\n contentAV += '<li><input type=\"text\" value=\"1\" class=\"page-input\"></li>';\n contentAV += '<li>OF ' + total_pages + '</li>';\n contentAV += '<li class=\"next-page\"><a href=\"' + avURL + '&pg=2' + '\">&gt;</a></li>';\n contentAV += '<li class=\"last-page\"><a href=\"' + avURL + '&page=' + total_pages + '\">&gt;&gt;</a></li>';\n contentAV += '</ul>';\n contentAV += '<div class=\"paginated-spin\"><i class=\"fa fa-spinner\"></i></div>';\n\n $(\"#tab-audio-video\").append(contentAV);\n\n //Add the event listener for the first-page element\n $(\"li.first-page a\").click(function(e) {\n e.preventDefault();\n var currentTarget = $(e.currentTarget).attr('href');\n $.ajax({\n url: currentTarget,\n beforeSend: function(xhr) {\n $('.paginated-spin i.fa').addClass('fa-spin');\n $('.paginated-spin').show();\n }\n })\n .done(paginatedVideos)\n .always(function() {\n $('.paginated-spin i').removeClass('fa-spin');\n $('.paginated-spin').hide();\n $('li input.page-input').val('1');\n $('li.previous-page a').attr('href', currentTarget);\n var nextTarget = currentTarget.substr(0, currentTarget.lastIndexOf('=') + 1) + 2;\n $('li.next-page a').attr('href', nextTarget);\n });\n });\n\n //Add the listener for the previous-page element\n $(\"li.previous-page a\").click(function(e) {\n e.preventDefault();\n var currentTarget = $(e.currentTarget).attr('href');\n currentTarget = currentTarget.substr(0, currentTarget.lastIndexOf('=') + 1);\n var newpage = parseInt($('li input.page-input').val()) - 1;\n if (newpage < 1) { newpage = 1; }\n var currentURL = currentTarget + newpage;\n var previousTarget = currentTarget + ((newpage - 1) < 1 ? 1 : (newpage - 1));\n var nextTarget = currentTarget + ((newpage + 1) > parseInt(total_pages) ? total_pages : (newpage + 1));\n $.ajax({\n url: currentURL,\n beforeSend: function(xhr) {\n $('.paginated-spin i.fa').addClass('fa-spin');\n $('.paginated-spin').show();\n }\n })\n .done(paginatedVideos)\n .always(function() {\n $('.paginated-spin i').removeClass('fa-spin');\n $('.paginated-spin').hide();\n $('li input.page-input').val(newpage);\n $(e.currentTarget).attr('href', previousTarget);\n $('li.next-page a').attr('href', nextTarget);\n });\n });\n\n //Add the listener for the next-page element\n $(\"li.next-page a\").click(function(e) {\n e.preventDefault();\n var currentTarget = $(e.currentTarget).attr('href');\n currentTarget = currentTarget.substr(0, currentTarget.lastIndexOf('=') + 1);\n var newpage = parseInt($('li input.page-input').val()) + 1;\n if (newpage > parseInt(total_pages)) { newpage = parseInt(total_pages); }\n var currentURL = currentTarget + newpage;\n var previousTarget = currentTarget + ((newpage - 1) < 1 ? 1 : (newpage - 1));\n var nextTarget = currentTarget + ((newpage + 1) > parseInt(total_pages) ? total_pages : (newpage + 1));\n $.ajax({\n url: currentURL,\n beforeSend: function(xhr) {\n $('.paginated-spin i.fa').addClass('fa-spin');\n $('.paginated-spin').show();\n }\n })\n .done(paginatedVideos)\n .always(function() {\n $('.paginated-spin i').removeClass('fa-spin');\n $('.paginated-spin').hide();\n $('li input.page-input').val(newpage);\n $('li.previous-page a').attr('href', previousTarget);\n $(e.currentTarget).attr('href', nextTarget);\n });\n });\n\n //Add the listener for the pager text input element\n $(\"li input.page-input\").change(function(e) {\n e.preventDefault();\n var currentTarget = avURL + '&pg=';\n var newpage = parseInt($(this).val());\n if (newpage > parseInt(total_pages)) { newpage = parseInt(total_pages); }\n if (newpage < 1) { newpage = 1; }\n var currentURL = currentTarget + newpage;\n var previousTarget = currentTarget + ((newpage - 1) < 1 ? 1 : (newpage - 1));\n var nextTarget = currentTarget + ((newpage + 1) > parseInt(total_pages) ? total_pages : (newpage + 1));\n $.ajax({\n url: currentURL,\n beforeSend: function(xhr) {\n $('.paginated-spin i.fa').addClass('fa-spin');\n $('.paginated-spin').show();\n }\n })\n .done(paginatedVideos)\n .always(function() {\n $('.paginated-spin i').removeClass('fa-spin');\n $('.paginated-spin').hide();\n $('li input.page-input').val(newpage);\n $('li.previous-page a').attr('href', previousTarget);\n $('li.next-page a').attr('href', nextTarget);\n });\n });\n\n //Add the event listener for the last-page element\n $(\"li.last-page a\").click(function(e) {\n e.preventDefault();\n var currentTarget = $(e.currentTarget).attr('href');\n var newpage = parseInt(total_pages);\n var previousTarget = avURL + (newpage - 1);\n $.ajax({\n url: currentTarget,\n beforeSend: function(xhr) {\n $('.paginated-spin i.fa').addClass('fa-spin');\n $('.paginated-spin').show();\n }\n })\n .done(paginatedVideos)\n .always(function() {\n $('.paginated-spin i').removeClass('fa-spin');\n $('.paginated-spin').hide();\n $('li input.page-input').val(newpage);\n $('li.previous-page a').attr('href', previousTarget);\n $('li.next-page a').attr('href', currentTarget);\n });\n });\n}", "async function getMovies(apiUrl) {\n\n const response = await fetch(apiUrl);\n const data = await response.json();\n console.log(data.results)\n showMovies(data.results);\n}", "async function getMovies(url) {\n var resp = await fetch(url);\n var respData = await resp.json();\n showMovies(respData.results);\n}", "function getVideo(){\n $.getJSON(\"http://127.0.0.1:5000/downloadVideo/\"+id, function(json){\n receivedObjects = json;\n console.log(receivedObjects);\n document.getElementById(\"searchButton\").disabled = false;\n downloadDisplay.innerHTML = \"Download finished\";\n });\n}", "static findVideo(req,res) {\n console.log(\"Masuk ke static findAll\")\n Video.find({})\n .then(lists => {\n console.log(\"Hasil pencarian video: \", lists )\n res.status(200).json({\n msg: `List Video by all users`,\n data: lists\n })\n })\n .catch(error => {\n console.log(error)\n res.status(500).json({\n msg: 'ERROR find video: ',error\n }) \n })\n }", "function getVideoP(req, res) {\n\n VideoP.find(function (err, videosp) {\n if (err) {\n res.status(422);\n res.json({ error: err });\n }\n res.status(200);\n res.json(videosp);\n });\n}", "function apiVideo (opts, cb) {\n if (!opts.q && (!opts.name || !opts.artistName)) return cb(new Error('Missing required `q` or (name` and `artistName`) key'))\n if (opts.q && (opts.name || opts.artistName)) return cb(new Error('Do not include `q` and (`name` or `artistName`) key'))\n\n if (typeof opts.maxResults === 'string') opts.maxResults = Number(opts.maxResults)\n\n debug('%o', opts)\n\n const url = 'https://www.googleapis.com/youtube/v3/search'\n const params = {\n // The part parameter specifies a comma-separated list of one or more search\n // resource properties that the API response will include. (string)\n part: 'snippet',\n\n // The maxResults parameter specifies the maximum number of items that should\n // be returned in the result set. Acceptable values are 0 to 50, inclusive. The\n // default value is 5. (unsigned integer)\n maxResults: opts.maxResults\n ? Math.min(Math.max(opts.maxResults, 0), 50)\n : 5,\n\n // The safeSearch parameter indicates whether the search results should include\n // restricted content as well as standard content. Acceptable values are:\n // 'moderate', 'none', 'strict'. (string)\n safeSearch: 'none',\n\n // The videoEmbeddable parameter lets you to restrict a search to only videos\n // that can be embedded into a webpage. If you specify a value for this\n // parameter, you must also set the type parameter's value to video. Acceptable\n // values are: 'any', 'true'. (string)\n videoEmbeddable: 'true',\n\n // The videoSyndicated parameter lets you to restrict a search to only videos\n // that can be played outside youtube.com. If you specify a value for this\n // parameter, you must also set the type parameter's value to video. Acceptable\n // values are: 'any', 'true'. (string)\n videoSyndicated: 'any',\n\n // The type parameter restricts a search query to only retrieve a particular\n // type of resource. The value is a comma-separated list of resource types. The\n // default value is 'video,channel,playlist'. Acceptable values are: 'channel',\n // 'playlist', 'video'. (string)\n type: 'video',\n\n // The q parameter specifies the query term to search for. Your request can\n // also use the Boolean NOT (-) and OR (|) operators to exclude videos or to\n // find videos that are associated with one of several search terms. (string)\n q: opts.q || (opts.name + ' ' + opts.artistName)\n }\n\n sendRequest(url, params, onResponse)\n\n function onResponse (err, data) {\n if (err) return cb(err)\n let videos = data.items\n .map(item => {\n return {\n id: item.id.videoId,\n title: item.snippet.title,\n channelTitle: item.snippet.channelTitle\n }\n })\n\n if (!opts.q) {\n videos = videos\n .map((item, i) => {\n // Use YouTube's search rank as initial rank value (0-500)\n item.rank = item.ytRank = 500 - (i * 10)\n\n const title = item.title.toLowerCase()\n const channelTitle = item.channelTitle.toLowerCase()\n\n const artistName = opts.artistName.toLowerCase()\n\n // Promote \"official version\" videos (e.g. with \"(Official)\" in the title)\n if (OFFICIAL_REGEX.test(title)) item.rank += 7\n\n // Demote \"live version\" videos (e.g. with \"(Live)\" in the title)\n if (LIVE_REGEX.test(title)) item.rank -= 7\n\n // Demote \"full album\" videos (e.g. with \"(Full Album)\" in the title)\n if (FULL_ALBUM_REGEX.test(title)) item.rank -= 15\n\n // Promote videos from channels with the artist's name (e.g. \"Michael Jackson\" or\n // \"MichaelJackson\")\n if (channelTitle.includes(artistName)) item.rank += 15\n if (artistName.includes(' ') &&\n channelTitle.includes(artistName.replace(/ /g, ''))) item.rank += 15\n\n // Promote videos from a VEVO account, since it's likely official\n if (channelTitle.endsWith('vevo')) item.rank += 15\n\n // Promote videos from channels with \"official\" in the title\n if (channelTitle.includes('official')) item.rank += 7\n\n return item\n })\n .sort((a, b) => b.rank - a.rank)\n }\n\n const result = {\n meta: {\n query: opts\n },\n videos\n }\n\n cb(null, result)\n }\n}" ]
[ "0.7199131", "0.70443773", "0.6975768", "0.69152796", "0.6838443", "0.67857677", "0.6727161", "0.6698886", "0.6675401", "0.6667701", "0.66495323", "0.6588118", "0.6536126", "0.6533393", "0.6518241", "0.65137565", "0.6513169", "0.64575183", "0.6422255", "0.6392056", "0.63655055", "0.63553554", "0.63431066", "0.6337753", "0.63182586", "0.63155216", "0.6315505", "0.63051397", "0.62809587", "0.62796956", "0.62707424", "0.6270549", "0.6266577", "0.6247112", "0.62287605", "0.6227248", "0.6225969", "0.6205797", "0.61621785", "0.6127815", "0.6110114", "0.61079603", "0.6100998", "0.61004645", "0.6092369", "0.6086779", "0.60862595", "0.6082042", "0.605755", "0.6047509", "0.60447896", "0.6040008", "0.6030586", "0.6024835", "0.6016903", "0.6012422", "0.60104954", "0.5996462", "0.5987363", "0.5986119", "0.5981182", "0.59811544", "0.59805846", "0.59783417", "0.59770656", "0.5965007", "0.5960612", "0.59562856", "0.5944609", "0.5942277", "0.5940154", "0.59282494", "0.5916268", "0.5916227", "0.5912713", "0.5911274", "0.5911047", "0.5910272", "0.59094626", "0.59050566", "0.5892243", "0.5888829", "0.5883753", "0.58761865", "0.58745", "0.58695924", "0.58652186", "0.5861734", "0.58441323", "0.58441323", "0.5844018", "0.58363926", "0.58315706", "0.582394", "0.58233434", "0.5821065", "0.5815976", "0.58045095", "0.57996845", "0.5793779", "0.57888496" ]
0.0
-1
Renders the correct button for the payment screen depending on what kind of user is using the button (non registered, registered but not premium, registered and premium)
renderButton(planName) { if (this.props.user) { // If the user is already premium let them know! if (!isNil(this.props.user.plan)) return <button onClick={() => { this.props.pushAlert('info', 'Already Subscribed', 'You are already subscribed to this plan!'); ReactGA.modalview('/pricing#already-subscribed'); }} className="Plan-button common-UppercaseText common-Link--arrow"> Join free for 7 days </button>; else // Else show them the payment form return <button onClick={() => { this.setState({selectedPlan: this.state.plans[planName]}); ReactGA.modalview('/pricing#successful'); }} data-toggle="modal" data-target="#payment-modal" className="Plan-button common-Link--arrow"> Join free for 7 days </button> } // User is not signed in prompt them to signup return <button onClick={() => { this.props.history.push('/signup'); ReactGA.modalview('/pricing#signup'); }} className="Plan-button common-UppercaseText common-Link--arrow"> Join free for 7 days </button>; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function reviewButtonDisplay() {\n // Check user type\n console.log(\"isBusinessOwner()\", isBusinessOwner);\n if (isBusinessOwner == \"true\") {\n console.log(\"is a business owner\");\n hideElement(\"review-button\");\n } else {\n // Set saved ratings for the pop up and click open if it is a user \n // returning directly from auth\n displaySavedRatings(); \n }\n}", "renderConfirmalButton() {\n const { onArrivalConfirmed, showConfirmationButton } = this.props;\n const { destinationReached } = this.state;\n\n if (!showConfirmationButton || !destinationReached) {\n return null;\n }\n\n return this.renderButton('Confirm Arrival', onArrivalConfirmed);\n }", "function DealerCheck() {\n if (player2.isDealer) {\n return <a id=\"call-up-button\" onClick={setTrump} className=\"waves-effect waves btn\">I'll Pick it up</a>;\n } else return <a id=\"call-up-button\" onClick={setTrump} className=\"waves-effect waves btn\">You can pick it up</a>;\n}", "function renderButton() {\n gapi.signin2.render('signin2', {\n 'scope': 'profile email',\n 'width': 250,\n 'height': 40,\n 'longtitle': true,\n 'theme': 'dark',\n 'onsuccess': onSuccess,\n 'onfailure': onFailure\n });\n\n gapi.signin2.render('registrar-gmail', {\n 'scope': 'profile email',\n 'width': 250,\n 'height': 40,\n 'longtitle': true,\n 'theme': 'dark',\n 'onsuccess': onSuccess,\n 'onfailure': onFailure\n });\n}", "function paymentType(mofPayment){\n\tdocument.getElementById(\"termsDiv\").style.display=\"flex\";\n\ttype = mofPayment;\n\tif(document.getElementById(\"termsCheck\").checked != false){\n\t\tdocument.getElementById('confirmBtn').style.display='block';\n\t}\n\telse{\n\t\tdocument.getElementById('confirmBtn').style.display='none';\n\t}\n}", "renderButtons() {\n if(this.props.status === 'Upcoming') {\n return (\n <div>\n <Button variant=\"outline-danger\" onClick={this.handleShowCancelModal}>Cancelar</Button>\n </div>\n );\n }\n else if(this.props.status === 'Past') {\n return (\n <div>\n {this.props.hasReview ? \n <Button variant=\"outline-info\" disabled>Ya dejaste tu review</Button>\n :\n <Button variant=\"outline-success\" onClick={this.handleShowReviewModal}>Dejar Review</Button>\n }\n \n </div>\n );\n }\n }", "renderMembershipButton() {\n const { authUser } = this.props;\n // Admin or Voting Associate\n if (authUser && (authUser.is_member || authUser.is_admin)) return null;\n\n // Has already a membership proposal\n if (authUser && authUser.membership && authUser.membership.id) return null;\n\n return (\n <Link\n to=\"/app/proposal/upgrade-membership\"\n className=\"btn btn-primary-outline btn-fluid btn-icon\"\n >\n <Icon.Plus />\n New Proposal for Membership\n </Link>\n );\n }", "function displayPaymentInfo(paymentMethod) {\n if (paymentMethod == 'Credit Card') {\n document.querySelector('#credit-card').style.display = 'block';\n paypal.style.display = 'none';\n bitcoin.style.display = 'none';\n } else if (paymentMethod == 'PayPal') {\n document.querySelector('#credit-card').style.display = 'none';\n paypal.style.display = 'block';\n bitcoin.style.display = 'none';\n } else if (paymentMethod == 'Bitcoin') {\n document.querySelector('#credit-card').style.display = 'none';\n paypal.style.display = 'none';\n bitcoin.style.display = 'block';\n } else if (paymentMethod == 'Select Payment Method') {\n document.querySelector('#credit-card').style.display = 'none';\n paypal.style.display = 'none';\n bitcoin.style.display = 'none';\n }\n}", "showButtons(valutation, assignment) {\n\n let stateCurrentAssignment = '';\n //Set stateCurrentAssignment to the current state of the assignment\n this.state.assignments.forEach(assignment => {\n if (valutation.assignment_id === assignment.id) {\n stateCurrentAssignment = assignment.state;\n }\n })\n\n if (stateCurrentAssignment === 'Booked') {\n return (\n <div style={{ position: 'relative', right: '50px' }}>\n <CustomButton\n block\n bsStyle='success'\n onClick={\n () => {\n\n this.setState({\n operationToConfirm: 'Assegna incarico',\n selectedValutation: valutation,\n selectedAssignment: assignment,\n })\n\n this.setShowConfirm();\n\n\n }\n }\n >\n Assegna incarico\n </CustomButton>\n </div>\n )\n }\n else if (stateCurrentAssignment === 'Unassigned') {\n let showSendRequestButton = false;\n \n this.state.assignments.forEach(el => {\n \n if (el.id === assignment.id) {\n console.log('Ciao')\n if (el.student == null || el.student === '') {\n \n showSendRequestButton = true;\n }\n }\n })\n if (showSendRequestButton) {\n return (\n <div style={{ position: 'relative', right: '50px' }}>\n <CustomButton\n block\n bsStyle='success'\n onClick={\n () => {\n\n this.setState({\n operationToConfirm: 'Invia richiesta',\n selectedValutation: valutation,\n selectedAssignment: assignment,\n })\n\n this.setShowConfirm();\n\n\n }\n }\n\n >\n Invia richiesta\n </CustomButton>\n </div>\n )\n }\n else {\n return (\n <div style={{ position: 'relative', right: '50px' }}>\n <CustomButton\n block\n bsStyle='warning'\n disabled\n >\n Nessun operazione\n </CustomButton>\n </div>\n )\n }\n\n }\n else {\n return (\n <div style={{ position: 'relative', right: '50px' }}>\n <CustomButton\n block\n bsStyle='warning'\n disabled\n >\n Nessun operazione\n </CustomButton>\n </div>\n )\n }\n }", "render() {\n return (\n <div\n className=\"card\"\n onClick={() => this.props.clickHandler(this.props.bill)}\n >\n <div className=\"card-body\">\n <h2 className=\"card-company-name\">{this.props.bill.company_name}</h2>\n <h4 className=\"card-amount\">Amount Due:</h4>\n <p>${this.props.bill.amount}</p>\n <h4 className=\"card-amount\">Payment Due Date: </h4>\n <p>{this.props.bill.payment_due}</p>\n <h4 className=\"card-category\">Category: </h4>\n <p>{this.props.bill.category}</p>\n {this.props.isDefault ? null : (\n <button onClick={() => this.props.handlePaid(this.props.bill)}>\n {this.props.bill.paid ? \"Paid\" : \"Pay This Week\"}\n </button>\n )}\n <hr />\n </div>\n </div>\n );\n }", "generateSubmitButton(){\n var validity = this.state.keyValid[this.state.currKey];\n if (this.state.roundTwo) {\n if (this.state.upload !== null || this.state.processingFetch || this.state.md5Progress !== null) {\n return <Button bsStyle=\"success\" disabled><i className=\"icon icon-spin icon-circle-o-notch\"/></Button>;\n } else {\n return <Button bsStyle=\"success\" onClick={this.realPostNewContext}>Submit</Button>;\n }\n } else if (validity == 3) {\n if(this.state.processingFetch){\n return <Button bsStyle=\"success\" disabled><i className=\"icon icon-spin icon-circle-o-notch\"/></Button>;\n }else{\n return <Button bsStyle=\"success\" onClick={this.realPostNewContext}>Submit</Button>;\n }\n } else if (validity == 4) {\n return <Button bsStyle=\"success\" disabled>Submitted</Button>;\n } else {\n return <Button bsStyle=\"success\" disabled>Submit</Button>;\n }\n }", "function paymentMethod() {\n const creditCardPayment = document.getElementById(\"credit-card\");\n const paypalPayment = document.getElementById(\"paypal\");\n const bitcoinPayment = document.getElementById(\"bitcoin\");\n\n //sets payment type to credit card on page load\n paymentMenu.children[1].selected = true;\n paypalPayment.style.display = \"none\";\n bitcoinPayment.style.display = \"none\";\n\n paymentMenu.addEventListener(\"change\", (e) => {\n const clickedPayment = e.target.value;\n \n if (clickedPayment === \"paypal\") {\n creditCardPayment.style.display = \"none\";\n paypalPayment.style.display = \"\";\n bitcoinPayment.style.display = \"none\";\n } else if (clickedPayment === \"bitcoin\") {\n creditCardPayment.style.display = \"none\";\n paypalPayment.style.display = \"none\";\n bitcoinPayment.style.display = \"\";\n } else {\n creditCardPayment.style.display = \"\";\n paypalPayment.style.display = \"none\";\n bitcoinPayment.style.display = \"none\";\n }\n }); \n}", "renderRsvp(){\n if(this.props.party.host.email == this.props.currentUser.email){\n return( <div></div>)\n }\n if(this.props.party.attending.map((guest, key) => {\n return guest.email}).indexOf(this.props.currentUser.email) == -1) {\n return (\n <div>\n <p><span className=\"glyphicon glyphicon-envelope\"></span> Attending:</p>\n <button className=\"btn btn-default rsvp-buttons\" onClick={this.rsvpTrue}>Yes</button>\n <button className=\"btn btn-default rsvp-buttons\" onClick={this.rsvpFalse}>No</button>\n </div>\n )\n } else {\n return (\n <div>\n <p><span className=\"glyphicon glyphicon-envelope\"></span> Still Attending?</p>\n <button className=\"btn btn-default\" onClick={this.rsvpFalse}>No</button>\n </div>\n )\n }\n }", "function _formatButton(state, activeReservation) {\n var button = {};\n if (state === 'available') {\n button.unavailable = false;\n button.class = 'checkout';\n return button;\n } else if (activeReservation) {\n if (vm.isAdmin){\n button.class = 'checkin';\n } else { //User is not admin\n button.unavailable = true;\n console.log(vm.deviceData['active_reservations'][0]);\n button.class = 'checkin';\n if(vm.deviceData['active_reservations'][0].borrower.name.first === 'You'){\n button.unavailable = false;\n }\n }\n return button;\n } else {\n return {\n unavailable: true,\n class: 'checkout'\n };\n }\n }", "render() {\n\n const showButton = this.props.buttonRequested;\n const error = this.state.error;\n const disabled =\n !this.state.creditCardFormLoaded ||\n this.state.sendingInfoToServer;\n const sendingInfoToServer = this.state.sendingInfoToServer;\n\n // used to check if a prop has been passed down to show the submit button\n const checkButton = () => {\n if (showButton === true)\n return (\n <div className=\"field-cc__container\">\n <button onClick={this.props.onSubmit ? this.props.onSubmit : this.submitCreditCard} disabled={disabled} className={sendingInfoToServer ? 'loading' : ''}>{this.props.buttonText ? this.props.buttonText : 'Store my CC info safely!'}</button>\n </div>\n )\n }\n\n return (\n <div className=\"credit-card-form__wrapper\">\n\n <div className=\"credit-card-form__container\">\n\n <div className=\"field-cc__wrapper--smaller-fields\">\n <HostedField fieldType=\"Number\" errorMessage=\"Uh-oh! Looks like your credit card can only be accepted on Mars.\" />\n <HostedField fieldType=\"Cvv\" />\n </div>\n <div className=\"field-cc__wrapper--smaller-fields\">\n <p>Expiry date</p>\n <HostedField fieldType=\"Expiration-Month\" errorMessage=\"Please enter a valid expiry date\" />\n <HostedField fieldType=\"Expiration-Year\" errorMessage=\"Please enter a valid expiry date\" />\n </div>\n <div className=\"field-cc__container\">\n <input className=\"field-cc field-cc--creditCard-Name\" type=\"text\" name=\"creditCardName\" placeholder=\"Your Name\" />\n </div>\n \n {error}\n\n {checkButton()}\n\n </div>\n </div>\n )\n }", "function onPaymentTypeChange(e) {\n\n let exMonth = docDotQS(\".expiration-box\");\n let exYear = docDotQS(\".credit-card-box\");\n let paypalbox = docDotQS(\"#paypal\");\n let bitcoinbox = docDotQS(\"#bitcoin\");\n\n // If credit card chosen\n if (e.target.value === \"credit-card\") {\n exMonth.style.display = \"\";\n exYear.style.display = \"\";\n paypalbox.style.display = \"none\";\n bitcoinbox.style.display = \"none\";\n\n } else {\n\n exMonth.style.display = \"none\";\n exYear.style.display = \"none\";\n \n // If paypal chosen\n if (e.target.value === \"paypal\") {\n paypalbox.style.display = \"\";\n bitcoinbox.style.display = \"none\";\n } else {\n // If bitcoin chosen\n paypalbox.style.display = \"none\";\n bitcoinbox.style.display = \"\"\n }\n }\n}", "_renderVoteBtn(candidate) {\n if (this.props.data.session) { // if logged\n if (!this.state.votedFor) { // if not voted yet\n return (<div>\n <button className=\"vote-btn\" onClick={(e) => this._MakeVote(candidate)}>\n <span className=\"fa fa-thumbs-up\"></span>\n </button>\n </div>)\n } else { // if alredy voted\n return (<button className=\"vote-btn\">\n <span className=\"fa fa-thumbs-up\"></span>\n </button>)\n }\n }\n return false;\n }", "renderButton() {\n const { onDecrement, onIncrement, joined, fortNiteId } = this.props;\n\n if (fortNiteId === '') {\n return <input className=\"PrimaryButton\" type=\"button\" name=\"join\" value=\"JOIN\"></input>\n } else if (joined) {\n return <input className=\"SecondaryButton\" type=\"button\" name=\"join\" value=\"LEAVE\" onClick={onDecrement}></input>\n }\n return <input className=\"PrimaryButton\" type=\"button\" name=\"join\" value=\"JOIN\" onClick={onIncrement}></input>\n }", "function gotoPayment() {\n let errorMsg = document.getElementById(\"checkoutMsg\");\n let cartItem = document.getElementsByClassName(\"order-details\")[0];\n let loginBtn = '<button onclick=\"goToLogin()\">Login</button>';\n if (localStorage.getItem(\"customerLogged\")) {\n if (typeof cartItem != \"undefined\" && cartItem != null) {\n location.href = \"payment.php\";\n } else {\n errorMsg.innerHTML = \"Add items first\";\n errorMsg.style.color = \"red\";\n \n }\n } else {\n errorMsg.innerHTML = \"Must be logged first\";\n localStorage.removeItem('cartName');\n errorMsg.style.color = \"red\";\n errorMsg.innerHTML += loginBtn;\n }\n}", "renderAuthButton() {\n if (this.props.isSignedIn === null) {\n return null;\n } else if (this.props.isSignedIn) {\n return (\n <Button style={this.buttonStyles} onClick={this.onSignOutClick}>\n <Icon className=\"google\" />\n Sign Out\n </Button>\n );\n } else {\n return (\n <Button\n className=\"ui button\"\n style={this.buttonStyles}\n onClick={this.onSignInClick}\n >\n <Icon className=\"google\" />\n Sign in with Google\n </Button>\n );\n }\n }", "function prepareButtons(conversions) {\n\t$.each(conversions,function(currency,conversion) {\n\t\tconversion['buttonTexts']=buttonAmounts(conversion['rate']);\n\t});\n\t$('#buttons').data('conversions',conversions); // store conversions\n\n\t// direct donation button:\n\t$('#buttons button.directDonation').click(function() {\n\t\t$('#proceedCurrency').html($('#currency').val());\n\t\t$('#proceedAmount').html($(this).val());\n\t\t$('#proceedPaypalButton').attr('href',\n\t\t\tgenerateUrl('PayPal',$('#currency').val(),$(this).val())\n\t\t);\n\t\t$('#proceedCreditcardButton').attr('href',\n\t\t\tgenerateUrl('payments.wikimedia.org',$('#currency').val(),$(this).val())\n\t\t);\n\t\t$.mobile.changePage('#proceedPage', 'slideup', true, true);\n\t});\n\n\t// \"free amount...\" button:\n\t$('#freeAmountButton').click(function() {\n\t\t$('#freeAmountCurrency')\n\t\t\t.html($('#currency').val());\n\t\t$('#freeAmountAmount')\n\t\t\t.attr('placeholder',$('#currency').val())\n\t\t\t.val('');\n\t\t$.mobile.changePage('#freeAmoutPage', 'slideup', true, true);\n\t});\n\t// Donate button in free amount popup:\n\t$('#freeAmountPaypalButton, #freeAmountCreditcardButton')\n\t\t.click(function(event) {\n\t\tvar amount = $('#freeAmountAmount').val();\n\t\tamount = parseInt(amount,10);\n\t\tif (!amount || amount<1) { // click not possible\n\t\t\tamount='';\n\t\t\tevent.preventDefault();\n\t\t} else { // forward user to payment gateway\n\t\t\tvar url = generateUrl('PayPal',$('#currency').val(),amount);\n\t\t\t$('#freeAmountPaypalButton').attr('href',url);\n\t\t\turl = generateUrl(\n\t\t\t\t'payments.wikimedia.org',\n\t\t\t\t$('#currency').val(),\n\t\t\t\tamount);\n\t\t\t$('#freeAmountCreditcardButton').attr('href',url);\n\t\t}\n\t\t$('#freeAmountAmount').val(amount);\n\t});\n} // prepareButtons", "function updatePaymentMethod()\n{\n let paymentMethod = paymentSelector.value;\n if(paymentMethod === 'select method')\n {\n paymentMethod = 'credit-card';\n document.querySelector('#payment option[value=\"credit card\"]').selected = true;\n document.querySelector('#payment option[value=\"select method\"]').style.display = 'none'; \n }\n\n if(paymentMethod === 'credit card')\n {\n paymentMethod = 'credit-card';\n }\n\n document.querySelector('#credit-card').style.display = 'none';\n document.querySelector('#paypal').style.display = 'none';\n document.querySelector('#bitcoin').style.display = 'none';\n document.querySelector(`#${paymentMethod}`).style.display = 'block';\n}", "checkNewUserButton(){\n if(this.props.isNewUser===true){\n return <Button id=\"signupButton\" kind='primary' style={{ padding: \"20px\" ,fontSize:\"20px\"}} onClick={()=>this.signUp()}>Sign Up</Button>\n }\n else{\n return <Button className=\"loginb\" id=\"loginButton\" kind='primary' style={{ padding: \"20px\" ,fontSize:\"20px\"}} onClick={()=>this.logIn()}>Log In</Button>\n }\n }", "render() {\n const { expert={}, status='' } = this.props.expert\n const approved = status === 'approved'\n const button = (\n <Button onClick={this.changeStatus} color={approved ? 'danger' : 'success' } size=\"sm\">\n {approved ? 'Reject' : 'Approve' }\n </Button>\n )\n return (\n <div className=\"d-flex align-items-center\">\n <div>{`${expert.firstname} ${expert.lastname}`}</div>\n <Badge color={approved ? 'success' : 'danger'} className=\"ml-2 mr-auto\">{status}</Badge>\n {this.props.user.data.email && button}\n </div>\n )\n }", "generateValidationButton(){\n var validity = this.state.keyValid[this.state.currKey];\n // when roundTwo, replace the validation button with a Skip\n // button that completes the submission process for currKey\n if (this.state.roundTwo){\n if(this.state.upload === null && this.state.md5Progress === null){\n return(\n <Button bsStyle=\"warning\" onClick={function(e){\n e.preventDefault();\n this.finishRoundTwo();\n }.bind(this)}>Skip</Button>\n );\n }else{\n return <Button bsStyle=\"warning\" disabled>Skip</Button>;\n }\n } else if(validity === 3 || validity === 4){\n return(\n <Button bsStyle=\"info\" disabled>Validated</Button>\n );\n } else if(validity === 2){\n if (this.state.processingFetch) {\n return <Button bsStyle=\"danger\" disabled><i className=\"icon icon-spin icon-circle-o-notch\"/></Button>;\n } else {\n return <Button bsStyle=\"danger\" onClick={this.testPostNewContext}>Validate</Button>;\n }\n } else if (validity === 1){\n if (this.state.processingFetch) {\n return <Button bsStyle=\"info\" disabled><i className=\"icon icon-spin icon-circle-o-notch\"/></Button>;\n } else {\n return <Button bsStyle=\"info\" onClick={this.testPostNewContext}>Validate</Button>;\n }\n } else {\n return <Button bsStyle=\"info\" disabled>Validate</Button>;\n }\n }", "render() {\n const { isPaying, paymentMethod } = this.state;\n const {\n merchant_reference,\n amount,\n currency,\n product_name,\n user_id,\n paymentMethods\n } = this.props.url.query;\n\n return (\n <Page>\n <div className=\"row\">\n <div className=\"col-sm-6 col-sm-8 col-sm-offset-3 col-md-offset-2\">\n <LatipayLogo />\n <h2>\n {CURRENCIES_CODE_SIGN[currency]}\n {numeral(amount).format('0,0.00')}\n <small>{currency}</small>\n </h2>\n\n <div className=\"page-header lat-page-header\">\n <h5>请选择支付方式</h5>\n </div>\n <div className=\"lat-invoice-pay-methods\">\n {paymentMethods.map(pm => (\n <label\n key={pm}\n className=\"lat-invoce-pay-method\"\n htmlFor={`pay-${pm}`}\n >\n <input\n id={`pay-${pm}`}\n type=\"radio\"\n name=\"pay-method\"\n onClick={() => this.setPaymentMethod(pm)}\n />\n <img src={`/static/pay-${pm}.png`} alt={pm} />\n </label>\n ))}\n\n <style jsx>{`\n .lat-invoice-pay-methods {\n display: flex;\n flex-wrap: wrap;\n }\n .lat-invoce-pay-method {\n width: 25%;\n min-width: 150px;\n }\n .lat-invoce-pay-method img {\n width: 100px;\n margin: 1em;\n }\n `}</style>\n </div>\n {paymentMethod && (\n <button\n className=\"btn btn-success\"\n type=\"submit\"\n onClick={this.submit}\n disabled={isPaying}\n >\n &nbsp; &nbsp; &nbsp;PAY &nbsp; &nbsp; &nbsp;\n </button>\n )}\n <div className=\"page-header lat-page-header\">\n <h5>订单信息</h5>\n </div>\n\n <div className=\"lat-table\">\n <div className=\"table-responsive\">\n <table className=\"table table-hover \">\n <tbody>\n <tr>\n <td>产品信息</td>\n <td>{product_name}</td>\n </tr>\n <tr>\n <td>订单编号</td>\n <td>{merchant_reference}</td>\n </tr>\n <tr>\n <td>订单创建人</td>\n <td>{user_id}</td>\n </tr>\n </tbody>\n </table>\n <style jsx>{`\n td:first-of-type {\n width: 30%;\n }\n .attachment {\n text-decoration: underline;\n }\n `}</style>\n </div>\n </div>\n </div>\n </div>\n </Page>\n );\n }", "function ReturningCustomer() {\n document.getElementById('ReturningCustomer').style.display = 'block';\n document.getElementById('ReturningButton').style.display = 'none'; \n document.getElementById('RegisterButton').style.display = 'none'; \n}", "checkIfJustPaid() {\n\t\tlet actionString = window.location.href;\n\t\tif(actionString.indexOf('#processPayment') !== -1){\n\t\t\t// redirected back after payment \n\t\t\t// get query string parameter\n\t\t\tlet queryString = window.location.search;\t// ?id=40C477...sbg-vm-tx01&resourcePath=%2Fv1%2Fcheckouts%2F40...\n\t\t\t// check if resourcePath exists\n\t\t\tlet resourcePathPos = queryString.indexOf('resourcePath=');\n\t\t\tif(resourcePathPos != -1){\n\t\t\t\tlet resourceParam = queryString.substring(resourcePathPos);\n\t\t\t\t// just checking & trimming, if there is any other parameter at end\n\t\t\t\tif(resourceParam.indexOf('&') !== -1){\n\t\t\t\t\tresourceParam = queryString.substring(resourcePathPos, resourceParam.indexOf('&'));\n\t\t\t\t}\n\t\t\t\tlet [resourceKey, resourcePath] = resourceParam.split(\"=\");\t\t// destructuring param name, value\t\t\n\t\t\t\t// if a valid resourcePath available\n\t\t\t\tif(resourcePath.length >0){\n\t\t\t\t\t// activating Process breadcrumb & screen \n\t\t\t\t\tthis.donationActivity.goNextBreadCrumb(3).goNextScreen(3);\n\t\t\t\t\n\t\t\t\t\t// get payment status\n\t\t\t\t\tthis.donation.getDonationStatus(resourcePath);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Not redirected after a payment, show first page\n\t\t// checking if Donated before 1 hour\n\t\tlet activateFirstScrn = true;\n\t\tlet lastPaymentRespStr = localStorage.getItem('lastPaymentResp');\n\t\tif(lastPaymentRespStr){\n\t\t\tlet lastPaymentRespObj = JSON.parse(lastPaymentRespStr);\n\t\t\tlet timeDiffDetails = this.donationActivity.getTimeDiffDetails(lastPaymentRespObj.timestamp);\n\t\t\tif(!timeDiffDetails.donateAgain) {\n\t\t\t\t// activating Last(Thank You) breadcrumb & screen \n\t\t\t\tthis.donationActivity.goNextBreadCrumb(4).goNextScreen(4);\n\t\t\t\tthis.donationActivity.showThankYouText().showHistoryBlock();\n\t\t\t\tactivateFirstScrn = false;\n\t\t\t}\n\t\t}\n\t\t\n\t\t// activating First breadcrumb & screen \n\t\tif(activateFirstScrn){\n\t\t\tthis.donationActivity.goNextBreadCrumb(1).goNextScreen(1);\n\t\t}\n\t\t\n\t\treturn true;\n\t}", "function Get_button(props){\n\n if(props.status == \"available\") return( <Button size=\"mini\" positive>&nbsp;&nbsp;&nbsp;available&nbsp;&nbsp;&nbsp;</Button>);\n else return (<Button size=\"mini\" negative>unavailable</Button>);\n}", "renderButton(course) {\n if (this.subscription(course.id)) {\n return <NavLink to={`/courses/${course.id}`}><button>Go to {course.title}</button></NavLink>\n } else if (this.props.user) {\n return <button class=\"subscribe\" onClick={() => this.props.createSubscription(this.props.user.id, course.id)}>Subscribe</button>\n } else {\n return this.loggedOutButtons()\n }\n }", "render () {\n let buttonText\n let wrapper\n const { exists, available, quantity = true, checkoutUrl} = this.props\n\n if (exists && available) {\n buttonText = 'Buy Now'\n } else if (exists) {\n buttonText = 'Out of Stock'\n } else {\n buttonText = 'Unavailable'\n }\n\n const classes = classnames('btn', {\n 'btn-success': exists && available,\n 'disabled btn-default': !exists || !available\n })\n\n const buyNowButton = (\n <button className={classes} onClick={this.onBuyNow} href={checkoutUrl}>{buttonText}</button>\n )\n\n const addToCartButton = (\n <button className=\"btn btn-default\"\n data-tip=\"Add To Cart is not implemented, but is here to demonstrate the use of functional handler using Fake Cart\"\n onClick={this.onAddCart}>\n Add To Cart\n </button>\n )\n\n if (quantity) {\n wrapper = (\n <div className=\"AddToCart\">\n <div className=\"input-group\">\n <input type=\"number\"\n value={this.props.quantity}\n className=\"form-control\" \n placeholder=\"Enter quantity here\" \n onChange={this.onChangeQuantity}\n />\n <span className=\"input-group-btn\">\n {buyNowButton}\n {addToCartButton}\n </span>\n </div>\n </div>\n )\n } else {\n wrapper = (\n <div className=\"AddToCart\">\n {buyNowButton}\n </div>\n )\n }\n\n return wrapper\n }", "function updateSubmitButtonText(){\n if( EVENT.type === 'free' ){\n $form.find('[type=\"submit\"]').val('Confirm');\n }\n else{\n $form.find('[type=\"submit\"]').val('Pay $' + calcAmount());\n }\n }", "function updateSubmitButtonText(){\n if( EVENT.type === 'free' ){\n $form.find('[type=\"submit\"]').val('Confirm');\n }\n else{\n $form.find('[type=\"submit\"]').val('Pay $' + calcAmount());\n }\n }", "function payment (input1, input2, input3, input4){\n let clickedPayment = paymentType.options[paymentType.selectedIndex];\n if (clickedPayment.value == input1){\n input2.style.display = 'block';\n input3.style.display = 'none';\n input4.style.display = 'none';\n }\n}", "function paymentButtonDisabledEnabled()\n {\n $('.paymentButtonDisalbed').hide();\n $('.paymentButtonEnable').hide();\n if(totalOrderItem() > 0)\n {\n $('.paymentButtonDisalbed').hide();\n $('.paymentButtonEnable').show();\n }else{\n $('.paymentButtonEnable').hide();\n $('.paymentButtonDisalbed').show();\n }\n }", "chooseButton(){\n let {resetGame} = this.props\n let button = (this.props.reduxState.status.every(s=> s===gStatus.HEALTHY || s===gStatus.THIRSTY ||\n s===gStatus.HUNGRY || s===gStatus.STARVING ||s===gStatus.DEHYDRATED))?\n (<button key={'cont-btn'} data-test=\"continue-button\" onClick={()=> this.props.changePage('gameplay')}>Continue</button>): <button key={'reset-btn'} onClick={resetGame}>Start Over</button>\n return button;\n }", "function btnHandling() {\n // On same pages these buttons are not defined\n try {\n const userID = container.dataset.profile;\n const currentProfileID = document.querySelector(\".post-actions\").dataset.owner;\n\n if(userID !== currentProfileID) {\n const header = document.querySelector(\".posts-header\");\n const topBtn = document.querySelector(\".btn-follow.top\");\n const bottomBtn = document.querySelector(\".btn-follow.bottom\");\n const position = bottomBtn.getBoundingClientRect().bottom;\n const height = header.offsetHeight;\n\n if(position < height) {\n topBtn.classList.add(\"active\");\n } else {\n topBtn.classList.remove(\"active\");\n }\n }\n } catch{return}\n}", "renderElement(status, id) {\n if(this.state.isOwner) {\n if(status===\"p\" || status===\"P\") {\n return <div>\n <p className=\"card-title ml-4\">{\"Booking Status: Accepted/In Progress\"}</p>\n <div className=\"container\">\n <div className=\"row\">\n <div className=\"col-sm\">\n <button type=\"submit\" data-param={JSON.stringify({status:\"C\", id:id})} onClick={this.acceptBooking} className=\"btn btn-primary\" >\n Complete\n </button>\n </div>\n <div className=\"col-sm\">\n <button type=\"submit\" data-param={JSON.stringify({status:\"X\", id:id})} onClick={this.acceptBooking} className=\"btn btn-primary\" >\n Reject\n </button>\n </div>\n </div>\n </div>\n </div>;\n } else if(status===\"r\" || status===\"R\") {\n return <div>\n <p className=\"card-title ml-4\">{\"Booking Status: Accepted/In Progress\"}</p>\n <div className=\"container\">\n <div className=\"row\">\n <div className=\"col-sm\">\n <button type=\"submit\" data-param={JSON.stringify({status:\"P\", id:id})} onClick={this.acceptBooking} className=\"btn btn-primary\" >\n Confirm\n </button>\n </div>\n <div className=\"col-sm\">\n <button type=\"submit\" data-param={JSON.stringify({status:\"X\", id:id})} onClick={this.acceptBooking} className=\"btn btn-primary\" >\n Reject\n </button>\n </div>\n </div>\n </div>\n </div>;\n } else if(status===\"x\" || status===\"X\") {\n return <p className=\"card-title ml-4\">{\"Booking Status: Cancelled/Rejected\"}</p>;\n } else {\n return <p className=\"card-title ml-4\">{\"Booking Status: Completed\"}</p>;\n } \n } else {\n if(status===\"p\" || status===\"P\") {\n return <div>\n <p className=\"card-title ml-4\">{\"Booking Status: Accepted/In Progress\"}</p>\n <button type=\"submit\" data-param={JSON.stringify({status:\"C\", id:id})} onClick={this.acceptBooking} className=\"btn btn-primary\" >\n Complete\n </button>\n </div>;\n } else if(status===\"r\" || status===\"R\") {\n return <div>\n <p className=\"card-title ml-4\">{\"Booking Status: Accepted/In Progress\"}</p>\n <button type=\"submit\" data-param={JSON.stringify({status:\"X\", id:id})} onClick={this.acceptBooking} className=\"btn btn-primary\" >\n Cancel Request\n </button>\n </div>;\n } else if(status===\"x\" || status===\"X\") {\n return <p className=\"card-title ml-4\">{\"Booking Status: Cancelled/Rejected\"}</p>;\n } else {\n return <p className=\"card-title ml-4\">{\"Booking Status: Completed\"}</p>;\n } \n }\n }", "function displayButtonPayer(){\n var montantTotal = ($(\"#panierTotal\").text());\n if( montantTotal > 0){\n $(\"#panierBoutonPayer\").show();\n }else{\n $(\"#panierBoutonPayer\").hide();\n }\n}", "function policyButtonClick(e) {\n for (let i = 0; i < totalPolicyButtons.length; i++) {\n totalPolicyText[i].style.display = \"none\"\n }\n for (let i = 0; i < totalPolicyButtons.length; i++)\n if(totalPolicyButtons[i].classList.contains(\"active\")) {\n totalPolicyText[i].style.display = \"block\"\n }\n }", "function displayPaymentDetails(){\n if ($(\"#payment\").val() === \"credit card\") {creditCardPayment.show()}\n else creditCardPayment.hide();\n if ($(\"#payment\").val() === \"paypal\") {payPalPayment.show()}\n else payPalPayment.hide();\n if ($(\"#payment\").val() === \"bitcoin\") {bitcoinPayment.show()}\n else bitcoinPayment.hide();\n}", "displayReportButton() {\n let returnButton = null;\n\n if (this.state.button_flag == \"add\")\n returnButton = <button\n type=\"button\"\n className=\"btn btn-success btn-add-to-report mt-4\"\n title=\"Add to priority report\"\n onClick={this.handleAddToReportClick} disabled={this.state.priority_value != \"NA\" ? \"\" : \"disabled\"}>\n <FaPlus />\n </button>\n else if (this.state.button_flag == \"remove\")\n returnButton = <Fragment>\n {this.handleEditModeButtons()}\n <button\n type=\"button\"\n className=\"btn btn-success btn-add-to-report mt-4\"\n title=\"Remove from priority report\"\n onClick={this.handleRemoveFromReportClick}>\n <FaTimes />\n </button>\n </Fragment>\n\n return returnButton;\n }", "function CheckPaid(){\n if (store.state.generalData){\n // redirect to account page if the user has not paid, and they are not super\n if (store.state.superUser != true && store.state.paidMember == false && store.state.currentPage != 'account'){\n store.commit('updatePage', 'account')\n app.$toast.error(\"Please submit payment.\", {icon: 'warning'});\n return redirect('/account')\n }\n }\n }", "function showButtons() {\n // when users are not connected, we want start game button disabled\n // document.getElementById('start-game').style.display = 'inline';\n\n document.getElementById('button-invite').style.display = 'inline';\n // document.getElementById('button-preview').style.display = 'inline';\n document.getElementById('grab-username').style.display = 'inline';\n document.getElementById('username').style.display = 'inline';\n document.getElementById('invite-to').style.display = 'inline';\n\n // document.getElementById('end-call').style.display = 'none';\n\n // ensure that local media removes on firefox\n $('#local-media > video').remove();\n }", "function renderButton() {\n gapi.signin2.render('my-signin2', {\n 'scope': 'profile',\n 'width': 240,\n 'height': 50,\n 'longtitle': true,\n 'theme': 'dark',\n 'onsuccess': onSuccess,\n 'onfailure': onFailure\n });\n}", "async initPaymentRequestButton() {\n const { buttonTheme: theme, buttonType: type, canMakePayment, paymentRequest } = this;\n if (!canMakePayment) return;\n const computedStyle = window.ShadyCSS ? undefined : getComputedStyle(this);\n const propertyName = '--stripe-payment-request-button-height';\n const height = this.getCSSCustomPropertyValue(propertyName, computedStyle) || '40px';\n const style = { paymentRequestButton: { height, theme, type } };\n const options = { paymentRequest, style };\n const element = this.elements.create('paymentRequestButton', options);\n await this.set({ element });\n }", "isActivate(e){\n\t\tif(this.state.user.activate == 0){\n\t\treturn(\n\t\t\t<div>\n\t\t\t\t<span className=\"mr-20\">\n\t\t\t\t\t<button type=\"button\" className=\"Confirm_Button\" onClick={this.rejectPerson}> Reject </button>\n\t\t\t\t</span>\n\t\t\t\t<button type=\"button\" className=\"Confirm_Button\" onClick={this.AddPerson}> Confirm </button>\n\t\t\t</div> \n\t\t);\n\t\t}else{\n\t\t\tif (this.state.user.id == this.props.auth_user.id){\n\t\t\treturn;\n\t\t\t}\n\t\treturn <button type=\"button\" className=\"AddPositionButton\" onClick={this.handleShowRecommend}> Recommend</button> ;\n\t\t}\n\t}", "function bookingButtonHandler(button) {\n if (button == 'confirmButton') {\n document.getElementById('firstPage').style.display = 'none';\n document.getElementById('booking-content').style.display = 'none';\n document.getElementById('enjoyTrip').style.display = 'block';\n\n }\n else if (button == 'cancelButton') {\n document.getElementById('firstPage').style.display = 'block';\n document.getElementById('booking-content').style.display = 'none';\n }\n}", "function Payment () {\n return (\n <div class='payment-page-container'>\n <h1 class='secure'><span class=\"icomoon-lock align-items-center pr-3\"></span><img class='lock' src={Lock}/>Secure Payment</h1>\n <div class='payment-page'>\n \n <div class='cart'>\n <h1 class='cart-title'>Your cart</h1>\n </div>\n <div>\n <div class='summary'>\n <h1>Summary</h1>\n <h3>Total</h3>\n \n <a class='href' href='https://www.paypal.com/paypalme/tenniscoachesofnyc'>\n <button class='stripe-checkout'>Proceed to checkout</button>\n <h4 class='href'>-OR-</h4>\n <a href='https://www.paypal.com/paypalme/tenniscoachesofnyc'>\n <button class='paypal-checkout' >Checkout with <table border=\"0\" cellpadding=\"10\" cellspacing=\"0\" align=\"center\"><tr><td align=\"center\"></td></tr><tr><td align=\"center\"><a href=\"https://www.paypal.com/paypalme/tenniscoachesofnyc\" title=\"How PayPal Works\" onclick=\"javascript:window.open('https://www.paypal.com/paypalme/tenniscoachesofnyc','WIPaypal','toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=1060, height=700'); return false;\"><img src=\"https://www.paypalobjects.com/webstatic/mktg/logo/pp_cc_mark_37x23.jpg\" border=\"0\" alt=\"PayPal Logo\" /></a></td></tr></table></button></a></a>\n </div>\n {/* <a target=\"_blank\" rel=\"noopener noreferrer\" href='http://paypal.me/tenniscoachesofnyc'><img src=\"https://www.paypalobjects.com/webstatic/en_US/i/buttons/checkout-logo-large.png\" alt=\"Check out with PayPal\" /></a>\n <h2 class='or'>Or:</h2>\n <a target=\"_blank\" rel=\"noopener noreferrer\" href='https://venmo.com/Artemie-Amari'><img class='venmo' src={Venmo}/></a> */}\n {/* <div class='accepted'>\n <h3>Accepted Payment Methods</h3>\n </div> */}\n </div>\n </div>\n </div>\n );\n }", "getSubmitButton() {\n if(this.canSubmit()) {\n return (\n <div className=\"row\">\n <div className=\"submitBtn text-center col-md-12\">\n <input className=\"btn btn-lg btn-primary\" type=\"submit\" value=\"Order\" />\n </div>\n </div>\n );\n } else {\n return (\n <div>\n <div className=\"row\">\n <div className=\"submitBtn text-center col-md-12\">\n <input disabled=\"true\" className=\"btn btn-secondary btn-lg btn-disabled\" type=\"submit\" value=\"Order\" />\n </div>\n </div>\n <div className=\"row text-center\">\n <span className=\"formErrorText\">Cannot proceed; some fields are invalid - please review your info</span>\n </div>\n </div>\n );\n }\n\n }", "function renderMissionButton(mission, rank) {\n let type = mission.Condition.ConditionType;\n let buttonClass = \"\";\n \n if (!missionData.Current.Remaining.includes(mission) && !missionData.Completed.Remaining.includes(mission)) {\n buttonClass = \"disabled \";\n }\n \n let buttonOutlineStyle = (rank == \"Completed\") ? \"btn\" : \"btn-outline\";\n \n let buttonDescription = \"\";\n if (rank == \"Completed\") {\n buttonDescription = \"Uncomplete mission\"\n } else if (rank == \"Current\") {\n buttonDescription = \"Complete mission\"\n }\n \n if (type == \"ResourcesSpentSinceSubscription\" || type == \"ResearchersUpgradedSinceSubscription\") {\n buttonClass += `${buttonOutlineStyle}-danger`;\n } else if (type == \"ResearcherCardsEarnedSinceSubscription\") {\n buttonClass += `${buttonOutlineStyle}-success`;\n } else {\n buttonClass += `${buttonOutlineStyle}-secondary`;\n }\n \n let infoClass = hasScriptedReward(mission) ? \"scriptedRewardInfo\" : \"\"; \n \n return `<button class=\"btn ${buttonClass}\" onclick=\"clickMission('${mission.Id}')\" title=\"${buttonDescription}\">${describeMission(mission)}</button><a href=\"#\" class=\"btn btn-link infoButton ${infoClass}\" data-toggle=\"modal\" data-target=\"#infoPopup\" data-mission=\"${mission.Id}\" title=\"Click for mission info/calc\">&#9432;</a>`;\n}", "function selectPaymentMethod() {\n paymentMethod = $(this).text();\n chosePaymentMethod = true;\n $(\"#paymentMethodMenuButton\").text(paymentMethod);\n if (paymentMethod == \"Card\") {\n $(\"#selectCardMenu\").show();\n } else {\n $(\"#selectCardMenu\").hide();\n }\n}", "function _renderThanks() {\r\n el.form.hide();\r\n $('#thank-you').show();\r\n }", "function showButtons() {\n $(\".private\").css(\"display\", \"inherit\");\n $(\"#signUp\").css(\"display\", \"none\"); //Ocultamos el boton iniciar sesion\n}", "renderButtons() {\n // No confirmation needed so 1 OK button to dismiss the modal.\n if (this.props.type !== 'confirm') {\n return (\n <button\n className=\"o-button c-modal-button u-margin-top\"\n onClick={this.close}\n >\n OK\n </button>\n )\n }\n\n // If it is a confirm type, render 2 buttons, 1 to dismiss the\n // modal and 1 to call the confirm function.\n return (\n <div className=\"o-button-group c-modal-button-group u-margin-top\">\n <button\n className=\"o-button o-button--secondary c-modal-button\"\n onClick={this.close}\n >\n Cancel\n </button>\n <button\n className=\"o-button c-modal-button\"\n onClick={this.confirm}\n >\n Confirm\n </button>\n </div>\n )\n }", "function thankYouPage() {\r\n app.getView().render('subscription/emarsys_thankyou');\r\n}", "function insertButton() {\n\t\tconst button = paymentsClient.createButton({\n\t\t\tbuttonColor: window.gpay_button_color,\n\t\t\tbuttonSizeMode: 'fill',\n\t\t\tonClick: handleClick\n\t\t});\n\t\tbutton.id = 'checkoutcom-google-pay';\n\n\t\tif($selectedPaymentMethodId === $ckoPaymentMethodId) {\n\t\t\t$buttonArea.append(button);\n\t\t} else {\n\t\t\t$buttonArea.remove(button);\n\t\t}\n\t}", "render() {\n const currentUser = JSON.parse(sessionStorage.getItem(\"credentials\"))\n if (parseInt(this.props.user.id) === currentUser.id) {\n return <></>\n } else {\n if (this.props.newUser[0].vetoad === true && this.props.newUser[0].canSuggestEvent === false) {\n return (\n <Card className='invisibleCard'>\n <Card.Content className='invisibleCard'>\n <div className='participantModalButtonContainer'>\n <Button className='addParticipantEventButtons' color='green' onClick={() => this.props.updateVetoad(this.props.newUser[0].userId)}>Vetoad</Button>\n <Button className='addParticipantEventButtons' onClick={() => this.props.updateCanSuggestEvent(this.props.newUser[0].userId)}>Make Contributor</Button>\n </div>\n </Card.Content>\n </Card>\n )\n } else if (this.props.newUser[0].canSuggestEvent === true && this.props.newUser[0].vetoad === false) {\n return (\n <Card className='invisibleCard'>\n <Card.Content className='invisibleCard'>\n <div className='participantModalButtonContainer'>\n <Button className='addParticipantEventButtons' onClick={() => this.props.updateVetoad(this.props.newUser[0].userId)}>Vetoad</Button>\n <Button className='addParticipantEventButtons' color='green' onClick={() => this.props.updateCanSuggestEvent(this.props.newUser[0].userId)}>Make Contributor</Button>\n </div>\n </Card.Content>\n </Card>\n )\n } else if (this.props.newUser[0].canSuggestEvent === true && this.props.newUser[0].vetoad === true) {\n return (\n <Card className='invisibleCard'>\n <Card.Content className='invisibleCard'>\n <p>{this.props.newUser[0].firstName} {this.props.newUser[0].lastName}\n <div className='participantModalButtonContainer'>\n <Button className='addParticipantEventButtons' color='green' onClick={() => this.props.updateVetoad(this.props.newUser[0].userId)}>Vetoad</Button>\n <Button className='addParticipantEventButtons' onClick={() => this.props.updateCanSuggestEvent(this.props.newUser[0].userId)} color='green'>Make Contributor</Button>\n </div>\n </p>\n </Card.Content>\n </Card>\n )\n } else {\n return (\n <Card className='invisibleCard'>\n <Card.Content className='invisibleCard'>\n <div className='participantModalButtonContainer'>\n <Button className='addParticipantEventButtons' onClick={() => this.props.updateVetoad(this.props.newUser[0].userId)}>Vetoad</Button>\n <Button className='addParticipantEventButtons' onClick={() => this.props.updateCanSuggestEvent(this.props.newUser[0].userId)}>Make Contributor</Button>\n </div>\n </Card.Content>\n </Card>\n )\n }\n }\n }", "renderDisplayButton(displayed) {\n const { entries } = this.state;\n const total = entries.length;\n let displayButton;\n // compare length of visible answers to length of total answers to determine button to render\n if (displayed === total && total > 2) {\n // only allow users to collapse answers if total length is greater than 2\n displayButton = <b className=\"link\" role=\"button\" onClick={this.toggleShowAll}>COLLAPSE</b>;\n } else if (displayed < total) {\n // only allow users to load answers if there are unloaded answers\n displayButton = <b className=\"link\" role=\"button\" onClick={this.toggleShowAll}>SEE MORE ANSWERS</b>;\n }\n return displayButton;\n }", "reviewButton() {\n let reviewId = false;\n if (this.props.currentUser) {\n Object.keys(this.props.reviews).forEach(el => {\n if (this.props.reviews[el].user_id === this.props.currentUser.id) {\n reviewId = true\n }\n });\n }\n if (this.props.currentUser && reviewId) {\n return (\n <button\n onClick={this.handleEdit}\n className=\"edit-review\">\n <FontAwesome className=\"fa fa-star\"\n name=\"star\"\n size='lg'/>\n Edit Your Review </button>\n );\n } else if (this.props.currentUser) {\n return (\n <button\n onClick={this.handleCreate}\n className=\"show-review\">\n <FontAwesome className=\"fa fa-star\"\n name=\"star\"\n size='lg'/>\n Write a Review </button>\n );\n } else {\n return (\n <LoginFormContainer/>\n );\n }\n }", "function makeOrderButton() {\n if (checkStorage()) {\n document.getElementById(\"buttons\").innerHTML +=\n '<li><a href=\"order.html\">Confirm Your Order</a></li>';\n }\n}", "function preparePayPalButtons () {\n\tpaypal.Buttons({\n\t\tstyle: {\n\t\t\tlayout: 'horizontal'\n\t\t},\n\n\t\tcreateOrder: async function () {\n\t\t\tlet data = await $.post('/checkout', {\n\t\t\t\trequestedServices: buildRequestList(),\n\t\t\t\tpaymentMethod: 'PAYPAL'\n\t\t\t});\n\t\t\treturn data.orderID;\n\t\t},\n\n\t\t// Capture the funds from the transaction and validate approval with server.\n\t\tonApprove: async function (data) {\n\t\t\tlet status = await $.post('/approve', data);\n\t\t\tif (status === 'OK') {\n\t\t\t\tCookies.remove(window.serverData.checkoutCookieName, { expires: 1, path: '/', domain: window.serverData.checkoutCookieDomain, secure: false, sameSite: 'lax' });\n\t\t\t\tcheckoutItems = {};\n\t\t\t\tawait refreshCart();\n\t\t\t\tshowStatusMessage('Your purchase was received and is now pending!');\n\t\t\t} else {\n\t\t\t\tconsole.error(status, 'Transaction failed.');\n\t\t\t}\n\t\t}\n\t}).render('#paypal-button-container');\n}", "function showButtonVersion(acc) {\n elm = $('.version__button .invoice_button');\n acc == 'S'\n ? elm.css({ visibility: 'visible' })\n : elm.css({ visibility: 'hidden' });\n}", "unsignedButtonClicked()\n\t{\n\t\tthis.db.set( 'letterType', 3 );\n\t\treturn this.router.navigateToRoute( 'voting-form' );\n\t}", "function PaymentScreen(props) {\n /**\n * This useSelector function will extract the data from redux store state.\n * The useSelector will take the current state as the argument and returns\n * the required state.\n * Redux generally used to maintian the states of the entire application.\n */\n const [paymentMethod, setPaymentMethod] = useState('');\n \n const dispatch = useDispatch();\n\n /**\n * This submit button redirect to the next checkout step\n * by saving the payment method selected by the user.\n */\n const submitHandler = (e) => {\n e.preventDefault();\n dispatch(savePayment({ paymentMethod }));\n props.history.push('placeorder');\n }\n /**\n * This will return the data about how the DOM should look like.\n */\n return <div>\n <CheckoutSteps step1 step2 step3 ></CheckoutSteps>\n <div className=\"form\">\n <form onSubmit={submitHandler} >\n <ul className=\"form-container\">\n <li>\n <h2>Payment</h2>\n </li>\n <li>\n <div>\n <input type=\"radio\" name=\"paymentMethod\" id=\"paymentMethod\" value=\"paypal\" onChange={(e) => setPaymentMethod(e.target.value)}></input>\n <label htmlFor=\"paymentMethod\">Paypal</label>\n </div>\n </li>\n <li>\n <button type=\"submit\" className=\"button primary\">Continue</button>\n </li>\n </ul>\n </form>\n </div>\n </div>\n}", "function mainButtons(role) {\n\n\n var inlineHtml = ''\n inlineHtml +=\n '<div class=\"form-group container zee_available_buttons_section\">';\n inlineHtml += '<div class=\"row\">';\n if (isNullorEmpty(businessValuationApproved) || businessValuationApproved == 2) {\n // inlineHtml +=\n // '<div class=\"col-xs-6 sendDeed\"><input type=\"button\" value=\"SEND DEED OF VARIATION - EXIT PROGRAM ASSISTANCE OFFER\" class=\"form-control btn btn-info\" id=\"sendDeed\" /></div>'\n inlineHtml +=\n '<div class=\"col-xs-12 saveZeeLead\"><input type=\"button\" value=\"BUSINESS VALUATION APPROVED\" class=\"form-control btn btn-primary\" id=\"businessValuationApproved\" /></div>'\n } else if (deedOfVariationSent != 1 && businessValuationApproved == 1) {\n inlineHtml +=\n '<div class=\"col-xs-6 sendDeed\"><input type=\"button\" value=\"SEND DEED OF VARIATION - EXIT PROGRAM ASSISTANCE OFFER\" class=\"form-control btn btn-info\" id=\"sendDeed\" /></div>'\n inlineHtml +=\n '<div class=\"col-xs-6 saveZeeLead\"><input type=\"button\" value=\"SAVE\" class=\"form-control btn btn-primary\" id=\"saveZeeLead\" /></div>'\n } else if (deedOfVariationSent == 1 && deedOfVariationUploaded != 1) {\n inlineHtml +=\n '<div class=\"col-xs-12 saveZeeLead\"><input type=\"button\" value=\"UPLOAD SIGNED DEED OF VARIATION - EXIT PROGRAM ASSISTANCE OFFER\" class=\"form-control btn btn-primary\" id=\"uploadDeed\" /></div>'\n } else {\n inlineHtml +=\n '<div class=\"col-xs-12 saveZeeLead\"><input type=\"button\" value=\"SAVE\" class=\"form-control btn btn-primary\" id=\"saveZeeLead\" /></div>'\n }\n\n inlineHtml += '</div>';\n inlineHtml += '</div>';\n\n return inlineHtml\n }", "function CostCheckButton(theBtn : GameObject, itemCost : int) \n{\n\tif(cashCount < itemCost) //we can't afford this item :(\n\t{\n\t\ttheBtn.transform.Find(\"Label\").gameObject.GetComponent(UILabel).color = Color.red; //set cost text to red color\n\t\ttheBtn.transform.Find(\"Background\").gameObject.GetComponent(UISlicedSprite).color = Color(.5,.5,.5,.5); //set btn graphic to half-alpha grey\n\t\ttheBtn.collider.enabled = false; //disable button collider\n\t}\n\telse //we can afford this item! :)\n\t{\n\t\ttheBtn.transform.Find(\"Label\").gameObject.GetComponent(UILabel).color = Color.green; //set cost text to red color\n\t\ttheBtn.transform.Find(\"Background\").gameObject.GetComponent(UISlicedSprite).color = onColor; //set the color to \"on\"\n\t\ttheBtn.collider.enabled = true; //enable button collider\n\t}\n}", "render() {\n const currentUser = JSON.parse(sessionStorage.getItem(\"credentials\"))\n if (parseInt(this.props.user.userId) === currentUser.id) {\n return <></>\n } else {\n if (this.props.user.vetoad === true && this.props.user.canSuggestEvent === false) {\n return (\n <Card className='participantCard'>\n <Card.Content className='participantCard'>\n <li>\n <div className='participantButtonContainer'>\n <p className='addEventUserName'>{this.props.user.name}</p>\n <div className='addEventButtonContainer'>\n <Button className='addEventButtons' color='green' onClick={() => this.props.updateVetoad(this.props.user.userId)}>Vetoad</Button>\n <Button className='addEventButtons' onClick={() => this.props.updateCanSuggestEvent(this.props.user.userId)}>Make Contributor</Button>\n <Button className='addEventButtons' icon='trash alternate outline' onClick={() => this.props.removeParticipant(this.props.user.userId)}></Button>\n </div>\n </div>\n </li>\n </Card.Content>\n </Card>\n )\n } else if (this.props.user.canSuggestEvent === true && this.props.user.vetoad === false) {\n return (\n <Card className='participantCard'>\n <Card.Content className='participantCard'>\n <li>\n <div className='participantButtonContainer'>\n <p className='addEventUserName'>{this.props.user.name}</p>\n <div className='addEventButtonContainer'>\n <Button className='addEventButtons' onClick={() => this.props.updateVetoad(this.props.user.userId)}>Vetoad</Button>\n <Button className='addEventButtons' color='green' onClick={() => this.props.updateCanSuggestEvent(this.props.user.userId)}>Make Contributor</Button>\n <Button className='addEventButtons' icon='trash alternate outline' onClick={() => this.props.removeParticipant(this.props.user.userId)}></Button>\n </div>\n </div>\n </li>\n </Card.Content>\n </Card>\n )\n } else if (this.props.user.canSuggestEvent === true && this.props.user.vetoad === true) {\n return (\n <Card className='participantCard'>\n <Card.Content className='participantCard'>\n <li>\n <div className='participantButtonContainer'>\n <p className='addEventUserName'>{this.props.user.name}</p>\n <div className='addEventButtonContainer'>\n <Button className='addEventButtons' color='green' onClick={() => this.props.updateVetoad(this.props.user.userId)}>Vetoad</Button>\n <Button className='addEventButtons' onClick={() => this.props.updateCanSuggestEvent(this.props.user.userId)} color='green'>Make Contributor</Button>\n <Button className='addEventButtons' icon='trash alternate outline' onClick={() => this.props.removeParticipant(this.props.user.userId)}></Button>\n </div>\n </div>\n </li>\n </Card.Content>\n </Card>\n )\n } else {\n return (\n <Card className='participantCard'>\n <Card.Content className='participantCard'>\n <li>\n <div className='participantButtonContainer'>\n <p className='addEventUserName'>{this.props.user.name}</p>\n <div className='addEventButtonContainer'>\n <Button className='addEventButtons' onClick={() => this.props.updateVetoad(this.props.user.userId)}>Vetoad</Button>\n <Button className='addEventButtons' onClick={() => this.props.updateCanSuggestEvent(this.props.user.userId)}>Make Contributor</Button>\n <Button className='addEventButtons' icon='trash alternate outline' onClick={() => this.props.removeParticipant(this.props.user.userId)}></Button>\n </div>\n </div>\n </li>\n </Card.Content>\n </Card>\n )\n }\n }\n }", "function showHidePayPal() {\n\tif (formIsValid()) {\n\t\t$('#paypal-button').show()\n\t\t$('#empty-order-warning').hide()\n\t} else {\n\t\t$('#paypal-button').hide()\n\t\t$('#empty-order-warning').show()\n\t}\n}", "renderPaymentModal() {\n const avatar = () => (\n <UserAvatar\n source={\n this.state.recipient.avatarPath\n ? this.state.recipient.avatarPath\n : null\n }\n />\n );\n\n const amountToDisplay = `SGD $${this.state.amountPayable.toFixed(2)}`;\n return (\n <Modal\n backdropStyle={styles.backdrop}\n visible={this.state.paymentModalVisible}\n >\n <Card>\n <Text style={{fontWeight: 'bold', marginTop: 10, marginBottom: 10}}>\n Review Payment\n </Text>\n <ListItem\n description={\n <Text style={{fontSize: 17, fontWeight: 'bold'}}>\n {this.state.recipient && this.state.recipient.name}\n </Text>\n }\n title={\n <Text style={styles.label}>\n Recipient\n </Text>\n }\n accessoryRight={avatar}\n />\n <Divider />\n <ListItem\n description={\n <Text style={{fontSize: 17, fontWeight: 'bold'}}>\n {amountToDisplay}\n </Text>\n }\n title={\n <Text style={styles.label}>\n Pay Amount\n </Text>\n }\n />\n <Layout style={styles.modalButtonsContainer}>\n <Button\n style={styles.modalButton}\n size={'small'}\n onPress={() => {\n this.setState({paymentModalVisible: false});\n this.handleMakePayment();\n }}>\n Confirm\n </Button>\n <Button\n appearance={'outline'}\n style={styles.modalButton}\n size={'small'}\n onPress={() => {\n this.setState({paymentModalVisible: false, message: 'Payment was Cancelled'});\n }}>\n Dismiss\n </Button>\n </Layout>\n </Card>\n </Modal>\n );\n }", "renderLoginButton() {\n if (this.props.loggedIn) {\n return (\n <button className=\"ui red google button\"\n onClick={this.onSignOut}>\n <i className=\"google icon\" />\n SIGN OUT\n </button>\n )\n } else {\n return (\n <button className=\"ui green google button\"\n onClick={this.onSignIn}>\n <i className=\"google icon\"/>\n SIGN IN\n </button>\n )\n };\n }", "function btnregsenior(){\n\tdocument.getElementById(\"btnregsenior\").classList=\"regtypebtn btn btn-sm btn-primary col-xs-6 noround btnregsenior\";\n\tdocument.getElementById(\"btnregserviceprovider\").classList=\"regtypebtn btn btn-sm btn-default col-xs-6 noround btnregserviceprovider\";\n\tdocument.getElementById(\"bigicon\").classList=\"fa fa-user-circle-o\";\n\tdocument.getElementById(\"bigicon1\").classList=\"fa fa-user-circle-o\";\n\tdocument.getElementById(\"userType\").value=\"senior\";\n\tdocument.getElementById(\"reg-form\").style.display=\"block\";\n\tdocument.getElementById(\"providerServiceType\").style.display=\"none\";\n}", "function btnregserviceprovider(){\n\tdocument.getElementById(\"btnregsenior\").classList=\"regtypebtn btn btn-sm btn-default col-xs-6 noround btnregsenior\";\n\tdocument.getElementById(\"btnregserviceprovider\").classList=\"regtypebtn btn btn-sm btn-success col-xs-6 noround btnregserviceprovider\";\n\tdocument.getElementById(\"bigicon\").classList=\"fa fa-user-circle-o\";\n\tdocument.getElementById(\"bigicon1\").classList=\"fa fa-user-circle-o\";\n\tdocument.getElementById(\"userType\").value=\"serviceprovider\";\n\tdocument.getElementById(\"reg-form\").style.display=\"block\";\n\tdocument.getElementById(\"providerServiceType\").style.display=\"table\";\n\tdocument.getElementById(\"address\").style.display=\"none\";\n}", "function setButtons() {\n if ($routeParams.username != $rootScope.currentUser.username) {\n if ($rootScope.currentUser.friends.indexOf($routeParams.username) == -1) { // we aren't following them yet, show friend button\n $scope.friendbutton = true;\n $scope.unfriendbutton = false;\n } else {\n $scope.unfriendbutton = true;\n $scope.friendbutton = false;\n }\n }\n }", "paymentButtonClicked(){\n \n this.setState({\n accountModalVisible : true,\n paymentsModalVisible : false, \n })\n\n }", "function ButtonsProfile() {\n return (\n <div className=\"o-buttons-container\">\n <Button\n colorBackground={\"Blue\"}\n colorText={\"White\"}\n text={\"A domicilio\"}\n onClick={\"\"}\n icon={\"\"}\n />\n\n <Button\n colorBackground={\"Background\"}\n colorBorder={\"Blue\"}\n colorText={\"Blue\"}\n text={\"En el local\"}\n onClick={\"\"}\n icon={\"\"}\n />\n </div>\n );\n}", "function formatButton(button, paymentitems, paymentitemsbonus, iap) {\n function findItemByCCost(paymentitems, ccost) {\n var ret = {};\n _.forEach(paymentitems, function(item) {\n if (item.ccost == ccost) {\n ret = item;\n // break;\n return false;\n }\n });\n return ret;\n }\n\n var item = findItemByCCost(paymentitems, button.ccost);\n var itembonus = findItemByCCost(paymentitemsbonus, button.ccost);\n // \"value\": \"40K Gold\",\n // \"bonus\": \"+80K Chip\",\n // \"cost\": \"10K VND\",\n // \"syntax\": \"mw 10000 teen NAP 52fun-ann2009-1\",\n // \"add\": \"+9029\",\n button['carrier'] = usercarrier;\n var value = item[\"value\"]; // cần format cái này\n button['value'] = numeral(value).format('0,0');\n if (button.ctype == 0) // chip\n button['value'] += ' Chip';\n else // ctype == 1 -> Gold\n button['value'] += ' Gold';\n if (iap) {\n button['cost'] = item[\"USD\"];\n } else {\n button['cost'] = button[\"ccost\"] + \" VND\";\n }\n if (button.bstyle == 1) { // giá cũ/ giá mới\n var newvalue = itembonus[\"value\"] * (100 + button['bvalue']) / 100;\n button['bonus'] = numeral(newvalue).format('0,0');\n } else { // giá cũ/ bonus\n var bonus = itembonus[\"value\"] * (0 + button['bvalue']) / 100;\n button['bonus'] = \"+\" + numeral(bonus).format('0,0');\n }\n // button['bonus'] = numeral(button['bonus']).format('0.0a');\n if (button.btype == 0) // chip\n button['bonus'] += ' Chip';\n else\n button['bonus'] += ' Gold';\n if (button.type == \"sms\") {\n button['add'] = item[\"add\"];\n var smssyntax = item[\"content\"];\n smssyntax = _.replace(smssyntax, new RegExp(\"%user%\", \"g\"), username);\n button['syntax'] = _.replace(smssyntax, new RegExp(\"%type%\", \"g\"), button['ctype']);\n }\n\n if (usercarrier == 'unknown') {\n button['add'] = \"\";\n button['syntax'] = \"\";\n }\n\n\n return button;\n }", "rightButton() {\r\n if (!this.props.uBlocked) {\r\n if (this.props.following) {\r\n return (\r\n <TouchableOpacity\r\n style={styles.following}\r\n onPress={() => { this.unfollow(); }}\r\n >\r\n <Text style={{ color: '#fff', fontWeight: 'bold', fontSize: 15 }}>\r\n Following\r\n </Text>\r\n </TouchableOpacity>\r\n );\r\n }\r\n if (this.props.blocked) {\r\n return (\r\n <TouchableOpacity\r\n style={styles.blocked}\r\n onPress={() => { this.unblock(); }}\r\n >\r\n <Text style={{ color: 'red', fontWeight: 'bold', fontSize: 15 }}>\r\n Blocked\r\n </Text>\r\n </TouchableOpacity>\r\n );\r\n }\r\n if (this.props.following === false) {\r\n return (\r\n <TouchableOpacity\r\n style={styles.follow}\r\n onPress={() => { this.follow(); }}\r\n >\r\n <Text style={{ color: '#1DA1F2', fontWeight: 'bold', fontSize: 15 }}>\r\n Follow\r\n </Text>\r\n </TouchableOpacity>\r\n );\r\n }\r\n if (this.props.myProfile) {\r\n return (\r\n <TouchableOpacity\r\n style={styles.EditProfile}\r\n onPress={this.props.EditProfile}\r\n >\r\n <Text style={{ color: '#657786', fontWeight: 'bold' }}>\r\n Edit Profile\r\n </Text>\r\n </TouchableOpacity>\r\n );\r\n }\r\n }\r\n\r\n\r\n return (null);\r\n }", "function click(e){\n \n var nameOfClass=e.target.className;\n\n if(nameOfClass===\"navigation__container_wrapper_button\"){\n\n var btnId=e.target.id;\n\n if(btnId===\"button-button2\"){\n \n validateFlag=checkForm1();\n }\n else if(btnId===\"button-button1\"){\n storeActiveButtonId(btnId);\n modifyApperance(btnId);\n }\n else if(btnId===\"button-button3\"){\n validateFlag=checkForm2();\n }\n else if(btnId===\"button-button4\"){\n \n validateFlag=checkForm3();\n }\n if(validateFlag==1){\n storeActiveButtonId(btnId);\n storeInSessionStorage(btnId);\n modifyApperance(btnId);\n }\n else{\n alert(\"Fill the complete form\");\n }\n \n var pageData=getDataFromSessionStorage();\n\n if(pageData!=null){\n modifyData(pageData,0 );\n }\n \n \n \n \n }\n else if(nameOfClass===\"footer__container_wrapper_button\"){\n \n var activeBtnId=JSON.parse(window.sessionStorage.getItem('activeBtnId'));\n var validateFlag=0;\n \n \n if(e.target.id===\"button-nextButton\"){\n if(activeBtnId===\"button-button1\"){\n validateFlag=checkForm1();\n }\n else if(activeBtnId===\"button-button2\"){\n validateFlag=checkForm2();\n }\n else if(activeBtnId===\"button-button3\"){\n validateFlag=checkForm3();\n var active=getActiveSideBarOption();\n getCheckedOption(active);\n }\n if(validateFlag==1){\n if(parseInt(activeBtnId[13])==4){\n var newBtnNumber=parseInt(activeBtnId[13]);\n }\n else{\n var newBtnNumber=parseInt(activeBtnId[13])+1;\n }\n var newBtnId=\"button-button\"+newBtnNumber;\n if(newBtnId===\"button-button4\"){\n var id=getActiveQuestion();\n showSelectedQuestion(id);\n highlightQuestion(id);\n storeActiveQuestion(id);\n }\n storeActiveButtonId(newBtnId);\n storeInSessionStorage(newBtnId);\n var pageData=getDataFromSessionStorage(newBtnId);\n modifyApperance(newBtnId);\n if(pageData!=null){\n modifyData(pageData,0);\n }\n \n }\n \n \n }\n else if(e.target.id===\"button-backButton\"){\n //storeInSessionStorage(activeBtnId);\n if(parseInt(activeBtnId[13])==1){\n var newBtnNumber=parseInt(activeBtnId[13]);\n }\n else{\n var newBtnNumber=parseInt(activeBtnId[13])-1;\n }\n var newBtnId=\"button-button\"+newBtnNumber;\n \n storeActiveButtonId(newBtnId);\n \n var pageData=getDataFromSessionStorage(newBtnId);\n console.log(\"data on coming back \",pageData);\n modifyData(pageData,0);\n modifyApperance(newBtnId);\n \n }\n else if(e.target.id===\"button-submitButton\"){\n console.log(\"in submit button\");\n var validateFlag=checkButtonStatus();\n if(validateFlag==1){\n storeInSessionStorage(\"button-submitButton\");\n alert(\"Submitted Successfully\");\n }\n }\n \n \n\n }\n}", "renderThank()\n {\n \treturn (\n \t\t<div>\n \t\t<h3 style={{color:myMuiTheme.palette.primary1Color}}>Thanks for filling out our survey! Click the button below to proceed to our main website. </h3><br/>\n <RaisedButton label=\"Main Page\" secondary={true} labelColor={myMuiTheme.palette.labelColor} \n onClick={this.handleOnClick}\n />\n </div>\n \t\t)\n }", "function change_buttons() {\n\tdocument.querySelectorAll('.request-button, .delete-button').forEach(function(button) {\n\t\tvar trade_request = document.querySelector('#trade-requests > div[data-isbn=\"' + button.dataset.isbn + '\"]');\n\t\tvar active_trade = document.querySelector('#active-trades > div[data-isbn=\"' + button.dataset.isbn + '\"]');\n\t\tif (trade_request || active_trade) {\n\t\t\tbutton.setAttribute('disabled', '');\n\t\t\tif (trade_request) {\n\t\t\t\tbutton.innerText = 'Trade Requested';\n\t\t\t}\n\t\t\telse if (active_trade) {\n\t\t\t\tbutton.innerText = 'Loaning';\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tbutton.removeAttribute('disabled');\n\t\t\tif (button.classList.contains('request-button')) {\n\t\t\t\tbutton.innerText = 'Request Book';\t\n\t\t\t}\n\t\t\telse if (button.classList.contains('delete-button')) {\n\t\t\t\tbutton.innerText = 'Delete Book';\n\t\t\t}\n\t\t}\n\t});\n}", "render() {\n const text = this.state.followed ? 'un-follow' : 'follow';\n const label = this.state.followed ? 'Following' : 'Follow'\n return (\n <div className=\"customContainer\">\n <button className=\"btn-primary\" onClick={this.handleClick} >\n {label}</button>\n <p className={styles.followText}>\n Click to {text} this Country (must be logged in to follow)\n </p>\n </div>\n );\n }", "function feedbackButton() {\n $( '#age-selector-response .thank-you' ).show();\n $( '#age-selector-response .helpful-btn' )\n .attr( 'disabled', true )\n .addClass( 'btn__disabled' ).hide();\n}", "function AcceptUI() {\n\n //To set the action URL for the payment form in Accept UI section\n var form = document.getElementById(\"paymentForm\");\n form.setAttribute(\"action\", window.location.href.split('?')[0]);\n \n //Accept UI pay button has predefined attributes that are declared below.\n //To set values for accept UI Pay button\n var ele = document.getElementById(\"btnAcceptUI\");\n\n //Below values are fetched from the constants.js file\n ele.setAttribute(\"data-apiLoginID\", globalVars.ApiLoginID);\n ele.setAttribute(\"data-clientKey\", globalVars.ClientKey);\n}", "approve() {\n if (!this.props.accepted) {\n return (\n <div>\n <RaisedButton\n label=\"Approve\"\n style={buttonStyle}\n onClick={this.approveRequest}\n />\n </div>\n );\n } else {\n return (\n <div>\n <h4>\n Approved<i class=\"fa fa-check\" aria-hidden=\"true\" />\n </h4>\n </div>\n );\n }\n }", "function onBasicBuyBtnClicked() {\n console.log(\"onTestBtnClicked()...\");\n\n if (!window.PaymentRequest) {\n console.log(\"buildSimplePaymentRequest: PaymentRequest API is not available!\");\n alert('PaymentRequest API is not available!');\n return null;\n }\n \n const request = new PaymentRequest( \n supportedPaymentMethods, \n paymentDetails, \n {} \n );\n \n request.show() \n .then(function(response) {\n // Process response\n response.complete(\"success\");\n console.log(\"Payment success!\");\n alert('Payment is successful!');\n }).catch(function(err) {\n console.error(\"Uh oh, something bad happened\", err.message);\n alert('Payment is cancelled!');\n });\n}", "function keurenButton() {\n\tconst menuButtonBody = document.querySelector('.menu-buttons');\n\t\n\tvar role = sessionStorage.getItem(\"rol\");\n\t//If user is a Voorstel manager add 2 buttons for approving products and seeing all the products\n\tif (role === \"Voorstel manager\") {\n\t\tmenuButtonBody.innerHTML += '<div class=\"button-div\">' +\n\t\t\t\t\t\t\t\t\t\t'<a href=\"product_keuren.html\"><button class=\"menu-button\" name=\"keuren\" value=\"Keuren\" id=\"keuren\">Keuren</button></a>' +\n \t\t\t\t\t\t\t\t'</div>';\n\t\t\n \tmenuButtonBody.innerHTML += '<div class=\"button-div\">' +\n \t\t\t\t\t\t\t\t\t'<a href=\"products.html\"><button class=\"menu-button\" name=\"product\" value=\"Producten\" id=\"producten\"\">Producten</button></a>' +\n \t\t\t\t\t\t\t\t'</div>';\n \t\n \t$(\".menu-content\").css(\"margin\", \"6vh auto\");\n\n //If user is a Budget manager only add 1 button that leads to budget proposals\n\t} else if (role === \"Budget manager\") {\n\t\tmenuButtonBody.innerHTML += '<a href=\"budget_keuren.html\"><button class=\"menu-button\" name=\"keuren\" value=\"Keuren\" id=\"keuren\"\">Keuren</button></a>';\n\t\t\n\t\t$(\".menu-content\").css(\"margin\", \"12vh auto\");\n\t}\n}", "function formVal () {\n creditCheck ();\n if (payment.options[1].value === payment.value) {\n if (firstName.value === \"\") {\n registerButton.disabled = true;\n } else if (emailResult === false) {\n registerButton.disabled = true;\n } else if (checkBoxResult === false) {\n registerButton.disabled = true; \n } else if (creditCardResult === false) {\n registerButton.disabled = true; \n } else if (zipResult === false) {\n registerButton.disabled = true; \n } else if (cvvResult === false) {\n registerButton.disabled = true; \n } else {\n registerButton.disabled = false; \n }\n } else {\n if (firstName.value === \"\") {\n registerButton.disabled = true;\n } else if (emailResult === false) {\n registerButton.disabled = true;\n } else if (checkBoxResult === false) {\n registerButton.disabled = true; \n } else {\n registerButton.disabled = false; \n } \n }\n if (registerButton.disabled === true) {\n registerButton.style.color = 'white';\n registerButton.style.backgroundColor = 'grey';\n registerButton.style.cursor = 'not-allowed';\n } else {\n registerButton.style.color = null;\n registerButton.style.backgroundColor = null;\n registerButton.style.cursor = 'pointer';\n }\n}", "function renderModalFooterBtns() {\n if (forgotPwdTabSelected) {\n return (\n <>\n <button className=\"modal-link-btn\" type=\"button\" onClick={openLoginRegisterModal}>Back</button>\n <button className=\"modal-action-btn\" type=\"submit\">Submit</button>\n </>\n )\n }\n\n if (resetPwdTabSelected) {\n return (\n <>\n <button className=\"modal-action-btn\" type=\"submit\">Reset</button>\n </>\n )\n }\n\n return null;\n }", "function approveBtnFun() {\r\n let approveBtn = document.querySelector('.footer-section .approve-btn');\r\n if (!approveBtn.classList.contains('disabled')) {\r\n let container = document.querySelector('.pay-now-container'),\r\n total = document.querySelector('.total-section .total-num-box'),\r\n payNowBtn = container.querySelector('.pay-btn span');\r\n // check validation\r\n payNowCheckValidation();\r\n payNowBtn.textContent = total.textContent;\r\n // Open popup\r\n globalObj.openPopup(container);\r\n }\r\n}", "function handleShipToStore() {\n differentStorePickup = false;\n $.next_button.setTitle(_L('Next'));\n}", "render() {\n return !this.state.isLoading ? (this.state.isSubscribed ?\n <Button onClick={this.handleUnsubscribe.bind(this)} className=\"h-50\" variant=\"outline-primary\">\n <BookmarkCheck className=\"mr-2\" />Unfolloow\n </Button> :\n <Button onClick={this.handleSubscribe.bind(this)} className=\"h-50\" variant=\"outline-secondary\">\n <BookmarkPlus className=\"mr-2\" />&nbsp; Folloow &nbsp;\n </Button>) \n : <Button variant=\"outline-secondary\">&nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp; ... &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</Button>\n }", "function initPayment(){\n paymentOptions[1].selected = true;\n //we use nextElementSibling because the divs don't have id or class in the HTML\n displayPayment (creditCardDiv);\n /* creditCardDiv.style.display = '';\n paypalDiv.style.display = 'none';\n bitcoinDiv.style.display = 'none'; */\n }", "function AddPlayer(props) {\n const { userData } = useUser()\n return (\n <div>\n {!userData.user.booking ? props.selected ? \n <div>\n <button onClick={props.book}>Book?</button>\n <button onClick={props.cancel}>Cancel</button>\n </div>: null :\n <button onClick={() => props.unbook()}>Unbook court</button>}\n </div>\n )\n}", "function display(payment,payment2,payment3){\r\n\tbackToSummery();\r\n\tpayment2.style.display=\"none\";\r\n\tpayment.style.display=\"block\";\r\n\tbackToColor();\r\n\tpayment3.style.background=\"#fff\";\r\n}", "function simpleOverallButton() {\n \"use strict\";\n var extra = simple_global.button_style;\n\n if ($('.wpcf7-form input[type=\"submit\"]').length > 0) {\n $('.wpcf7-form input[type=\"submit\"]').addClass('btn-bt').addClass(extra);\n }\n if ($('#respond input[type=\"submit\"]').length > 0) {\n $('#respond input[type=\"submit\"]').addClass('btn-bt').addClass(extra);\n }\n\n if ($('.woocommerce .button, #woocommerce .button').length > 0) {\n $('.woocommerce .button, #woocommerce .button').not('.wpb_content_element.button').addClass('btn-bt').addClass(extra);\n }\n\n if ($('.not_found .search_field').length > 0) {\n $('.not_found .search_field button').addClass('btn-bt').addClass(extra);\n }\n\n if ($('.post-password-form input[type=\"submit\"]').length > 0) {\n $('.post-password-form input[type=\"submit\"]').addClass('btn-bt').addClass(extra);\n }\n\n if ($('.mc_signup_submit input').length > 0) {\n $('.mc_signup_submit input').addClass('btn-bt').addClass(extra);\n }\n\n if ($('.mc4wp-form input[type=\"submit\"]').length > 0) {\n $('.mc4wp-form input[type=\"submit\"]').addClass('btn-bt').addClass(extra);\n }\n\n $(\"body\").bind(\"added_to_cart\", function() {\n $('.added_to_cart').addClass('btn-bt').addClass(extra);\n });\n if ($('#place_order.button').length > 0) {\n $('#place_order.button').addClass('btn-bt').addClass(extra);\n }\n }", "function renderButtons() {\n // Determine if player1 exists and render player1 buttons if not\n if (player1 === null) {\n // console.log(\"Adding Player 1 buttons\");\n\n $(\"#button-view\").empty();\n\n // Iterate through our array, creat the buttons and append them to the button-view div\n for (var i = 0; i < computerChoices.length; i++) {\n var a = $(\"<button>\");\n a.addClass(\"btn btn-default m-1 choice1\");\n a.attr(\"data-name\", computerChoices[i]);\n a.text(computerChoices[i]);\n $(\"#button-view\").append(a);\n };\n }\n // Determine if player2 exists and render player2 buttons if not\n else if ( (player1 !== null) && (player2 === null) ) {\n // console.log(\"Adding Player 2 buttons\");\n\n $(\"#button-view\").empty();\n\n // Iterate through our array, creat the buttons and append them to the button-view div\n for (var i = 0; i < computerChoices.length; i++) {\n var a = $(\"<button>\");\n a.addClass(\"btn btn-default m-1 choice2\");\n a.attr(\"data-name\", computerChoices[i]);\n a.text(computerChoices[i]);\n $(\"#button-view\").append(a);\n };\n }\n}", "function switchToStripe() {\n const currentlyOnStripe = $stripePaymentButton.is(\":visible\") === true || currentProcessor === \"stripe\";\n if (currentlyOnStripe === true) {\n return false;\n }\n currentProcessor = \"stripe\";\n $paypalPaymentBox.fadeOut(pmtMethodTransitionMs, function () {\n $paypalRadio.prop(\"checked\", false);\n $stripePay.fadeIn(pmtMethodTransitionMs);\n $stripeRadio.prop(\"checked\", true);\n });\n }", "function addStripePaymentButton($amount){\n removeStripeScript();\n\n var $amountForStripe = $amount*100,\n $container = $(\"<div>\").attr(\"id\", \"stripeBtnScript\"),\n $stripeScript = $(\"<script>\").addClass(\"stripe-button\");\n\n $stripeScript.attr(\"src\", \"https://checkout.stripe.com/checkout.js\");\n $stripeScript.attr(\"data-key\", \"pk_test_7AL8K2hvvfLEyVuLe6eLL1jE\");\n $stripeScript.attr(\"data-amount\", $amountForStripe);\n $stripeScript.attr(\"data-name\", \"Pick6 - Online Squares\");\n $stripeScript.attr(\"data-description\", \"Add $\"+$amount+\" of Credit\");\n $stripeScript.attr(\"data-image\", \"img/pick6_128.jpg\");\n $stripeScript.attr(\"data-locale\", \"auto\");\n $stripeScript.attr(\"data-email\", \"{{Auth::user()->email}}\");\n $stripeScript.attr(\"data-zip-code\", true);\n\n $container.append($stripeScript);\n $(\"#forStripe\").append($container);\n\n var origin = window.location.origin;\n var url = origin+\"/charge\";\n $(\"#payForm\").attr(\"action\", url);\n\n var $amountInput = $(\"<input>\");\n $amountInput.attr(\"type\", \"hidden\");\n $amountInput.attr(\"name\", \"amount\");\n $amountInput.attr(\"value\", $amountForStripe);\n $(\"#payForm\").append($amountInput);\n\n setTimeout(function(){\n $(\"button.stripe-button-el\").trigger(\"click\");\n }, 500);\n }", "showChooseOrSignIn () {\n if (this.rsWidget.classList.contains('rs-modal')) {\n this.rsBackdrop.style.display = 'block';\n this.rsBackdrop.classList.add('visible');\n }\n // choose backend only if some providers are declared\n if (this.rs.apiKeys && Object.keys(this.rs.apiKeys).length > 0) {\n this.setState('choose');\n } else {\n this.setState('sign-in');\n }\n }" ]
[ "0.6542581", "0.63429713", "0.6242841", "0.62422943", "0.62125885", "0.6202621", "0.6165143", "0.61620194", "0.6141722", "0.61381066", "0.6030694", "0.59838", "0.59441376", "0.5930966", "0.5884081", "0.58815604", "0.5863927", "0.58572143", "0.58392096", "0.5814357", "0.5811823", "0.579495", "0.5792527", "0.5772994", "0.5771556", "0.5771146", "0.57469267", "0.57331574", "0.5729437", "0.5724821", "0.57229686", "0.5712672", "0.5712672", "0.570003", "0.5685074", "0.5670338", "0.56685084", "0.5660059", "0.5640029", "0.56397986", "0.5638046", "0.5634896", "0.5614963", "0.5614483", "0.55986106", "0.5598481", "0.5586309", "0.55798477", "0.55733204", "0.5567911", "0.55603325", "0.555231", "0.5550117", "0.5538038", "0.55271924", "0.55241925", "0.5502316", "0.54942447", "0.54814345", "0.54771405", "0.5474857", "0.54730445", "0.5459288", "0.5455013", "0.5435857", "0.5433702", "0.54333717", "0.5427412", "0.5424067", "0.5419645", "0.5418997", "0.5418899", "0.5418624", "0.5415927", "0.5409804", "0.5408215", "0.54028934", "0.540163", "0.5400138", "0.5397404", "0.53953856", "0.53943664", "0.53851855", "0.5381316", "0.537531", "0.53673655", "0.53662294", "0.53635484", "0.5361358", "0.53602403", "0.5359615", "0.5348774", "0.53470695", "0.5345985", "0.5342789", "0.5342684", "0.5339085", "0.5333127", "0.53329325", "0.53216517" ]
0.74037564
0
this function takes the temperature from the dataHandler and displays the temperature according to the correct temperature unit, and colors the temperature hot or cold.
function formatTemperature(kelvin) { var clicked = false; var fahr = ((kelvin * 9 / 5) - 459.67).toFixed(0); var cels = (kelvin - 273.15).toFixed(1); //initial temperature display $tempText.html(fahr); var firstClick = false; //click handler to update the temperature unit of measurement. $tempMode.off("click").on("click", function() { firstClick = true; console.log(clicked); clicked === false ? clicked = true : clicked = false; clicked === true ? $tempMode.html("C&deg") : $tempMode.html("F&deg"); if (clicked) { $tempText.html(cels); } else $tempText.html(fahr); }); if (cels > 24) { $("#temp-text").css("color", "red"); } else if (cels < 18) { $("#temp-text").css("color", "blue"); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function showTemperature(response) {\n let temperatureElement = document.querySelector(\".current-temperature\");\n let cityElement = document.querySelector(\".current-city\");\n let descriptionElement = document.querySelector(\".description\");\n let minimumTemperature = document.querySelector(\".min-temp\");\n let maximumTemperature = document.querySelector(\".max-temp\");\n let humidityElement = document.querySelector(\".humidity-percent\");\n let windElement = document.querySelector(\".wind-speed\");\n let currentEmoji = document.querySelector(\".currentemoji\");\n let img = document.querySelector(\"#artwork\");\n let textElement = document.querySelector(\"#cartel\");\n\n celsiusTemperature = response.data.main.temp;\n\n let emojiElement = response.data.weather[0].icon;\n if (emojiElement === \"01d\" || emojiElement === \"01n\") {\n currentEmoji.innerHTML = \"☀️\";\n img.setAttribute(\"src\", \"img/tarsila-doamaral.jpg\");\n textElement.innerHTML = `<div> Tarsila do Amaral, <i>Abaporu</i>, 1928 </br>© Tarsila do Amaral </div>`;\n }\n\n if (emojiElement === \"02d\" || emojiElement === \"02n\") {\n currentEmoji.innerHTML = \"🌤\";\n img.setAttribute(\"src\", \"img/swynnerton-landscape.jpg\");\n textElement.innerHTML = `<div>Annie Louisa Swynnerton, <i>Italian Landscape</i>, 1920 </br>© Manchester Art Gallery </div>`;\n }\n\n if (emojiElement === \"03d\" || emojiElement === \"03n\") {\n currentEmoji.innerHTML = \"🌥\";\n img.setAttribute(\"src\", \"img/etel-adnan.jpg\");\n textElement.innerHTML = `<div>Etel Adnan, <i>Untitled</i>, 2010</br>© Rémi Villaggi / Mudam Luxembourg</div>`;\n }\n\n if (emojiElement === \"04d\" || emojiElement === \"04n\") {\n currentEmoji.innerHTML = \" ☁️\";\n img.setAttribute(\"src\", \"img/georgia-okeefe-clouds.jpg\");\n textElement.innerHTML = `<div> Georgia O’Keeffe, <i>Sky Above Clouds IV</i>, 1965</div>`;\n }\n if (emojiElement === \"09d\" || emojiElement === \"09n\") {\n currentEmoji.innerHTML = \"🌧\";\n img.setAttribute(\"src\", \"img/vangogh-rain.jpg\");\n textElement.innerHTML = `<div>Vincent Van Gogh, <i>Auvers in the Rain</i>, 1890</div>`;\n }\n if (emojiElement === \"10d\" || emojiElement === \"10n\") {\n currentEmoji.innerHTML = \"🌦\";\n img.setAttribute(\"src\", \"img/munch-lecri.jpg\");\n textElement.innerHTML = `<div>Edvard Munch, <i>Le Cri</i>, 1893 </br>© National Gallery of Norway</div>`;\n }\n if (emojiElement === \"11d\" || emojiElement === \"11n\") {\n currentEmoji.innerHTML = \"🌩\";\n img.setAttribute(\"src\", \"img/william-turner.jpg\");\n textElement.innerHTML = `<div>William Turner, <i>Fishermen at Sea</i>, 1796</div>`;\n }\n if (emojiElement === \"13d\" || emojiElement === \"13n\") {\n currentEmoji.innerHTML = \"❄️\";\n img.setAttribute(\"src\", \"img/monet-snow.jpg\");\n textElement.innerHTML = `<div>Claude Monet, <i>Wheatstacks, Snow Effect, Morning</i>, 1891</div>`;\n }\n if (emojiElement === \"50d\" || emojiElement === \"50n\") {\n currentEmoji.innerHTML = \"🌫\";\n img.setAttribute(\"src\", \"img/friedrich-seafog.jpg\");\n textElement.innerHTML = `<div>Caspar David Friedrich, </br><i>Wanderer above the Sea of Fog</i>, 1818</div>`;\n }\n\n let parisTemperature = Math.round(celsiusTemperature);\n temperatureElement.innerHTML = `• ${parisTemperature}°C`;\n cityElement.innerHTML = response.data.name;\n descriptionElement.innerHTML = response.data.weather[0].description;\n minimumTemperature.innerHTML = Math.round(response.data.main.temp_min) + \"°C\";\n maximumTemperature.innerHTML = Math.round(response.data.main.temp_max) + \"°C\";\n humidityElement.innerHTML = response.data.main.humidity + \"%\";\n windElement.innerHTML = Math.round(response.data.wind.speed) + \" km/h\";\n\n getForecast(response.data.coord);\n}", "function renderWeather(data) {\n\toutputLocation.textContent = data.name + \", \" + data.sys.country;\n\toutputTemp.textContent = Math.round(data.main.temp);\n\toutputDesc.textContent = \" \" + data.weather[0].description;\n\toutputMaxTemp.textContent = \" \" + Math.round(data.main.temp_max);\n\toutputMinTemp.textContent = \" \" + Math.round(data.main.temp_min);\n\toutputWind.textContent = Math.round(data.wind.speed);\n\toutputHumidity.textContent = data.main.humidity;\n \n}", "function showTemperature(response) {\n console.log(response)\n document.querySelector(\"#city\").innerHTML = response.data.name;\n\n let temperature = Math.round(response.data.main.temp);\n \n let temp = document.querySelector(\"#now-temp\");\n temp.innerHTML = temperature;\n \n let highTemp = document.querySelector(\"#high-temp\");\n highTemp.innerHTML = Math.round(response.data.main.temp_max);\n \n let lowTemp = document.querySelector(\"#low-temp\");\n lowTemp.innerHTML = Math.round(response.data.main.temp_min);\n \n let description = document.querySelector(\"#description\");\n description.innerHTML = response.data.weather[0].description;\n \n let wind = document.querySelector(\"#wind\");\n wind.innerHTML = Math.round(response.data.wind.speed * 3.6);\n\n let humidity = document.querySelector(\"#humidity\");\n humidity.innerHTML = Math.round(response.data.main.humidity);\n\n let mainIcon = document.querySelector('#main-weather-icon')\n mainIcon.setAttribute('src', `http://openweathermap.org/img/wn/${response.data.weather[0].icon}@2x.png`);\n mainIcon.setAttribute('alt', response.data.weather[0].description);\n}", "function displayTemperature(response) {\n let cityName = response.data.name;\n let cityElement = document.querySelector(\"#city\");\n let dateElement = document.querySelector(\"#day-time\");\n let temperature = Math.round(response.data.main.temp);\n let currentTemp = document.querySelector(\"#degree\");\n let tempDescription = document.querySelector(\"#conditions\");\n let humidity = document.querySelector(\"#humidity-stat\");\n let wind = document.querySelector(\"#wind-stat\");\n let icon = document.querySelector(\"#weather-icon\");\n\n celsiusTemp = response.data.main.temp;\n\n cityElement.innerHTML = `${cityName}`;\n dateElement.innerHTML = formatDate(response.data.dt * 1000);\n currentTemp.innerHTML = `${temperature}`;\n tempDescription.innerHTML = response.data.weather[0].description;\n humidity.innerHTML = response.data.main.humidity;\n wind.innerHTML = Math.round(response.data.wind.speed);\n icon.setAttribute(\"src\", `http://openweathermap.org/img/wn/${response.data.weather[0].icon}@2x.png`);\n icon.setAttribute(\"alt\", response.data.weather[0].description);\n}", "function updateHVACDriverTempDisplay(temp) {\n\t$(\"#environmentData .temperature .value\").text(temp);\n}", "function displayTemperature(temperature) {\n\tlet returnTemp = temperature\n\tif (!isMetric()) {\n\n\t\t\treturnTemp = temperature * (9 / 5) + 32;\n\t\t// this equation was wrong returnTemp = (temperature - 32) * (5 / 9)\n\t}\n\t//rounding the temp\n\treturn Math.round(returnTemp)\n}", "function colorWorldWideWeather(temperature){\n var color;\n if (temperature > 40) {\n color = \"red\";\n }\n else if (temperature > 30 && temperature <= 40) {\n color = \"orange\"\n }\n else if (temperature > 20 && temperature <= 30) {\n color = \"yellow\"\n }\n else if (temperature > 10 && temperature <= 20) {\n color = \"blue\";\n }\n else {\n color = \"grey\";\n }\n return color;\n }", "function stuffTemperature(temp, units) {\n // console.log(\"stuffTemperature:\", temp, units);\n $('#temperature').html(temp.toString() + '&#176; ');\n var unitString = units == 'metric'\n ? 'C'\n : 'F';\n $(\"#units\").html(unitString);\n}", "function showTemp(response) {\n // Identify Celcius Temp\n celciusTemperature = Math.round(response.data.main.temp);\n // Locate Metric\n let currentTemperature = Math.round(celciusTemperature);\n // Identify Element to Change\n let currentTemperatureElement = document.querySelector(\"#temp\");\n // Change Element to Metric\n currentTemperatureElement.innerHTML = `${currentTemperature} °C`;\n // Change Country and City in HTML\n let city = response.data.name;\n let country = response.data.sys.country;\n let locationElement = document.querySelector(\"#searched-city\");\n locationElement.innerHTML = `${city}, ${country}`;\n // Change Weather Details\n document.querySelector(\n \"#humidity\"\n ).innerHTML = ` Humidity: ${response.data.main.humidity}%`;\n document.querySelector(\n \"#wind-speed\"\n ).innerHTML = ` Wind: ${response.data.wind.speed} mph`;\n\n // Change Icon\n let weatherIcon = document.querySelector(\"#current-weather-icon\");\n weatherIcon.innerHTML = `<img src=\"https://openweathermap.org/img/wn/${response.data.weather[0].icon}@2x.png\" alt=\"weather-icon\">`;\n\n // Change Weather Description\n let weatherDescriptionElement = document.querySelector(\n \"#weather-description\"\n );\n if (currentTemperature <= 0) {\n weatherDescriptionElement.innerHTML =\n \"It's very cold out there. Wrap up warm!\";\n } else if (currentTemperature >= 10 === currentTemperature <= 19) {\n weatherDescriptionElement.innerHTML = \"Maybe put on a jumper.\";\n } else if (currentTemperature > 19) {\n weatherDescriptionElement.innerHTML =\n \"It's a lovely warm day. <br /> Get outside and enjoy it!\";\n }\n\n getForecast(response.data.coord);\n}", "function displayTemperature(response) {\n // step 5\n let temperature = document.querySelector(\"#temperature\");\n // step 6\n temperature.innerHTML = `${Math.round(response.data.main.temp)}°C`;\n let city = document.querySelector(\"#city\");\n city.innerHTML = response.data.name;\n}", "function showTemperature(response) {\n celsuisTemp = Math.round(response.data.main.temp);\n let apiLocation = response.data.name;\n let cityPlaceholder = document.querySelector(\".location\");\n cityPlaceholder.innerHTML = `${apiLocation}`;\n let temperaturePlaceholder = document.querySelector(\".temperature\");\n temperaturePlaceholder.innerHTML = `${celsuisTemp}°C`;\n let description = response.data.weather[0].main;\n let descriptionPlaceholder = document.querySelector(\".weatherDescription\");\n descriptionPlaceholder.innerHTML = `${description}`;\n let humidity = response.data.main.humidity;\n let humuidityPlaceholder = document.querySelector(\".humidityValue\");\n humuidityPlaceholder.innerHTML = `Humidity: ${humidity}%`;\n let windSpeed = response.data.wind.speed;\n let windPlaceholder = document.querySelector(\".windSpeed\");\n windPlaceholder.innerHTML = `Wind Speed: ${windSpeed}m/s`;\n fahrenheitLink.classList.remove(\"active\");\n celsiusLink.classList.add(\"active\");\n let iconToday = document.querySelector(\".weather-icon\");\n iconToday.setAttribute(\"class\", showIcon(response.data.weather[0].icon));\n}", "function show(data){ \n return `<h3 class='temp'> The Weather in ${location} is Currently ${data.main.temp} C°</h3>`;\n }", "function showTemperature(response) {\n let temperature = Math.round(response.data.main.temp);\n temperatureDisplay.innerHTML = temperature;\n let description = response.data.weather[0].description;\n descriptionDisplay.innerHTML = description;\n let wind = Math.round(response.data.wind.speed);\n windDisplay.innerHTML = `Wind: ${wind}km/h`;\n let humidity = Math.round(response.data.main.humidity);\n humidityDisplay.innerHTML = `Humidity: ${humidity}%`;\n let tempMin = Math.round(response.data.main.temp_min);\n let tempMax = Math.round(response.data.main.temp_max);\n tempRangeDisplay.innerHTML = `${tempMin}℃/${tempMax}℃`;\n console.log(response);\n let cityApi = response.data.name;\n cityDisplay.innerHTML = cityApi;\n}", "function displayTemperature(response) {\n let cityElement = document.querySelector(\"#Location\");\n let tempElement = document.querySelector(\"#todayTemp\");\n let describElement = document.querySelector(\"#description\");\n let humidElement = document.querySelector(\"#humid\");\n let windElement = document.querySelector(\"#wind\");\n let dateElement = document.querySelector(\"#date\");\n let iconElement = document.querySelector(\"#icon\");\n cityElement.innerHTML = response.data.name;\n tempElement.innerHTML = Math.round(response.data.main.temp);\n describElement.innerHTML = response.data.weather[0].description;\n humidElement.innerHTML = response.data.main.humidity;\n windElement.innerHTML = Math.round(response.data.wind.speed);\n dateElement.innerHTML = formateDate(response.data.dt * 1000);\n iconElement.setAttribute(\n \"src\",\n `https://openweathermap.org/img/wn/${response.data.weather[0].icon}@2x.png`\n );\n\n iconElement.setAttribute(\"alt\", response.data.weather[0].description);\n}", "function chg_temp(temp){\n \n if (temp == \"celsius\"){\n \n document.getElementById(\"curr_temp\").innerHTML = \"<small>Current temperature: </small>\" + \"<b>\" + data.main.temp +\"</b>\"+ \"<b> C </b>\";\n document.getElementById(\"hi_temp\").innerHTML = \"<small>Expected High: </small>\" + \"<b>\" + data.main.temp_max + \"</b>\" + \" <b> C </b>\";\n document.getElementById(\"low_temp\").innerHTML = \"<small>Expected Low: </small>\" + \"<b>\" + data.main.temp_min + \" </b>\" + \"<b>C </b>\";\n btn.innerHTML = \"Press for Farenheit\";\n temp = \"farenheit\";\n }\n else{\n\n var curr_temp_faren = parseFloat((data.main.temp * 1.8) + 32).toFixed(2);\n var hi_temp_faren = parseFloat((data.main.temp_max * 1.8) + 32).toFixed(2);\n var low_temp_faren = parseFloat((data.main.temp_min * 1.8) + 32).toFixed(2);\n\n document.getElementById(\"curr_temp\").innerHTML = \"<small>Current temperature: </small>\" + \"<b>\" + curr_temp_faren +\"</b>\"+ \"<b> F </b>\";\n document.getElementById(\"hi_temp\").innerHTML = \"<small>Expected High: </small>\" + \"<b>\" + hi_temp_faren + \"</b>\" + \" <b> F </b>\";\n document.getElementById(\"low_temp\").innerHTML = \"<small>Expected Low: </small>\" + \"<b>\" + low_temp_faren + \" </b>\" + \"<b>F </b>\";\n btn.innerHTML = \"Press for celsius\"\n temp = \"celsius\";\n }\n}", "function getColorTemp(temp) {\n//turn the power on, if already on, this will not turn it off\n//Needed because 'set_bright' only works if the bulb is on\n let message;\n if (temp < LOW_TEMP) {\n return \"2700\";\n } else if (temp > HIGH_TEMP) {\n return \"6500\";\n } else {\n let increment = ((6500 - 2700) / (HIGH_TEMP - LOW_TEMP)) || 1;\n return \"\" + (6500 - increment * (temp - LOW_TEMP));\n }\n}", "function displayTemperature(response) {\n let cityElement = document.querySelector(\"#city-name\");\n let humid = response.data.main.humidity;\n let humidityElement = document.querySelector(\"#humidity-read\");\n let precipitation = Math.round(response.data.main.temp);\n let precipitationElement = document.querySelector(\"#precip-read\"); \n let wind = Math.round(response.data.wind.speed);\n let windElement = document.querySelector(\"#wind-read\");\n let feel = Math.round(response.data.main.feels_like);\n let feelElement = document.querySelector(\"#feel-read\");\n let temp = Math.round(response.data.main.temp);\n let temperatureElement = document.querySelector(\"#read-out\");\n let description = response.data.weather[0].main;\n let descriptionElement = document.querySelector(\"#describe-read\");\n let dateElement = document.querySelector(\"#current-data\");\n let visualElement = document.querySelector(\"#representation\");\n \n farenheitTemp = response.data.main.temp;\n\n cityElement.innerHTML = response.data.name;\n humidityElement.innerHTML = `Humidity: ${humid}%`;\n precipitationElement.innerHTML = `Precipitation: ${precipitation}%`;\n windElement.innerHTML = `Wind Speed: ${wind} km/h`;\n feelElement.innerHTML = `It feels like ${feel}°F`;\n temperatureElement.innerHTML = `${temp}°F`;\n descriptionElement.innerHTML = `Currently: ${description}`;\n dateElement.innerHTML = formatDate(response.data.dt * 1000)\n visualElement.setAttribute(\n \"src\",\n `https://openweathermap.org/img/wn/${response.data.weather[0].icon}@2x.png`\n );\n\n getForecast(response.data.coord)\n}", "function showTemp(response) {\n console.log(response);\n let searchCity = document.querySelector(\"#currentCityName\");\n searchCity.innerHTML = response.data.name;\n\n let temperature = Math.round(response.data.main.temp);\n let temperatureElement = document.querySelector(\"#metricT\");\n temperatureElement.innerHTML = `${temperature}˚C`;\n\n let description = document.querySelector(\"#description\");\n description.innerHTML = response.data.weather[0].description;\n\n let maxTemp = document.querySelector(\"#highTemp\");\n maxTemp.innerHTML = `${Math.round(response.data.main.temp_max)}˚C`;\n\n let minTemp = document.querySelector(\"#lowTemp\");\n minTemp.innerHTML = `${Math.round(response.data.main.temp_min)}˚C`;\n\n let feelsLike = document.querySelector(\"#feelsTemp\");\n feelsLike.innerHTML = `${Math.round(response.data.main.feels_like)}˚C`;\n}", "function displayTemperature(response) {\n let temperatureElement = document.querySelector(\"#temperature\");\n let cityElement = document.querySelector(\"#city\");\n let descriptionElement = document.querySelector(\"#description\");\n let humidityElement = document.querySelector(\"#humidity\");\n let windElement = document.querySelector(\"#wind\");\n let dateElement = document.querySelector(\"#date\");\n let iconElement = document.querySelector(\"#icon\");\n\n temperatureElement.innerHTML = Math.round(celsiusTemperature);\n cityElement.innerHTML = response.data.name;\n descriptionElement.innerHTML = response.data.weather[0].description;\n humidityElement.innerHTML = response.data.main.humidity;\n windElement.innerHTML = Math.round(response.data.wind.speed);\n dateElement.innerHTML = formatDate(response.data.dt * 1000);\n iconElement.setAttribute(\n \"src\",\n `http://openweathermap.org/img/wn/${response.data.weather[0].icon}@2x.png`\n );\n iconElement.setAttribute(\"alt\", response.data.weather[0].description);\n\n getForecast(response.data.coord);\n}", "function changeTodaysTempC(data) {\n const todaysTemp = get(\".weather-info-temperature\");\n todaysTemp.textContent = data.main.temp + \" °C\";\n createTodaysIcon(data)\n}", "function showTemp(response){\n //search Temp\n let currentTemp = Math.round(response.data.main.temp);\n let currentCelcius = document.querySelector(\"#degrees\");\n currentCelcius.innerHTML = currentTemp;\n //search Desc\n let descValue = response.data.weather[0].description;\n let currentDesc = document.querySelector(\"#desc\");\n currentDesc.innerHTML = descValue;\n //search Temp Min & Max\n let tempMinValue = Math.round(response.data.main.temp_min);\n let tempMin = document.querySelector(\"#min\");\n tempMin.innerHTML = tempMinValue;\n let tempMaxValue = Math.round(response.data.main.temp_max);\n let tempMax = document.querySelector(\"#max\");\n tempMax.innerHTML = tempMaxValue;\n //change icon\n let iconValue = response.data.weather[0].icon;\n let weatherIcon = document.querySelector(\"#icon\");\n weatherIcon.setAttribute(\"src\", `http://openweathermap.org/img/wn/${iconValue}@2x.png`);\n weatherIcon.setAttribute(\"alt\", response.data.weather[0].description)\n //show info\n //humidity - you asked for precipitation but is not on the API\n let humidityValue = Math.round(response.data.main.humidity);\n let currentHum = document.querySelector(\"#humidity\");\n currentHum.innerHTML = humidityValue;\n //Wind\n let windValue = Math.round(response.data.wind.speed);\n let currentWind = document.querySelector(\"#wind\");\n currentWind.innerHTML = windValue;\n\n celsiusTemp = response.data.main.temp;\n\n getForecast(response.data.coord);\n //Change Background Image\n updateBackgroundImg(iconValue);\n\n}", "function isHot(){\n\t\tconsole.log(temperature_measurement);\n\t\tif((temperature >= 8 && temperature_measurement === \"c\") || (temperature >= 46.4 && temperature_measurement === \"f\")){\n\t\t\t$('table').addClass('glow');\n\t\t}\n\t}", "function showTemperature(response) {\n document.querySelector(\"#city\").innerHTML = response.data.name;\n document.querySelector(\"#currentTemp\").innerHTML = Math.round(\n response.data.main.temp\n );\n}", "function getTemperature(tempUnits){\n $.getJSON(api, function(data){\n if (tempUnits ==\"celsius\"){\n var tempSulfix = \"C\";\n var temp = (data.current.temp_c);\n var feelslike = (data.current.feelslike_c);\n }\n else if (tempUnits == \"farenheit\"){\n var tempSulfix = \"F\";\n var temp = (data.current.temp_f);\n var feelslike = (data.current.feelslike_f);\n }\n document.getElementById(\"pTemp\").innerHTML = temp + \"&deg\" + tempSulfix;\n document.getElementById(\"pFeel\").innerHTML = feelslike + \"&deg\" + tempSulfix;\n });\n }", "function renderDay (data, tog) {\n\ttemp = displayTemp(data.list[0].temp.day, tog);\n\ttempMin = displayTemp(data.list[0].temp.min, tog);\n\ttempMax = displayTemp(data.list[0].temp.max, tog);\n\tdescription = data.list[0].weather[0].description;\n\tdescription = description[0].toUpperCase() + description.substring(1);\n\twind = displaySpeed(data.list[0].speed, tog);\n\ticon = data.list[0].weather[0].icon;\n\tbgURL = switchBG(icon);\n\tcity = data.city.name;\n $(\"#todayTemp\").html(\" \" + description + \"<br />\" + 'Temp: ' + temp + \"<br />\" + 'High/Low: ' + tempMax + \"/\" + tempMin + \"<br />\" + 'Wind: ' + wind);\n\tif (night == 1) {\n\t\t$(\"#todayTemp\").css({\"color\":\"white\", \"background\":\"rgba(255, 255, 255, 0.07)\"})\n\t}\n\tif (night == 0){\n \t$(\"#weatherBG\").prepend('<h1> Today in ' + city + '</h1>');\n\t\t}\n\t\telse {\n\t\t\t$(\"#weatherBG\").prepend('<h2> Tonight in ' + city + '</h2>');\t\n\t\t}\n}", "function formatCelsiusMain(temperature) {\n let mainTemperatureSpace = document.querySelector(\"#temperaturevalue\");\n mainTemperatureSpace.innerHTML = temperature;\n celsiusorfarenheitSpace.innerHTML = \"°C\";\n}", "function showTemp(response) {\n let currentTemp = Math.round(response.data.list[0].main.temp);\n let currentTemperature = document.querySelector(\"#temp\");\n currentTemperature.innerHTML = currentTemp;\n\n let currentHumid = Math.round(response.data.list[0].main.humidity);\n let humidity = document.querySelector(\"#humid\");\n humidity.innerHTML = `${currentHumid}%`;\n\n let currentWind = (response.data.list[0].wind.speed) * 100;\n let windSpeed = document.querySelector(\"#speed\");\n windSpeed.innerHTML = currentWind;\n\n let cityName = response.data.list[0].name;\n let currentCity = document.querySelector(\"#city-name\");\n currentCity.innerHTML = cityName;\n}", "function displayWeather(weatherData) {\n\n //Get City Name and Date\n var cityName = weatherData.city_name;\n var countryID = weatherData.country_code;\n var currentDate = (weatherData.data[0].datetime);\n var cityCountrySrc = cityName + \", \" + countryID\n $(\"#cityMain\").text(cityCountrySrc + \" (\" + currentDate + \")\");\n\n //Weather Icon - Icons stored in repo as \"weatherbit.io\" did not have URL links.\n var iconID = weatherData.data[0].weather.icon;\n var weatherIcon = \"./assets/icons/\" + iconID + \".png\";\n $(\"#iconMain\").attr(\"src\", weatherIcon);\n\n //Current day main display\n $(\"#tempMain\").text(\"Temperature: \" + weatherData.data[0].max_temp + \"\\u2103\");\n $(\"#humdMain\").text(\"Humidity: \" + weatherData.data[0].rh + \"%\");\n $(\"#wsMain\").text(\"Wind Speed: \" + Math.ceil(weatherData.data[0].wind_spd * 3.6) + \" km/h\");\n\n //UV Index Color coding\n var uvIndex = Math.ceil(weatherData.data[0].uv);\n var uvMain = $(\"#uvMain\");\n uvMain.text(\" UV Index: \" + uvIndex + \" \");\n var bgColor = \"background-color\"\n\n if (uvIndex <= 2) {\n uvMain.css(bgColor, \"Green\");\n };\n if ((uvIndex >= 3) && (uvIndex <= 5)) {\n uvMain.css(bgColor, \"gold\");\n };\n if ((uvIndex >= 6) && (uvIndex <= 7)) {\n uvMain.css(bgColor, \"orange\");\n };\n if ((uvIndex >= 8) && (uvIndex <= 10)) {\n uvMain.css(bgColor, \"red\");\n };\n if (uvIndex > 10) {\n uvMain.css(bgColor, \"purple\");\n };\n\n //Weather Data that will populate the 5 day forecast cards run through a for loop.\n for (var i = 1; i < 6; i++) {\n $(\"#date\" + i).text(weatherData.data[i].datetime);\n $(\"#icon\" + i).attr(\"src\", \"./assets/icons/\" + weatherData.data[i].weather.icon + \".png\");\n $(\"#temp\" + i).text(\"Temp: \" + weatherData.data[i].max_temp + \"\\u2103\");\n $(\"#humd\" + i).text(\"Humidity: \" + weatherData.data[i].rh + \"%\");\n }\n }", "function displayWeather(data) {\n changeHero(loc.data.name);\n $('#cityName').text(`${loc.data.name}`)\n $('#cityTemp').text(`${parseInt(data.data.current.temp)}`);\n if (unit == \"imperial\") {\n $('#cityUnit').attr('class', 'icofont-fahrenheit');\n } else {\n $('#cityUnit').attr('class', 'icofont-celsius');\n }\n\n $('.high').each(function(ind, el) {\n $(el).text(`${parseInt(data.data.daily[ind].temp.max)}`);\n });\n\n $('.low').each(function(ind, el) {\n $(el).text(`${parseInt(data.data.daily[ind].temp.min)}`);\n });\n\n $('.day').each(function(ind, el) {\n let newDate = new Date(data.data.daily[ind].dt * 1000);\n let day = newDate.toDateString().slice(0, 3);\n $(el).text(`${day} ${newDate.getDate()}`);\n });\n\n $('.mainWeather').each(function(ind, el) {\n switch (data.data.daily[ind].weather[0].main.trim()) {\n case \"Clouds\":\n $(this).text('Cloudy');\n break;\n case \"Rain\":\n $(this).text('Rainy');\n break;\n case \"Clear\":\n $(this).text('Clear');\n break;\n case \"Snow\":\n $(this).text('Snow');\n break;\n case \"Drizzle\":\n $(this).text('Light Rain');\n break;\n case \"Thunderstorm\":\n $(this).text('Thunderstorms');\n break;\n default:\n $(this).text('Cloudy');\n break;\n }\n });\n\n $('.weatherIcon').each(function(ind, el) {\n switch (data.data.daily[ind].weather[0].main.trim()) {\n case \"Clouds\":\n $(this).attr('class', 'weatherIcon icofont-cloudy');\n break;\n case \"Rain\":\n $(this).attr('class', 'weatherIcon icofont-rainy');\n break;\n case \"Clear\":\n $(this).attr('class', 'weatherIcon icofont-sun');\n break;\n case \"Snow\":\n $(this).attr('class', 'weatherIcon icofont-snow');\n break;\n case \"Drizzle\":\n $(this).attr('class', 'weatherIcon icofont-rainy-sunny');\n break;\n case \"Thunderstorm\":\n $(this).attr('class', 'weatherIcon icofont-rainy-thunder');\n break;\n default:\n $(this).attr('class', 'weatherIcon icofont-clouds');\n break;\n }\n });\n\n $('.desc').each(function(ind, el) {\n $(el).text(`${data.data.daily[ind].weather[0].description.trim()}`);\n });\n\n\n $('.humid').each(function(ind, el) {\n $(el).text(` ${data.data.daily[ind].humidity} %`);\n });\n\n\n $('.uvi').each(function(ind, el) {\n $(el).text(` ${data.data.daily[ind].uvi}`);\n let uv = parseInt(data.data.daily[ind].uvi);\n switch (uv) {\n case 11:\n $(this).parent().attr('class', 'ui label image violet');\n case 8:\n case 9:\n case 10:\n $(this).parent().attr('class', 'ui label image red');\n break;\n case 6:\n case 7:\n $(this).parent().attr('class', 'ui label image orange');\n break;\n case 3:\n case 4:\n case 5:\n $(this).parent().attr('class', 'ui label image yellow');\n break;\n case 0:\n case 1:\n case 2:\n $(this).parent().attr('class', 'ui label image green');\n break;\n }\n });\n\n\n $('.wind').each(function(ind, el) {\n $(el).text(` ${data.data.daily[ind].wind_speed} MPH`);\n });\n\n animateWeather(data.data.current.weather[0].main.trim())\n\n setTimeout(() => {\n $('.segment').dimmer('hide');\n }, 250);\n\n}", "function showTemperature(response) {\n //Select HTML parts, which have to be substitute with the api data:\n let temp = document.querySelector(\".degree\");\n let hum = document.querySelector(\"#local-humidity\");\n let wind = document.querySelector(\"#local-wind\");\n let weatherDescription = document.querySelector(\"#weather-description\");\n let bigWeatherIcon = document.querySelector(\"#big-icon\");\n let cityName = document.querySelector(\"#city-name\");\n\n celsiusTemperature = response.data.main.temp; //you don't need \"let\" because it is already defined in 4.1.1\n\n //Select data from the apiUrl:\n let temperature = Math.round(celsiusTemperature);\n let humidity = response.data.main.humidity;\n let windSpeed = response.data.wind.speed;\n let weatherDescr = response.data.weather[0].description;\n let iconSource = response.data.weather[0].icon;\n let currentCityName = response.data.name;\n console.log(currentCityName);\n\n temp.innerHTML = `${temperature}`;\n hum.innerHTML = `${humidity}`;\n wind.innerHTML = `${windSpeed}`;\n cityName.innerHTML = `${currentCityName}`;\n weatherDescription.innerHTML = `${weatherDescr}`;\n bigWeatherIcon.setAttribute(\n \"src\",\n `http://openweathermap.org/img/wn/${iconSource}@2x.png`\n );\n}", "function displayWeatherData() {\r\n if(weatherData.name && weatherData.sys.country) {\r\n currentLocation.innerHTML = weatherData.name + ', ' + weatherData.sys.country;\r\n };\r\n humidity.innerHTML = 'Humidity: ' + weatherData.main.humidity + ' %';\r\n pressure.innerHTML = 'Pressure: ' + transformFromHpaToMmHg() + ' mm Hg';\r\n temperature.innerHTML = transformFromKelvinToCelsius() + '°';\r\n\r\n var imgUrl = 'http://openweathermap.org/img/wn/' + weatherData.weather[0].icon + '@4x.png';\r\n weatherIcon.innerHTML = '<img src=' + imgUrl + '>';\r\n windDeg = weatherData.wind.deg;\r\n windInfo.innerHTML = 'Wind: ' + transformWindDeg() + ', ' + transformFromKnotsToMeters() + ' m/s';\r\n weatherSummary.innerHTML = weatherData.weather[0].main;\r\n words.value = \"\";\r\n}", "function renderWeatherInformation(data, units) {\n let tempUnit = '°C';\n\n if (units === 'imperial') {\n tempUnit = '°F';\n }\n const weatherDescription = document.querySelector(\n '.weather-info__description'\n );\n weatherDescription.textContent = _utils__WEBPACK_IMPORTED_MODULE_0__.capitalize(\n data.current.weather[0].description\n );\n const city = document.querySelector('.weather-info__city');\n city.textContent = data.name;\n const date = document.querySelector('.weather-info__date');\n date.textContent = _utils__WEBPACK_IMPORTED_MODULE_0__.formatDate(data.current.dt, data.timezone_offset);\n const time = document.querySelector('.weather-info__time');\n time.textContent = _utils__WEBPACK_IMPORTED_MODULE_0__.formatTime(data.current.dt, data.timezone_offset);\n\n const temperature = document.querySelector('.weather-info__temperature');\n temperature.textContent = `${Math.round(data.current.temp)} ${tempUnit}`;\n const temperatureIcon = document.querySelector('.weather-info__icon');\n temperatureIcon.innerHTML = _utils__WEBPACK_IMPORTED_MODULE_0__.getIcon(data.current.weather[0].icon);\n}", "function switchTempUnit() {\r\n temperatureF = (temperatureC * 9 / 5 + 32).toFixed(2);\r\n var whatTemp = $(\"#tempUnit\").html();\r\n var whatTempCode = whatTemp.charCodeAt(0);\r\n $(\"#temp-display\").html(temperatureF);\r\n //If temperature is in celsius\r\n if (whatTempCode === 8451) {\r\n $(\"#temp-switch\").html('Switch to Celsius');\r\n $(\"#tempUnit\").html('&#8457');\r\n $(\"#temp-display\").html(temperatureF);\r\n tempUnit = '&#8457';\r\n tempType = 'imperial';\r\n } else {\r\n $(\"#temp-switch\").html('Switch to Farenheit');\r\n $(\"#tempUnit\").html('&#8451');\r\n $(\"#temp-display\").html(temperatureC);\r\n tempUnit = '&#8451';\r\n tempType = 'metric';\r\n }\r\n }", "function showTemp(response){\n //console.log(response.data);\n let temperature = Math.round(reponse.data.main.temp);\n let temperatureElement = document.querySelector(\"#temperature\");\n temperatureElement.innerHTML = `${response.data.main.temp}°C`;\n}", "function drawKennedyWeather(d) {\n var celcius = Math.round(parseFloat(d.main.temp)-273.15);\n\n document.getElementById('description2').innerHTML = d.weather[0].description;\n document.getElementById('temp2').innerHTML = celcius + '&deg;';\n document.getElementById('location2').innerHTML = d.name;\n}", "paint(weatherData) {\n const tempF = weatherData.main.temp.toFixed(0),\n tempC = Util.tempFtoC(tempF),\n humidity = weatherData.main.humidity,\n dewPointC = Util.getDewPointCelsius(tempC, humidity),\n dewPointF = Util.tempCtoF(dewPointC),\n feelLF = weatherData.main.feels_like.toFixed(0),\n feelLC = Util.tempFtoC(feelLF),\n windDirection = Util.windDirection(weatherData.wind.deg);\n\n this.wLocation.textContent =\n weatherData.name + ', ' + weatherData.sys.country;\n this.wDescription.textContent = weatherData.weather[0].description;\n\n this.wTemp.textContent = tempF + ' F (' + tempC + ' C)';\n this.wIcon.setAttribute(\n 'src',\n `https://openweathermap.org/img/wn/${weatherData.weather[0].icon}@2x.png`\n );\n \n this.wHumidity.textContent = 'Relative Humidity: ' + humidity + '%';\n this.wdewpoint.textContent =\n 'Dewpoint: ' + dewPointF + ' F (' + dewPointC + ' C)';\n this.wFeelLike.textContent =\n 'Feels Like: ' + feelLF + ' F (' + feelLC + ' C)';\n this.wWind.textContent =\n 'Wind: From the ' +\n windDirection +\n ' at ' +\n weatherData.wind.speed +\n ' MPH';\n }", "function weatherDataFahrenheit() {\r\n navigator.geolocation.getCurrentPosition(locationHandler);\r\n function locationHandler(position){\r\n placelat = position.coords.latitude;\r\n placelon = position.coords.longitude;\r\n $.getJSON(\"http://api.openweathermap.org/data/2.5/weather?APPID=c87ae1ce207b86d32f1ac31b319e04ad&lat=\"+placelat+\"&lon=\"+placelon+\"&units=imperial\", function(dataTwo){\r\n placeName = dataTwo.name;\r\n placeTemp = dataTwo.main.temp;\r\n $( \".weather_Location\" ).html( placeName );\r\n $( \".temp_deg\" ).html( Math.round(placeTemp) + \"&nbsp;&deg;F\" );\r\n weatherIcon = dataTwo.weather[0].icon;\r\n switch (weatherIcon) {\r\n case '01d':\r\n iconUrl = 'http://res.cloudinary.com/db6e0gluw/image/upload/v1498754536/1_ee8m7x.png';\r\n backgroundColor = '#ffffcc';\r\n break;\r\n case '02d':\r\n iconUrl = 'http://res.cloudinary.com/db6e0gluw/image/upload/v1498754536/2_snkyrl.png';\r\n backgroundColor = '#ffffcc';\r\n break;\r\n case '03d':\r\n iconUrl = 'http://res.cloudinary.com/db6e0gluw/image/upload/v1498754536/3_wvvsmq.png';\r\n backgroundColor = '#d9d9d9';\r\n break;\r\n case '04d':\r\n iconUrl = 'http://res.cloudinary.com/db6e0gluw/image/upload/v1498754536/3_wvvsmq.png';\r\n backgroundColor = '#d9d9d9';\r\n break;\r\n case '09d':\r\n iconUrl = 'http://res.cloudinary.com/db6e0gluw/image/upload/v1498754536/4_vveyub.png';\r\n backgroundColor = '#b3d9ff';\r\n break;\r\n case '10d':\r\n iconUrl = 'http://res.cloudinary.com/db6e0gluw/image/upload/v1498754536/5_we8jwt.png';\r\n backgroundColor = '#b3d9ff';\r\n break;\r\n case '11d':\r\n iconUrl = 'http://res.cloudinary.com/db6e0gluw/image/upload/v1498754536/6_hkoodr.png';\r\n backgroundColor = '#b3d9ff';\r\n break;\r\n case '13d':\r\n iconUrl = 'http://res.cloudinary.com/db6e0gluw/image/upload/v1498754536/7_ikf9r1.png';\r\n backgroundColor = '#80ccff';\r\n break;\r\n case '50d':\r\n iconUrl = 'http://res.cloudinary.com/db6e0gluw/image/upload/v1498754536/8_pwltiz.png';\r\n backgroundColor = '#d9d9d9';\r\n break;\r\n case '01n':\r\n iconUrl = 'http://res.cloudinary.com/db6e0gluw/image/upload/v1498754536/9_fiq6zz.png';\r\n backgroundColor = '#ffffcc';\r\n break;\r\n case '02n':\r\n iconUrl = 'http://res.cloudinary.com/db6e0gluw/image/upload/v1498754536/10_idcsnl.png';\r\n backgroundColor = '#ffffcc';\r\n break;\r\n case '03n':\r\n iconUrl = 'http://res.cloudinary.com/db6e0gluw/image/upload/v1498754536/3_wvvsmq.png';\r\n backgroundColor = '#d9d9d9';\r\n break;\r\n case '04n':\r\n iconUrl = 'http://res.cloudinary.com/db6e0gluw/image/upload/v1498754536/3_wvvsmq.png';\r\n backgroundColor = '#d9d9d9';\r\n break;\r\n case '09n':\r\n iconUrl = 'http://res.cloudinary.com/db6e0gluw/image/upload/v1498754536/4_vveyub.png';\r\n backgroundColor = '#b3d9ff';\r\n break;\r\n case '10n':\r\n iconUrl = 'http://res.cloudinary.com/db6e0gluw/image/upload/v1498754536/5_we8jwt.png';\r\n backgroundColor = '#b3d9ff';\r\n break;\r\n case '11n':\r\n iconUrl = 'http://res.cloudinary.com/db6e0gluw/image/upload/v1498754536/6_hkoodr.png';\r\n backgroundColor = '#b3d9ff';\r\n break;\r\n case '13n':\r\n iconUrl = 'http://res.cloudinary.com/db6e0gluw/image/upload/v1498754536/7_ikf9r1.png';\r\n backgroundColor = '#80ccff';\r\n break;\r\n case '50n':\r\n iconUrl = 'http://res.cloudinary.com/db6e0gluw/image/upload/v1498754536/8_pwltiz.png';\r\n backgroundColor = '#d9d9d9';\r\n break;\r\n }\r\n $(\".icon\").html(\"<img src='\" + iconUrl + \"'>\");\r\n $(\".main_body\").css(\"background-color\", backgroundColor );\r\n });\r\n }\r\n }", "function displayWeather() {\n locationElement.innerHTML = `${weather.city}, ${weather.country}`; // City/Country name\n iconElement.innerHTML = `<img src=\"icons/${weather.iconId}.png\"/>`; // Icon\n tempElement.innerHTML = `${weather.temperature.value}°<span>F</span>`; // Temp\n descElement.innerHTML = `${weather.description}`; // Short description\n descElementDaily.innerHTML = dailyDescription(); // Daily description\n sunRiseElement.innerHTML = `<span class=\"lightText\">Sunrise</span> <br>${weather.sunrise} AM`; // Sunrise\n sunSetElement.innerHTML = `<span class=\"lightText\">Sunset</span> <br>${weather.sunset} PM`; // Sunset\n windElement.innerHTML = `<span class=\"lightText\">Wind</span> <br>${weather.wind} mph`; // Wind speed\n gustElement.innerHTML = `<span class=\"lightText\">Gust</span> <br>${weather.gust} mph`; // Gust speed\n feelsLikeElement.innerHTML = `<span class=\"lightText\">Feels-like</span> <br>${weather.feels_like} °F`; // Feels-like\n humidityElement.innerHTML = `<span class=\"lightText\">Humidity</span> <br>${weather.humidity}%`; // Humidity \n tempMinElement.innerHTML = `<span class=\"lightText\">Min-temp</span> <br>${weather.temp_min} °F`; // Temp_min\n tempMaxElement.innerHTML = `<span class=\"lightText\">Max-temp</span> <br>${weather.temp_max} °F`; // Temp_max\n}", "function render(data,C){\n var currentWeather = data.weather[0].description;\n var currentTemp = displayTemp(data.main.temp,C);\n var icon = data.weather[0].icon;\n \n $(\"#currentTemp\").html(currentTemp);\n $(\"#currentWeather\").html(currentWeather);\n \n var apiIcon = \"http://openweathermap.org/img/w/01d.png\";\n $(\"#currentTemp\").prepend('<img src=' + apiIcon + '>' );\n }", "function populateCurrent(data) {\n //console.log(data);\n\n // show current data on the index.html\n cityName.text(\"Current City: \" + currentCityPull);\n todayDate.text(\"Today's Date: \" + myDate);\n currentDesc.text(\"Current Conditions: \" + data.current.weather[0].description);\n currentTemp.text(\"Current Temp: \" + data.current.temp + \"F\");\n currentWind.text(\"Current Wind: \" + data.current.wind_speed + \" MPH\");\n currentHumidity.text(\"Current Humidity: \" + data.current.humidity + \"%\");\n currentUiv.text(\"Current UV Index: \" + data.current.uvi)\n\n // This makes the color of the UV Index adjust with the severity \n //TODO How do I add also make the text white with the green and red background\n if (data.current.uvi <= 3.0) {\n $(\"#current-uvi\").css(\"background-color\", \"LightGreen\");\n } else if (data.current.uvi > 3.0 && data.current.uvi < 6.5) {\n $(\"#current-uvi\").css(\"background-color\", \"yellow\");\n } else if (data.current.uvi >= 6.5) {\n $(\"#current-uvi\").css(\"background-color\", \"Red\");\n };\n\n // populate the 5-day forecast\n\n\n\n let forecastDay = data.daily;\n fiveDayList.innerHTML = \"\";\n console.log(forecastDay);\n for (let i = 0; i < 5; i++) {\n //const dailyData = forecastDay[i];\n //console.log(dailyData);\n // console.log(\"date day \" + i + \" \" + data.daily[i].dt);\n // console.log(\"outlook day \" + i + \" \" + data.daily[i].weather[0].description);\n // console.log(\"humid day \" + i + \" \" + data.daily[i].humidity);\n // console.log(\"hi day \" + i + \" \" + data.daily[i].temp.max);\n // console.log(\"low day \" + i + \" \" + data.daily[i].temp.min);\n // console.log(\"wind day \" + i + \" \" + data.daily[i].wind_speed);\n\n\n var card = document.createElement('div');\n var cardDate = document.createElement('h4');\n var cardDesc = document.createElement('p');\n var cardHumid = document.createElement('p');\n var cardTempHi = document.createElement('p');\n var cardTempLo = document.createElement('p');\n var cardWind = document.createElement('p');\n\n function convertFiveDate(data) {\n\n currentDate = data.daily[i].dt\n // from https://www.epochconverter.com/programming/#javascript\n fiveDateFull = new Date(currentDate * 1000);\n console.log(\"5day human date: \" + fiveDateFull);\n //console.log(\"type of: \" + typeof fiveDateFull);\n let fiveDateString = JSON.stringify(fiveDateFull);\n console.log(fiveDateString);\n //console.log(\"string? \" + typeof fiveDateString);\n fiveDate = fiveDateString.substring(1, 11)\n };\n convertFiveDate(data)\n\n cardDate.innerText = fiveDate;\n cardDesc.innerText = data.daily[i].weather[0].description;\n cardHumid.innerText = \"humidity: \" + data.daily[i].humidity;\n cardTempHi.innerText = \"Hi Temp: \" + data.daily[i].temp.max;\n cardTempLo.innerText = \"Lo Temp: \" + data.daily[i].temp.min;\n cardWind.innerText = \"Wind: \" + data.daily[i].wind_speed;\n\n card.append(cardDate);\n card.append(cardDesc);\n card.append(cardHumid);\n card.append(cardTempHi);\n card.append(cardTempLo);\n card.append(cardWind);\n fiveDayList.append(card);\n\n\n };\n}", "function changeTemp() {\n\t\tvar temperature = Math.round(days[document.getElementById(\"slider\").value].\n\t\t\tquerySelector(\"temperature\").textContent);\n\t\tdocument.getElementById(\"currentTemp\").innerHTML = temperature + \"&#8457\";\t\n\t}", "function setDataToDisplay(data) {\n let weatherData = typeof data === \"string\" ? JSON.parse(data) : data;\n let curTemp = parseFloat(weatherData.main.temp - KELVIN_CONST).toFixed(0);\n let minTemp = parseFloat(weatherData.main.temp_min - KELVIN_CONST).toFixed(1);\n let maxTemp = parseFloat(weatherData.main.temp_max - KELVIN_CONST).toFixed(1);\n\n let iconURL =\n \"http://openweathermap.org/img/wn/\" +\n weatherData.weather[0].icon +\n \"@2x.png\";\n setWeatherICON(\n \"display-weather-icon\",\n iconURL,\n weatherData.weather[0].description\n );\n setDynamicValue(\n \"display-city-name\",\n weatherData.name + \", \" + weatherData.sys.country\n );\n setDynamicValue(\"display-date\", getDateFromUNIXtime(weatherData.dt));\n setDynamicValue(\"display-current-temp\", curTemp + \" \" + DEGREE);\n setDynamicValue(\n \"display-temp-min-max\",\n minTemp + \" \" + DEGREE + \"/ \" + maxTemp + \" \" + DEGREE\n );\n setDynamicValue(\n \"display-humidity\",\n weatherData.main.humidity + \" \" + PERCENT\n );\n // setDynamicValue('display-description',weatherData.weather[0].description);\n}", "function displayWeather(data) {\n const { name } = data;\n const { temp } = data.main;\n const { icon, description } = data.weather[0];\n \n cityName.innerText = name;\n temperature.innerText = Math.round(temp) + \"°C\";\n weatherDescription.innerText = description;\n tempIcon.src =\"https://openweathermap.org/img/wn/\"+ icon +\"@2x.png\";\n tempIcon.style.display = \"inline-block\";\n}", "function displayTemp(mainKey, mainValue) {\n if(mainKey == \"temp\") {\n $(\".temp\").html(\"<span id='tempValue'>\" + Math.floor(mainValue + 0.5) + \"</span>&deg;<a id='tempScale' href='#tempScale'>F</a>\");\n fTemp = $(\"#tempValue\").text();\n }\n}", "function drawVandenbergWeather(d) {\n var celcius = Math.round(parseFloat(d.main.temp)-273.15);\n\n document.getElementById('description1').innerHTML = d.weather[0].description;\n document.getElementById('temp1').innerHTML = celcius + '&deg;';\n document.getElementById('location1').innerHTML = d.name;\n}", "changeColor(boiler, Tint, Temp) {\n if (boiler) {\n var T_int = parseFloat(\"\" + Tint);\n var setTemp = parseFloat(\"\" + Temp);\n var diff = setTemp - T_int;\n if (diff > 0) {\n if (diff > 15) {\n this.setState({\n txtTempColor: '#e53935', //red\n });\n } else {\n if (diff > 10) {\n this.setState({\n txtTempColor: '#F57C00', //orange\n });\n } else {\n if (diff > 8) {\n this.setState({\n txtTempColor: '#FFA000', //light orange\n });\n } else {\n if (diff > 4) {\n this.setState({\n txtTempColor: '#FBC02D', //dark yellow\n });\n } else {\n if (diff > 2) {\n this.setState({\n txtTempColor: '#FFEB3B', //yellow\n });\n } else {\n this.setState({\n txtTempColor: '#FFF176', //lime\n });\n }\n }\n }\n }\n }\n } else {\n this.setState({\n txtTempColor: '#4CAF50', //green\n });\n }\n } else {\n this.setState({\n txtTempColor: '#ffffff', //white - boiler OFF\n });\n }\n }", "function init(dataSet) {\n switch (dataSet.weather[0].main) {\n case 'Clouds':\n document.body.style.backgroundImage = \"url('images/clouds.jpg')\";\n break;\n\n case 'Clear':\n document.body.style.backgroundImage = \"url('images/clear.jpg')\";\n break;\n\n case 'Rain':\n case 'Drizzle':\n case 'Mist':\n document.body.style.backgroundImage = \"url('images/rain.jpg')\";\n break;\n\n case 'Thunderstorm':\n document.body.style.backgroundImage = \"url('images/thunderstorm.jpg')\";\n break;\n\n case 'Snow':\n document.body.style.backgroundImage = \"url('images/snow.jpg')\";\n break;\n\n default:\n break;\n }\n\n let weatherType = document.getElementById('weatherType');\n let temperatureElement = document.getElementById('temperature');\n let humidityElement = document.getElementById('humidity');\n let windSpeedElement = document.getElementById('windSpeed');\n\n let weatherIcon = document.getElementById('weatherIcon');\n weatherIcon.src = 'https://openweathermap.org/img/w/' + dataSet.weather[0].icon + '.png';\n // console.log(weatherIcon.src);\n\n let resultsDescription = dataSet.weather[0].description;\n weatherType.innerHTML = resultsDescription.charAt(0).toUpperCase () + resultsDescription.slice(1);\n\n \n temperatureElement.innerHTML = \"<img src='icons/temp.png'/>\" + Math.floor(dataSet.main.temp) + '&#176C';\n windSpeedElement.innerHTML = \"<img src='icons/wind.png'/>\" + Math.floor(dataSet.wind.speed) + ' m/s';\n cityName.innerHTML = dataSet.name;\n humidityElement.innerHTML = \"<img src='icons/humidity.png'/>\" + Math.floor(dataSet.main.humidity) + ' %';\n\n \n\n console.log(dataSet.weather[0].main); // stan pogody\n console.log(dataSet.main.temp + \" \" + String.fromCharCode(176) + \"C\"); // temperatura w stopniach C\n console.log(dataSet);\n}", "function dataHandler(data) {\n dataString = JSON.stringify(data);\n console.log(data.main.temp);\n\n formatTemperature(data.main.temp);\n\n if (data.main.temp && data.sys) {\n // display icon\n if (data.weather) {\n var imgURL = \"http://openweathermap.org/img/w/\" + data.weather[0].icon + \".png\";\n $(\"#weatherImg\").attr(\"src\", imgURL);\n $(\"#weather-text\").html(data.weather[0].description);\n }\n // display wind speed\n if (data.wind) {\n var knots = data.wind.speed * 1.9438445;\n $windText.html(knots.toFixed(1) + \" Knots\");\n }\n }\n}", "function displayCurrentWeather(currentWeather) {\n\n console.log('currentWeather: ', currentWeather);\n\n //variable declarations\n var icon;\n var iconSrc;\n\n //calls returnTime function to convert unix time to mm/dd/yyyy format for display on dashboard\n var time = returnTime(currentWeather.dt);\n\n //displays city and date to first line of dashboard\n $('#city').text(cityState);\n $('#city').append(' ' + '(' + time + ')');\n\n //appends weather icon to first line of dashboard\n icon = currentWeather.weather[0].icon;\n iconSrc = 'https://openweathermap.org/img/wn/' + icon + '@2x.png';\n $('#city').append('<span><img src=\"' + iconSrc + '\" alt=\"sun\" id=\"currentIcon\"></span>');\n\n //displays current temp, humidity, wind speed, and uvi to dashboard\n $('#currentTemp').append(currentWeather.temp + ' &#8457;');\n $('#currentHumidity').append(currentWeather.humidity + '%');\n $('#currentWindSpeed').append(currentWeather.wind_speed + ' MPH');\n uvi.append(currentWeather.uvi);\n \n //conditional to determine the background color of the uvi data based on the current uvi\n if (currentWeather.uvi >= 1 && currentWeather.uvi < 3) {\n uvi.css('background-color', 'green');\n uvi.css('color', 'white');\n } else if (currentWeather.uvi >= 3 && currentWeather.uvi < 6) {\n uvi.css('background-color', 'yellow');\n } else if (currentWeather.uvi >= 6 && currentWeather.uvi < 8) {\n uvi.css('background-color', 'orange');\n uvi.css('color', 'white');\n } else if (currentWeather.uvi >= 8 && currentWeather.uvi < 11) {\n uvi.css('background-color', 'red');\n uvi.css('color', 'white');\n } else if (currentWeather.uvi >= 11) {\n uvi.css('background-color', 'purple');\n uvi.css('color', 'white'); \n }\n\n} //end function displayCurrentWeather", "function displayWeather(data) {\n nyWeather = f2k(data.main.temp);\n // debugger\n $('p.NY-Weather').text(`The weather in New York is ${nyWeather} F`);\n}", "function updateCurrent() {\n // console.dir(document.querySelector('#temp'));\n $('#current-city').html(\"\" + activeCity + \": \" + \"<span>\" + date.format('MMM. Do') + \"<span><img src='\"+ weathData.icon + \"'>\" );\n // console.log(weathData.uv);\n $('#temp').text(weathData.temp + \" °F\");\n $('#hum').text(weathData.hum + \"%\");\n $('#wind').text(weathData.wind + \" MPH\");\n $('#uv').removeClass('yellow red green')\n if (weathData.uv < 3) {\n $('#uv').text(weathData.uv).addClass('green');\n } else if (weathData.uv >= 3 && weathData.uv < 8) {\n $('#uv').text(weathData.uv).addClass('yellow');\n } else if (weathData.uv > 8) {\n $('#uv').text(weathData.uv).addClass('red');\n }\n \n }", "showWeather(weather) {\n this.weatherIcon.src = weather.isRaining ? Raining : Sun;\n this.textNode.nodeValue = weather.temperature + ' ' + Celsius.normalize(); // celsius unicode\n }", "function displayWeather(data, cityInputText){\n if(data.length === 0){\n currentDate.textContent = \"No data for that city :(\";\n return;\n }\n else{\n currentDate.textContent = cityInputText + moment().format(\" MM/DD/YY\");\n var iconUrl = \"http://openweathermap.org/img/wn/\" +data.current.weather[0].icon +\"@2x.png\";\n //http://openweathermap.org/img/wn/[email protected]\n //only need link for img icon\n //console.log(data.current.weather[0].icon);\n var cityTemp = data.current.temp;\n var cityHumidity = data.current.humidity;\n var cityWind = data.current.wind_speed;\n var cityUV = data.current.uvi;\n //clear out previous classname\n currentUVIndex.className = \"\";\n //var uvi = parseInt($(this).attr(\"\"))\n if(cityUV < 3.0){\n //cityUV.innerHTML = (\"class = 'low'\")\n currentUVIndex.className += \"low\";\n }\n if(cityUV > 3 && cityUV < 7){\n currentUVIndex.className += \"moderate\";\n }\n else if(cityUV > 7){\n currentUVIndex.className += \"danger\";\n }\n //console.log(cityTemp);\n \n var currentIcon = document.getElementById(\"icon\");\n currentIcon.src = iconUrl;\n currentTemp.textContent= \"Temp: \" + cityTemp + \" °F\";\n currentHumidity.textContent = \"Humidity \" + cityHumidity + \" %\";\n currentWindSpeed.textContent = \"Wind Speed: \" + cityWind + \" mph\";\n currentUVIndex.textContent = \"UV Index: \" + cityUV;\n }\n}", "function renderWeatherDetails(data, units) {\n let tempUnit = '°C';\n let speedUnit = 'km/h';\n\n if (units === 'imperial') {\n tempUnit = '°F';\n speedUnit = 'mph';\n }\n\n // convert windspeed from meters per second to km/h\n if (units === 'metric') {\n data.current.wind_speed *= 3.6;\n }\n\n const temperatureFeelsLike = document.querySelector('#feels-like');\n temperatureFeelsLike.textContent = `${Math.round(\n data.current.feels_like\n )} ${tempUnit}`;\n\n const humidity = document.querySelector('#humidity');\n humidity.textContent = `${data.current.humidity} %`;\n const chanceOfRain = document.querySelector('#chance-of-rain');\n chanceOfRain.textContent = `${data.daily[0].pop} %`;\n const windSpeed = document.querySelector('#wind-speed');\n // round to 1 decimal place\n windSpeed.textContent = `${\n Math.round(data.current.wind_speed * 10) / 10\n } ${speedUnit}`;\n}", "function farenheitToCelcius(){\n if (tempUnits == \"celsius\"){\n tempUnits = \"farenheit\";\n document.getElementById(\"buttonFC\").innerHTML = \"Temperature in Celcius\";\n }\n else if (tempUnits == \"farenheit\"){\n tempUnits = \"celsius\";\n document.getElementById(\"buttonFC\").innerHTML = \"Temperature in Farenheit\";\n }\n getTemperature(tempUnits);\n }", "function displayUV(latt, longt, appID) {\n\n var uviAPI = \"https://api.openweathermap.org/data/2.5/uvi?lat=\" + latt + \"&lon=\" + longt + \"&APPID=\" + appID;\n\n $.ajax({\n url: uviAPI,\n method: \"GET\"\n }).then(function (uviJSON) {\n var uvi = JSON.stringify(uviJSON);\n var uviObj = JSON.parse(uvi);\n resultUvEl.text(\"UV Index: \");\n uvColor.text(uviObj.value)\n var uvValue = parseInt(uviObj.value);\n if (uvValue < 2) {\n uvColor.css(\"background-color\", \"rgb(34, 151, 34)\")\n } else if (uvValue < 6) {\n uvColor.css(\"background-color\", \"yellow\")\n } else if (uvValue < 8) {\n uvColor.css(\"background-color\", \"orange\")\n } else if (uvValue < 11) {\n uvColor.css(\"background-color\", \"red\")\n } else {\n uvColor.css(\"background-color\", \"#6538708f\")\n }\n });\n}", "function setTempDisplayColor() {\n if (degreesF < 0){\n tempDisplay.style.color = `hsl(250, 100%, 35%)`; // If below 0° set to dark blue\n } else if (degreesF > 100) {\n tempDisplay.style.color = `hsl(350, 100%, 35%)`; // If above 100° set to bright red\n } else {\n tempDisplay.style.color = `hsl(${degreesF + 250}, 100%, 35%)`; // Otherwise vary the hue between blue and red \n }\n }", "function showTemp(response) {\n //obj destructuring\n console.log(response.data);\n const {\n coord: { lat, lon },\n dt,\n main: { temp, temp_min, temp_max, feels_like, humidity },\n name,\n wind: { speed },\n } = response.data;\n\n const { main, description, icon } = response.data.weather[0];\n\n //formate time from value given in response mill secs\n formatDate(dt * 1000);\n\n place.innerHTML = name || city.value;\n cityTemp.textContent = `${temp} ℃`;\n tempDesc.textContent = description;\n\n tempDesc.textContent =\n tempDesc.innerHTML.charAt(0).toUpperCase() + tempDesc.innerHTML.slice(1);\n tempMaxMin.textContent = `${Math.round(temp_min)}℃/${Math.round(\n temp_max\n )}℃ `;\n tempRealFeel.textContent = `Feels Like: ${feels_like}℃`;\n humidityNow.textContent = ` Humidity: ${humidity}% `;\n windSpeedElem.textContent = ` Wind: ${speed} km/h`;\n\n let tempIcon = icon;\n let iconURL = `http://openweathermap.org/img/wn/${tempIcon}@2x.png`;\n //setting def value\n weatherImgElem.setAttribute(\"src\", iconURL);\n weatherImgElem.setAttribute(\"alt\", description);\n\n weatherImgIlus[main] &&\n weatherImgElem.setAttribute(\"src\", weatherImgIlus[main]);\n\n //to display the hourly forecast\n let forecastUrl = `https://api.openweathermap.org/data/2.5/forecast?q=${name}&units=metric&appid=${apiKey}`;\n\n //display hourly(3) weather;\n axios.get(forecastUrl).then(showForeCast);\n\n //get daily wether\n getDailyWeather(lat, lon);\n\n //get hourly forecast\n // getHourlyWeather(lat, lon);\n}", "function renderCurrentWeather(location, temperature, humidity, windSpeed, uv, condition) {\n $(\"#welcome\").css(\"display\", \"none\");\n $(\"#currentWeather, #forecast\").css(\"display\", \"block\");\n $(\"#location\").empty().append(`${location} `);\n let date = moment().format(\"MM\" + \"/\" + \"DD\" + \"/\" + \"YYYY\");\n $(\"#location\").append(`${date} `);\n\n let icon = $(\"<span>\");\n icon.addClass(getIcon(condition));\n $(\"#location\").append(icon);\n\n $(\"#temperature\").empty().append(`${temperature} °F`);\n\n $(\"#humidity\").empty().append(`${humidity}%`);\n\n $(\"#windSpeed\").empty().append(`${windSpeed} MPH`);\n\n let uvWarnings = {\n green: \"* You can safely stay outside using standard daily sun protection: broad spectrum SPF 30+ sunscreen containing zinc, sunglasses, and hat. Don't forget: in winter, reflection off snow can nearly double UV strength.\",\n yellow: \"* Stay in the shade during late morning through mid-afternoon. Wear broad spectrum SPF 30+ sunscreen containing zinc, sunglasses, and hat.\",\n orange: \"* Stay in the shade as much as possible, especially during late morning through mid-afternoon. Wear broad spectrum SPF 30+ sunscreen containing zinc, protective clothing (long-sleeved shirt and pants), sunglasses, and wide-brimmed hat.\",\n red: \"* Extra protection needed. Be careful outside, especially during late morning through mid-afternoon. Stay in the shade as much as possible, especially during late morning through mid-afternoon. Wear broad spectrum SPF 30+ sunscreen containing zinc, protective clothing (long-sleeved shirt and pants), sunglasses, and wide-brimmed hat. Please note: white sand on the beach will reflect UV rays and can double UV exposure.\",\n purple: \"* Extra protection needed. Avoid sun exposure during late morning through mid-afternoon. Unprotected skin and eyes can burn in minutes. Wear broad spectrum SPF 30+ sunscreen containing zinc, protective clothing (like long-sleeves), sunglasses, and wide-brimmed hat. Please note: white sand on the beach will reflect UV rays and can double UV exposure.\"\n }\n\n let warnings = [];\n let uvWarning = $(\"<div>\");\n if (uv < 3) {\n $(\"#uv\").css(\"background-color\", \"green\");\n uvWarning.append(uvWarnings.green);\n }\n else if (uv < 6) {\n $(\"#uv\").css(\"background-color\", \"yellow\");\n uvWarning.append(uvWarnings.yellow);\n }\n else if (uv < 8) {\n $(\"#uv\").css(\"background-color\", \"orange\");\n uvWarning.append(uvWarnings.orange);\n }\n else if (uv < 11) {\n $(\"#uv\").css(\"background-color\", \"red\");\n uvWarning.append(uvWarnings.red);\n }\n else {\n $(\"#uv\").css(\"background-color\", \"purple\");\n uvWarning.append(uvWarnings.purple);\n }\n $(\"#warnings\").empty().append(uvWarning);\n $(\"#uv\").empty().append(uv);\n}", "function renderWeather(data) {\n\tlet timestamp = data[0].dt;\n\tlet date = new Date(timestamp * 1000);\n\n\tlet dayOfWeek = date.toLocaleDateString(undefined, {\n\t\tday: 'numeric',\n\t\tmonth: 'short',\n\t\tyear: 'numeric',\n\t});\n\n\tlet time = new Date(data[1].dt * 1000).toLocaleTimeString(undefined, {\n\t\tday: 'numeric',\n\t\tmonth: 'short',\n\t\thour: '2-digit',\n\t});\n\n\tlet sunrise = new Date(data[0].sunrise * 1000).toLocaleTimeString(undefined, {\n\t\thour: '2-digit',\n\t\tminute: '2-digit',\n\t});\n\n\tlet sunset = new Date(data[0].sunset * 1000).toLocaleTimeString(undefined, {\n\t\thour: '2-digit',\n\t\tminute: '2-digit',\n\t});\n\n\tlet temp = parseInt(data[0].temp.day);\n\tlet feels = parseInt(data[0].feels_like.day);\n\tlet max = parseInt(data[0].temp.max);\n\tlet min = parseInt(data[0].temp.min);\n\tlet rain = parseInt(data[0].pop);\n\tlet wind = parseInt(data[0].wind_speed);\n\tlet description = data[0].weather[0].description;\n\tlet uv = parseInt(data[0].uvi);\n\tlet windDeg;\n\n\tif (data[0].wind_deg > 90 && data[0].wind_deg < 180) {\n\t\twindDeg = 'SE';\n\t} else if (data[0].wind_deg > 180 && data[0].wind_deg < 270) {\n\t\twindDeg = 'SW';\n\t} else if (data[0].wind_deg > 270 && data[0].wind_deg < 360) {\n\t\twindDeg = 'NW';\n\t} else if (data[0].wind_deg < 90) {\n\t\twindDeg = 'NE';\n\t}\n\n\treturn `\n \n <div class=\"front\">\n\n <div class=\"top\">\n <div class=\"week\">${dayOfWeek}.</div>\n </div>\n\n <div class=\"current\">\n <div class=\"icon\">\n <img src=\"https://openweathermap.org/img/wn/${data[0].weather[0].icon}@2x.png\">\n <h1><span>${temp}°C</span></h1>\n </div>\n \n <div class=\"text\">\n <p> Feels Like ${feels}°C</p>\n <p>${description}</p>\n </div>\n </div>\n\n <div class=\"forecast\">\n\n <div class=\"row\">\n <div class=\"left\">Temperature</div>\n <div class=\"right\"> ${max}°C/${min}°C</div>\n </div>\n\n <div class=\"row\">\n <div class=\"left\">Humidity</div>\n <div class=\"right\">${data[0].humidity}%</div>\n </div>\n\n <div class=\"row\">\n <div class=\"left\">Precipitation</div>\n <div class=\"right\">${rain}%</div>\n </div>\n\n <div class=\"row\">\n <div class=\"left\">Pressure</div>\n <div class=\"right\">${data[0].pressure}mbar</div>\n </div>\n\n <div class=\" row\">\n <div class=\"left\">Wind Speed</div>\n <div class=\"right\">${wind}km/h</div>\n </div>\n\n <div class=\" row\">\n <div class=\"left\">Wind Direction</div>\n <div class=\"right\">${data[0].wind_deg}°${windDeg}</div>\n </div>\n\n\n <div class=\"row\">\n <div class=\"left\">Morning</div>\n <div class=\"right\">${data[0].temp.morn}°C</div>\n </div>\n\n <div class=\"row\">\n <div class=\"left\">Sunrise</div>\n <div class=\"right\">${sunrise}</div>\n </div>\n\n <div class=\"last\" id=\"tr\">\n <div class=\"left\">Night</div>\n <div class=\"right\">${data[0].temp.night}°C</div>\n </div>\n\n <div class=\"last\">\n <div class=\"left\">Sunset</div>\n <div class=\"right\">${sunset}</div>\n </div>\n\n </div>\n </div>\n \n </div>`;\n}", "function formatFarenheitMain(temperature) {\n let temperatureSpace = document.querySelector(\"#temperaturevalue\");\n temperatureSpace.innerHTML = temperature;\n celsiusorfarenheitSpace.innerHTML = \"°F\";\n}", "function processWeatherData(data) {\n stock.text = data[0];\n prev_close = data[1];\n TSLA = stock.text;\n console.log(\"TSLA stock is: \" + data[0]);\n console.log(\"TSLA previous close: \" + data[1]);\n if (TSLA > prev_close) {\n stock.style.fill = \"green\";\n } else if (TSLA < prev_close){\n stock.style.fill = \"red\";\n } else {\n stock.style.fill = \"yellow\"; \n }\n}", "function showWeather (response) {\n console.log(response.data);\n\n let temperature = Math.round(response.data.main.temp);\n let wind = (response.data.wind.speed)*2.2;\n let windRounded = Math.round(wind);\n let temperatureElement = document.querySelector(\"#temperature\");\n let humidityElement = document.querySelector(\"#humidity\");\n let windElement = document.querySelector(\"#wind\");\n let weatherDescriptionElement = document.querySelector(\"#weather-description\");\n let iconElement = document.querySelector (\"#weather-icon\");\n let dateElement = document.querySelector (\"#date-today\");\n \n//City Name Entered now comes from API\n let cityName = response.data.name;\n let city = document.querySelector(\"#city-name\")\n city.innerHTML = cityName;\n\n celsiusTemperature = response.data.main.temp; \n // Can use above in let temperature \n\n//Presenting Translated Variables on HTML\n temperatureElement.innerHTML = temperature;\n humidityElement.innerHTML = `Humidity: ${response.data.main.humidity}%`;\n windElement.innerHTML = `Wind: ${windRounded}mph`;\n weatherDescriptionElement.innerHTML = response.data.weather[0].description;\n iconElement.setAttribute(\n \"src\",\n `http://openweathermap.org/img/wn/${response.data.weather[0].icon}@2x.png`);\n dateElement.innerHTML = formatDateAndTime (response.data.dt * 1000);\n}", "function update(){\r\n\r\n // remove elements to avoid too many elements\r\n // on screen\r\n svg.select(\"circle\").remove();\r\n svg.selectAll(\".temperature\").remove();\r\n svg.select(\".title\").remove();\r\n\r\n if (index >= temperatureData.length - 1) {\r\n index = 0;\r\n } else {\r\n index++;\r\n }\r\n\r\n svg.append(\"text\")\r\n .attr(\"x\", width/2)\r\n .attr(\"y\", \"80\")\r\n .attr(\"text-anchor\", \"middle\")\r\n .attr(\"class\", \"title\")\r\n .attr(\"fill-opacity\", 0)\r\n .text(\"US Cities Low Temperature in Feburary\")\r\n .transition(d3.transition().duration(1200))\r\n .attr(\"fill-opacity\", 1);\r\n\r\n svg.append(\"circle\")\r\n .attr(\"cx\", 0)\r\n .attr(\"cy\", height/2)\r\n .attr(\"r\", function(){\r\n var rowOfData = temperatureData[index];\r\n var temperatureOfRow = rowOfData.lowTemp;\r\n var radius = circleSizeScale(temperatureOfRow);\r\n return radius;\r\n })\r\n .attr(\"fill\", function(d){\r\n var rowOfData = temperatureData[index];\r\n // lowTemp is the attribute of the array of objects\r\n // from the dataset\r\n var temperatureOfrow = rowOfData.lowTemp;\r\n // use the linear scale called colorScale\r\n var currentColor = colorScale(temperatureOfrow);\r\n return currentColor;\r\n })\r\n .attr(\"fill-opacity\", 0)\r\n .transition(d3.transition().duration(1000))\r\n .attr(\"fill-opacity\", 1)\r\n .attr(\"cx\", width/2);\r\n\r\n svg.append(\"text\")\r\n .attr(\"x\", 0)\r\n .attr(\"y\", height * 0.75)\r\n .attr(\"class\", \"temperature\")\r\n .attr(\"text-anchor\", \"middle\")\r\n .text(function(d){\r\n var rowOfData = temperatureData[index];\r\n // lowTemp is the attribute of the array of objects\r\n // from the dataset\r\n var cityOfRow = rowOfData.city;\r\n var temperatureOfRow = rowOfData.lowTemp;\r\n var textLabel = cityOfRow + \" Temperature: \" + \r\n temperatureOfRow + \"F\" ;\r\n return textLabel;\r\n })\r\n .attr(\"fill-opacity\", 0)\r\n .transition(d3.transition().duration(1000))\r\n .attr(\"fill-opacity\", 1)\r\n .attr(\"x\", width/2);\r\n\r\n\r\n}", "function currentWeather(data) {\r\n document.getElementById(\"currentweathervalue\").innerHTML = `${Math.round(data.main.temp)}&deg;`;\r\n document.getElementById(\"hightempvalue\").innerHTML = `${Math.round(data.main.temp_max)}&deg;`;\r\n document.getElementById(\"lowtempvalue\").innerHTML= `${Math.round(data.main.temp_min)}&deg`;\r\n document.getElementById(\"humidityvalue\").innerHTML= `${data.main.humidity}%`;\r\n document.getElementById(\"windvalue\").innerHTML= `${Math.round(data.wind.speed)} MPH`;\r\n document.getElementById(\"currentstatus\").innerHTML= `${data.weather[0].main}`\r\n document.getElementById(\"weathericon\").src= `http://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png`\r\n}", "function format_y_tooltip_temp(dataPoint) {\n return \" Temperature: \" + dataPoint.temp + \"\\u00B0\" + \"C\";\n }", "function extractWeather(data){\r\n\tvar tempCels = Math.round(parseFloat(data.main.temp));\r\n\tvar feelsCels = Math.round(parseFloat(data.main.feels_like));\r\n\tvar description = data.weather[0].description;\r\n\tvar icon = data.weather[0].icon;\r\n\tchangeHTML(tempCels, feelsCels, description, icon);\r\n}", "function showWeather(response) {\n document.querySelector(\n \"#city-display\"\n ).innerHTML = `${response.data.name}, ${response.data.sys.country}`;\n\n celsiusTemperature = response.data.main.temp;\n feelsLikeTemperature = response.data.main.feels_like;\n\n let temp = document.querySelector(\"#current-temp\");\n let currentTemp = Math.floor(celsiusTemperature);\n\n let description = document.querySelector(\"#description\");\n let weatherDescription = response.data.weather[0].description;\n\n console.log(weatherDescription);\n\n if (\n weatherDescription === \"scattered clouds\" ||\n \"few clouds\" ||\n \"broken clouds\" ||\n \"overcast clouds\"\n ) {\n document.body.style.backgroundImage = `url(\"images/cloudy.jpg\")`;\n }\n if (weatherDescription === \"clear sky\") {\n document.body.style.backgroundImage = `url(\"images/sunnyday.jpg\")`;\n }\n if (weatherDescription === \"shower rain\" || \"rain\") {\n document.body.style.backgroundImage === `url(\"images/rainy1.jpg\")`;\n }\n if (weatherDescription === \"snow\") {\n document.body.style.backgroundImage = `url(\"images/snowy.jpg\")`;\n }\n if (weatherDescription === \"thunderstorm\") {\n document.body.style.backgroundImage === `url(\"images/stormy.jpg\")`;\n }\n if (weatherDescription === \"mist\") {\n document.body.style.backgroundImage = `url(\"images/misty.jpg\")`;\n }\n\n let feelsLike = document.querySelector(\"#feels-like\");\n let feelsLikeTemp = Math.floor(feelsLikeTemperature);\n\n // let humidity = document.querySelector(\"#humidity\");\n // let showHumidity = response.data.main.humidity;\n\n // let windSpeed = document.querySelector(\"#wind-speed\");\n // let showWindSpeed = Math.floor(response.data.wind.speed);\n\n let max = document.querySelector(\"#high\");\n let min = document.querySelector(\"#low\");\n let high = Math.floor(response.data.main.temp_max);\n let low = Math.floor(response.data.main.temp_min);\n\n temp.innerHTML = `${currentTemp}`;\n description.innerHTML = `${weatherDescription}`;\n feelsLike.innerHTML = `Feels like ${feelsLikeTemp}`;\n // humidity.innerHTML = `Humidity: ${showHumidity}`;\n // windSpeed.innerHTML = `Windspeed: ${showWindSpeed}`;\n max.innerHTML = `${high}`;\n min.innerHTML = ` ${low}`;\n\n let iconElement = document.querySelector(\"#icon\");\n iconElement.innerHTML = response.data.weather[0].icon;\n iconElement.setAttribute(\n \"src\",\n `http://openweathermap.org/img/wn/${response.data.weather[0].icon}@2x.png`\n );\n iconElement.setAttribute(\"alt\", response.data.weather[0].description);\n\n getForecast(response.data.coord);\n}", "function temperature_update(new_value, id, styleX, min, max){\n \tnew_value=Number(new_value);\n \tmax=Number(max);\n \tmin=Number(min);\n \t\n \t\tswitch(styleX) {\n\t\t\tcase \"style1\":\n\t \t\t\t\tRGB=get_color_from_therm(new_value);\n\t \t\t\t\tval=100-get_size_of_value(new_value, min, max);\n\t \t\t\t\tlog_temperatures(\"$('#\"+id+\"-size').attr('height',\"+val+\"'%');\");\n\t \t\t\t\t$(\"#\"+id+\"-color\").css( 'fill', RGB );\n\t \t\t\t\t$(\"#\"+id+\"-size\").attr('height',val+'%');\n\t \t\t\t\t$(\"#\"+id+\"-text\").text(new_value+\" °C\");\n\t \t\t\t\tlog_temperatures(\"set tetx: \"+\"#\"+id+\"-text\");\n\t \t\t\t\t//$(\"#\"+item.name+\"-text\").textContent=\"50\";\n\t \t\t\t\tlog_temperatures(\"New height:\"+val);\n\t \t\t\t\tlog_temperatures(\"Oreginal height:\"+$(\"#\"+id).height());\n\t \t\t\t\tbreak;\n\t\t\tcase \"style2\":\n\t \t\t\t\tRGB=get_color_from_therm(new_value);\n\t \t\t\t\tval_w=get_size_of_value(new_value, min, max);\n\t \t\t\t\tval_h=60-val_w*0.01*50;\n\t \t\t\t\tlog_temperatures(\"$('#\"+id+\"-size').attr('height',\"+val+\"'%');\");\n\t \t\t\t\t$(\"#\"+id+\"-color\").css( 'fill', RGB );\n\t \t\t\t\t$(\"#\"+id+\"-color\").attr('points','0,60 '+val_w+',60 '+val_w+','+val_h);\n\t \t\t\t\t$(\"#\"+id+\"-text\").text(new_value+\" °C\");\n\t \t\t\t\tlog_temperatures(\"set tetx: \"+\"#\"+id+\"-text\");\n\t \t\t\t\t//$(\"#\"+item.name+\"-text\").textContent=\"50\";\n\t \t\t\t\tlog_temperatures(\"New height:\"+val);\n\t \t\t\t\tlog_temperatures(\"Oreginal height:\"+$(\"#\"+id).height());\n\t \t\t\t\tbreak;\t\t\t\t\t\t\t\n\t\t}\n\t}", "function displayWeatherInfo(displayData) {\n tempSpan.textContent = displayData.main.temp + \" °F\";\n windSpan.textContent = displayData.wind.speed + \" MPH\";\n humiditySpan.textContent = displayData.main.humidity + \" %\";\n city.textContent = displayData.name;\n date.textContent = dateDisplay;\n}", "function getTemp(weatherData) {\n var tempKelvin = weatherData;\n // console.log(tempKelvin);\n var degFInt = Math.floor(tempKelvin);\n // console.log(degFInt);\n $temp2.html(degFInt + \"\\u00B0F\");\n}", "function temperatureHandler( event, device, controlId ) {\n var thermostat = $(\"#\" + device.id);\n thermostat.val(device.state); \n\n //udpate the server with data set by remote control\n var data = JSON.stringify(device)\n updateDevice(data);\n\n $( document ).trigger( \"confirmTemperatureEvent\", [ controlId, device.state ] );\n }", "function show(data) {\n // DATE\n document.getElementById('date').innerHTML = data.forecast.forecastday[0].date\n\n // TIME\n let time = (data.location.localtime).split('')\n document.getElementById('temperature-time').innerHTML = 'Updated' + ' ' + (time.slice(11,25).join(''))\n\n // DELHI\n document.getElementById('delhiTemp').innerHTML = data.current.temp_c\n document.getElementById('temperature-comment').innerHTML = data.current.condition.text\n\n // VISIBILITY\n document.getElementById('precipitation-value').innerHTML = (data.current.vis_km) + ' ' + 'km'\n document.getElementById('wind-value').innerHTML = (data.current.wind_kph) + ' ' + 'kph'\n document.getElementById('humidity-value').innerHTML = (data.current.humidity) + ' ' + '%'\n document.getElementById('pressure-value').innerHTML = (data.current.pressure_mb) + ' ' + 'mb'\n \n console.log(data)\n }", "function getColorValue(temp, low, high) {\n // make sure that the temperature doesn't fall out of bounds \n temp = (temp < LOW_TEMP) ? LOW_TEMP : temp;\n temp = (temp > HIGH_TEMP) ? HIGH_TEMP : temp;\n // the (|| 1) is to make sure divisor is not 0\n let divisor = (HIGH_TEMP - LOW_TEMP) || 1;\n let color = low + (temp - LOW_TEMP) * ((high - low) / divisor);\n \n return color;\n}", "function convertTemperature(elem, unit){\n\t\tif(unit == \"fahrenheit\"){\n\t\t\t$.each($('.temp-low, .temp-high, .temp-now'), function(){\n\t\t\t\tvar tempSpan = $(this).find('span:first-child');\n\t\t\t\tvar temp = tempSpan.text();\n\t\t\t\t// Fahrenheit = Celsius * 1.8 + 32\n\t\t\t\tvar convertedTemp = Math.round(parseInt(temp, 10) * 1.8 + 32);\n\t\t\t\ttempSpan.text(convertedTemp);\n\t\t\t\ttempSpan.next('span').html(\"&deg;F\");\n\t\t\t});\n\t\t}\n\t\telse if(unit == \"celsius\"){\n\t\t\t$.each($('.temp-low, .temp-high, .temp-now'), function(){\n\t\t\t\tvar tempSpan = $(this).find('span:first-child');\n\t\t\t\tvar temp = tempSpan.text();\n\t\t\t\t// Celsius = (Fahrenheit - 32) / 1.8\n\t\t\t\tvar convertedTemp = Math.round((parseInt(temp, 10) - 32) / 1.8);\n\t\t\t\ttempSpan.text(convertedTemp);\n\t\t\t\ttempSpan.next('span').html(\"&deg;C\");\n\t\t\t});\n\t\t}\n\n\t\t$('.unit').removeClass('active');\n\t\telem.addClass('active');\n\t}", "function showWeather() {\n document.getElementById(\"summary\").innerHTML = summary;\n document.getElementById(\"temp\").innerHTML = `Temperature ${tempF} F`;\n document.getElementById(\"tempConvert\").classList.add(\"fahrenheit\");\n document.getElementById(\"humidT\").innerHTML = `Humidity: ${humidT.toFixed(0)}%`\n document.getElementById(\"windS\").innerHTML = `Wind Speed: ${windS} mi/h`\n skycons.set(\"icon\", icon)\n skycons.play();\n document.getElementById(\"tempConvert\").classList.remove(\"hidden\")\n}", "function displayWeatherData(data) {\n \n\n const cityName = document.querySelector('#cityName');\n cityName.innerHTML = data.name;\n const weatherIcon = document.createElement('img');\n \n weatherIcon.setAttribute(\"src\", `http://openweathermap.org/img/w/${data.weather[0].icon}.png`);\n weatherIcon.setAttribute('height', '200px');\n weatherIcon.setAttribute('width', '200px');\n const currentDiv = document.querySelector('.current');\n currentDiv.appendChild(weatherIcon);\n \n const temperature = document.querySelector('#temperature');\n temperature.innerHTML = Math.floor((data.main.temp) - 273.15) + '°';\n const windSpeed = document.querySelector('#windSpeed');\n windSpeed.innerHTML = `WIND : ${Math.floor(data.wind.speed)} m/s`;\n \n const description = document.querySelector('#description');\n description.innerHTML = data.weather[0].description;\n\n const sunRise = document.querySelector('#sunRise');\n sunRise.innerHTML = `SUN RISE : ${new Date(data.sys.sunrise * 1000).toLocaleTimeString()}`;\n\n const sunRSet = document.querySelector('#sunSet');\n sunSet.innerHTML = `SUN SET : ${new Date(data.sys.sunset * 1000).toLocaleTimeString()}`;\n\n \n\n//Optional a map showing where the city is located\n getMapCoordinates(data);\n function getMapCoordinates(data) {\n const latlongvalue = `${\n data.coord.lat\n },${\n data.coord.lon\n }`;\n const map_url = `https://maps.google.com/maps?q=${latlongvalue}&hl=es&z=14&amp;output=embed`;\n document.getElementById(\"map\").innerHTML = `<iframe src=\"${map_url}\"></iframe>`;\n }\n\n//Your feature here\n const feelsLike = document.querySelector('#feelsLike');\n feelsLike.innerHTML = `FEELS LIKE : ${Math.floor((data.main.feels_like)- 273.15)}°`;\n \n const tempMaxMin = document.querySelector('#tempMaxMin');\n tempMaxMin.innerHTML = `H : ${Math.floor((data.main.temp_max) - 273.15)}° L : ${Math.floor((data.main.temp_min) - 273.15)}°`;\n\n}", "function setTemp(json) {\n var temp = JSON.stringify(json.weather[0].icon);\n icon = icon.substr(1, icon.length - 2);\n iconUrl = '<img src=http://openweathermap.org/img/w/' + icon + '.png>';\n $('.temperature').html(temp + '° F' + iconUrl);\n}", "function displayWeather() {\n locationElement.textContent = `${weather.city}, ${weather.country}`;\n weatherIconElement.innerHTML = `<img src=\"./icons/${weather.iconID}.svg\" alt=\"icon\">`;\n descElement.textContent = `${weather.description}`;\n tempElement.innerHTML = `${weather.temperature.value}<span>°c</span>`;\n humidityElement.innerHTML = `<img class=\"humidity-icon\" src=\"./extraicons/humidity.svg\" alt=\"humidity\">${weather.humidity}`;\n}", "function drawTemp(obj) {\n let temperature = document.createElement('p');\n let temp = obj.main.temp;\n temp = ((temp - 273.15) * 9 / 5 + 32).toFixed(1);\n temperature.textContent = `Temperature: ${temp} °F`;\n return temperature;\n}", "function displayCurrentWeather(data) {\n //Current Weather\n const currentWeather = Math.round(data.main.temp).toString() + \" \\xB0 F\";\n $(\".current-weather\").prepend(currentWeather);\n\n //Weather Icon\n let iconCode = data.weather[0].icon;\n let iconURL = \"http://openweathermap.org/img/wn/\" + iconCode + \"@2x.png\";\n $(\".wicon\").attr(\"src\", iconURL);\n\n //feels like\n let feelsLike = Math.round(data.main.feels_like).toString() + \" \\xB0 F\";\n $(\".feels-like\").append(\" \" + feelsLike);\n\n //Weather Description\n let weatherDescription = data.weather[0].description;\n $(\".weather-description\").text(weatherDescription);\n\n //Humidity\n let humidity = data.main.humidity;\n $(\".humidity\").append(\" \" + humidity + \"%\");\n\n //Wind\n let wind = data.wind.speed;\n $(\".wind\").append(\" \" + wind + \" mph\");\n\n //Sunrise/Sunset\n let timeZone;\n timeZone = data.timezone;\n\n let sunrise = data.sys.sunrise + timeZone;\n sunrise = convertTimestamptoTime(sunrise);\n sunrise = sunrise.split(\":\").slice(0, 2);\n sunrise = formatTime(sunrise[0], parseInt(sunrise[1]));\n $(\".sunrise\").append(\" \" + sunrise);\n\n let sunset = data.sys.sunset + timeZone;\n sunset = convertTimestamptoTime(sunset);\n sunset = sunset.split(\":\").slice(0, 2);\n sunset = formatTime(sunset[0], parseInt(sunset[1]));\n $(\".sunset\").append(\" \" + sunset);\n}", "function changeUnit() {\n let tempUnit = document.getElementById(\"tempUnit\").innerText;\n if (tempUnit === null) {\n return;\n } else if (tempUnit === \"C\") {\n displayCurrentTemp.innerHTML = homeWeather.tempInFahrenheit + `&#176<span id=\"tempUnit\">F</span>`;\n } else if (tempUnit === \"F\") {\n displayCurrentTemp.innerHTML = homeWeather.tempInCelsius + `&#176<span id=\"tempUnit\">C</span>`;\n }\n}", "function weatherReport(cityData) {\n var cityTemp = $('<p></p>').text(cityData.current.temp);\n $('#temp').append(cityTemp);\n var cityHum = $('<p></p>').text(cityData.current.humidity);\n $('#humidity').append(cityHum);\n var cityWind = $('<p></p>').text(cityData.current.wind_speed);\n $('#wind').append(cityWind);\n var uvIndex = $('<p></p>').text(cityData.current.uvi);\n $('#uv').append(uvIndex);\n\n if (cityData.current.uvi <= 3) {\n $('#color').addClass('favorable');\n } else if (cityData.current.uvi> 3 && cityData.current.uvi < 6) {\n $('#color').addClass('moderate');\n } else {\n $('#color').addClass('severe');\n }\n }", "function assignColor(temp, mesurementStyle){\n\tnewTempLocation = document.getElementById(\"convertedTemp\");\n\n\tif(mesurementStyle === \"C\"){\n\t\tif(temp > 32){\n\t\t\tnewTempLocation.style.backgroundColor = \"red\";\n\t\t}else if(temp < 0){\n\t\t\tnewTempLocation.style.backgroundColor = \"lightblue\";\n\t\t}else{\n\t\t\tnewTempLocation.style.backgroundColor = \"lightgreen\";\n\t\t}\n\t}\n\tif(mesurementStyle === \"F\"){\n\t\tif(temp > 90){\n\t\t\tconsole.log(\"FAHR > 90\");\n\t\t\tnewTempLocation.style.backgroundColor = \"red\";\n\t\t}else if(temp < 32){\n\t\t\tconsole.log(\"FAHR < 32\");\n\t\t\tconsole.log(\"Temp: \", temp);\n\t\t\tnewTempLocation.style.backgroundColor = \"lightblue\";\n\t\t}else{\n\t\t\tconsole.log(\"FAHR 32 - 90\");\n\t\t\tnewTempLocation.style.backgroundColor = \"lightgreen\";\n\t\t}\n\t}\n}", "function showTemp(data){\r\n\tconsole.log(data.temp);\r\n\tCurrentTemp = data.temp;\r\n}", "function showTemp(currentCity, temp) {\n const tempH2 = document.createElement(\"h2\");\n tempH2.innerText = `Current Temperture in ${currentCity}: ${temp}`;\n tempH2.setAttribute(\"id\", \"tempH2\");\n document.body.appendChild(tempH2);\n }", "function showInformation(APIdata){\n //***5*** Get the required DATA from the API\n\n console.log(APIdata);\n\n var currentTemp = Math.round(APIdata.currently.apparentTemperature);\n var currentStat = APIdata.currently.summary\n var minTemp = Math.round(APIdata.daily.data[0].apparentTemperatureMin);\n var maxTemp = Math.round(APIdata.daily.data[0].apparentTemperatureMax);\n var dailyStat = APIdata.daily.data[0].summary;\n var precip = APIdata.daily.data[0].precipProbability;\n var humidity = (APIdata.daily.data[0].humidity * 100) + \" %\"\n\n console.log(minTemp, maxTemp);\n\n $( \"#waiting\" ).remove();\n\n $(\"#tempuratureNow\").text(currentTemp + \"°\");\n $(\"#nowSummary\").text(currentStat);\n\n $(\"#tempuratureMinMax\").text(\"low of \" + minTemp + \"° / high of \" + maxTemp + \"°\");\n $(\"#daySummary\").text(dailyStat);\n\n $(\"#precipitation\").text(precip + \" %\");\n $(\"#humidity\").text(\"Humidity: \" + humidity);\n\n $(\"#main-container\").css(\"display\", \"flex\");\n $(\"#main-container\").addClass(\"animated fadeInDown\");\n\n}", "function renderTemperature(weatherResponse){\n let currentTempFar = convertToFarenheight(weatherResponse.main.temp);\n let feelsLikeTempFar = convertToFarenheight(weatherResponse.main.feels_like);\n let tempMinFar = convertToFarenheight(weatherResponse.main.temp_min);\n let tempMaxFar = convertToFarenheight(weatherResponse.main.temp_max);\n let currentTempCel = convertToCelcius(weatherResponse.main.temp);\n let feelsLikeTempCel = convertToCelcius(weatherResponse.main.feels_like);\n let tempMinCel = convertToCelcius(weatherResponse.main.temp_min);\n let tempMaxCel = convertToCelcius(weatherResponse.main.temp_max);\n $(\".weather\").replaceWith(\n `<section class=\"weather orangeBox\">\n <div class=\"forecast\">\n <img id=\"weather-icon\" src=\"https://openweathermap.org/img/wn/${weatherResponse.weather[0].icon}.png\" alt=\"weather\">\n <p>${weatherResponse.weather[0].description}</p>\n <p>${weatherResponse.main.humidity} % humidity</p>\n </div>\n <div class=\"temp\">\n <p>It's currently ${currentTempFar} °F/ ${currentTempCel} °C</p>\n <p>Feels like ${feelsLikeTempFar} °F / ${feelsLikeTempCel} °C</p>\n <p>High of ${tempMaxFar} °F / ${tempMaxCel} °C and a low of ${tempMinFar} °F/ ${tempMinCel} °C</p>\n <p>${weatherResponse.wind.speed} mph winds</p>\n </div>\n </section>`\n );\n}", "function updateDisplay(weatherData) {\n var currentTemp = weatherData.main.temp;\n var currentHumidity = weatherData.main.humidity;\n var currentImg = 'https://openweathermap.org/img/w/' + weatherData.weather[0].icon + '.png'\n var currentWindSpeed = weatherData.wind.speed;\n var cityName = weatherData.name;\n\n document.getElementById('current-temp').textContent = currentTemp;\n document.getElementById('current-humidity').textContent = currentHumidity;\n document.getElementById('current-img').src = currentImg;\n document.getElementById('current-wind').textContent = currentWindSpeed;\n document.getElementById('current-city').textContent = cityName;\n return\n}", "function displayWeather(){\n iconElement.innerHTML = `<img src=\"icons/${weather.iconId}.png\"/>`;\n tempElement.innerHTML = `<span>Feels like</span> ${weather.temperature.value}°<span>C</span>`;\n descElement.innerHTML = weather.description;\n locationElement.innerHTML = `${weather.city}, ${weather.country}`;\n\n temp_minElement.innerHTML = `Min Temperature: ${weather.temperature.min}°<span>C</span>`;\n temp_maxElement.innerHTML = `Max Temperature: ${weather.temperature.max}°<span>C</span>`;\n humidityElement.innerHTML = `Humidity: ${weather.humidity}%`;\n pressureElement.innerHTML = `Pressure: ${weather.pressure} hpa`;\n windElement.innerHTML = `Wind: ${weather.wind} mph`;\n\n}", "function setText() {\n if (temperature < 10) return <p style={{ color: \"blue\" }}>It's cold ❄️</p>;\n else if (temperature > 30)\n return <p style={{ color: \"red\" }}> It's warm ☀️</p>;\n else return <p style={{ color: \"black\" }}>It's nice 🌼</p>;\n }", "checkWeatherText() {\n\n if ( this.state.description === \"Sunny\" || this.state.description === \"Clear\" ) {\n var root = document.getElementById('root');\n root.setAttribute('style', 'background: linear-gradient(0deg, rgb(249, 245, 148) 50%, #fff 50%)');\n var sun = document.getElementById('sun');\n sun.setAttribute('style', 'opacity: 1');\n var cloud1 = document.getElementById('cloud1');\n cloud1.setAttribute('style', 'opacity: 0');\n var cloud2 = document.getElementById('cloud2');\n cloud2.setAttribute('style', 'opacity: 0');\n var cloud2 = document.getElementById('cloud2');\n cloud2.setAttribute('style', 'opacity: 0');\n var rain = document.getElementById('rain');\n rain.setAttribute('style', 'display: none');\n var snow = document.getElementById('snow');\n snow.setAttribute('style', 'display: none');\n } else if ( this.state.description === \"Partly cloudy\" ) {\n var root = document.getElementById('root');\n root.setAttribute('style', 'background: linear-gradient(0deg, rgb(249, 245, 148) 50%, #fff 50%)');\n var sun = document.getElementById('sun');\n sun.setAttribute('style', 'opacity: 1');\n var cloud1 = document.getElementById('cloud1');\n cloud1.setAttribute('style', 'opacity: 1');\n var cloud2 = document.getElementById('cloud2');\n cloud2.setAttribute('style', 'opacity: 0');\n var rain = document.getElementById('rain');\n rain.setAttribute('style', 'display: none');\n var snow = document.getElementById('snow');\n snow.setAttribute('style', 'display: none');\n } else if ( this.state.description === \"Cloudy\" || this.state.description === \"Overcast\" ) {\n var root = document.getElementById('root');\n root.setAttribute('style', 'background: linear-gradient(0deg, #ebebeb 50%, #fff 50%)');\n var sun = document.getElementById('sun');\n sun.setAttribute('style', 'opacity: 0');\n var cloud1 = document.getElementById('cloud1');\n cloud1.setAttribute('style', 'opacity: 1');\n var cloud2 = document.getElementById('cloud2');\n cloud2.setAttribute('style', 'opacity: 1');\n var rain = document.getElementById('rain');\n rain.setAttribute('style', 'display: none');\n var snow = document.getElementById('snow');\n snow.setAttribute('style', 'display: none');\n } else if ( this.state.description === \"Patchy rain possible\" || this.state.description === \"Patchy light drizzle\"\n || this.state.description === \"Light drizzle\" || this.state.description === \"Patchy light rain\"\n || this.state.description === \"Light rain\" || this.state.description === \"Patchy light drizzle\"\n || this.state.description === \"Moderate rain at times\" || this.state.description === \"Moderate rain\"\n || this.state.description === \"Heavy rain at times\" || this.state.description === \"Heavy rain\"\n || this.state.description === \"Torrential rain shower\" || this.state.description === \"Patchy light rain with thunder\"\n || this.state.description === \"Moderate or heavy rain with thunder\" ) {\n var root = document.getElementById('root');\n root.setAttribute('style', 'background: linear-gradient(0deg, lightblue 50%, #fff 50%)');\n var sun = document.getElementById('sun');\n sun.setAttribute('style', 'opacity: 0');\n var cloud1 = document.getElementById('cloud1');\n cloud1.setAttribute('style', 'opacity: 1');\n var cloud2 = document.getElementById('cloud2');\n cloud2.setAttribute('style', 'opacity: 1');\n var snow = document.getElementById('snow');\n snow.setAttribute('style', 'display: none');\n document.documentElement.style.setProperty('--precipitation', 'lightblue');\n var rain = document.getElementById('rain');\n rain.setAttribute('style', 'opacity: 1');\n } else if ( this.state.description === \"Patchy snow possible\" || this.state.description === \"Blowing snow\"\n || this.state.description === \"Blizzard\" || this.state.description === \"Patchy light snow\"\n || this.state.description === \"Light snow\" || this.state.description === \"Patchy moderate snow\"\n || this.state.description === \"Moderate snow\" || this.state.description === \"Patchy heavy snow\"\n || this.state.description === \"Heavy snow\" || this.state.description === \"Light snow showers\"\n || this.state.description === \"Moderate or heavy snow showers\" || this.state.description === \"atchy light snow with thunder\"\n || this.state.description === \"Moderate or heavy snow with thunder\" ) {\n var root = document.getElementById('root');\n root.setAttribute('style', 'background: linear-gradient(0deg, \t#E8E8E8 50%, #fff 50%)');\n var sun = document.getElementById('sun');\n sun.setAttribute('style', 'opacity: 0');\n var cloud1 = document.getElementById('cloud1');\n cloud1.setAttribute('style', 'opacity: 1');\n var cloud2 = document.getElementById('cloud2');\n cloud2.setAttribute('style', 'opacity: 1');\n var rain = document.getElementById('rain');\n rain.setAttribute('style', 'display: none');\n var snow = document.getElementById('snow');\n snow.setAttribute('style', 'opacity: 1');\n document.documentElement.style.setProperty('--precipitation', '\t#DCDCDC');\n }\n }", "function renderData(allData){\n let avr = getForecast(allData);\n // Display the city name and temperatures for all days\n let cityName = document.getElementById('current-city-name');\n cityName.innerText = allData.city.name.toUpperCase() + ', '+ allData.city.country;\n let iconElement = document.createElement(\"i\");\n iconElement.setAttribute(\"class\",\"far fa-plus-square plus addremove\");\n iconElement.addEventListener('click',plusOnClick,false);\n cityName.appendChild(iconElement);\n document.getElementById('temp').innerHTML = avr[0].temp.toString()+'<span>&deg;C</span>';\n document.getElementById('day2').innerHTML = avr[1].temp.toString()+'<span>&deg;C</span>';\n document.getElementById('day3').innerHTML = avr[2].temp.toString()+'<span>&deg;C</span>';\n document.getElementById('day4').innerHTML = avr[3].temp.toString()+'<span>&deg;C</span>';\n document.getElementById('day5').innerHTML = avr[4].temp.toString()+'<span>&deg;C</span>';\n\n // Loop the loop through which we will display appropriate icons. Icons depend on the weather. Icons come from FontAwesome\n for (let i = 0 ; i < avr.length ; i++){\n let x = document.getElementsByClassName('icon')[i];\n x.className = \"\";\n switch(avr[i].weather.icon.toString()) {\n case '01':\n x.classList.add(\"icon\",\"fa-sun\",\"fas\"); //sun\n break;\n case '02':\n x.classList.add(\"icon\",\"fa-cloud-sun\",\"fas\"); //few clouds\n break;\n case '03':\n x.classList.add(\"icon\",\"fa-cloud\",\"fas\"); //scattered clouds\n break;\n case '04':\n x.classList.add(\"icon\",\"fa-cloud\",\"fas\"); //broken clouds\n break;\n case '09':\n x.classList.add(\"icon\",\"fa-cloud-rain\",\"fas\"); //shower rain\n break;\n case '10':\n x.classList.add(\"icon\",\"fa-cloud-sun-rain\",\"fas\"); //rain\n break;\n case '11':\n x.classList.add(\"icon\",\"fa-bolt\",\"fas\"); //thunderstorm\n break;\n case '13':\n x.classList.add(\"icon\",\"fa-snowflake\",\"fas\"); //snow\n break;\n case '50':\n x.classList.add(\"icon\",\"fa-smog\",\"fas\"); //mist\n break;\n }\n }\n\n //Display maximum and minimum temperature in first day and the humidity.\n document.getElementById('max').innerHTML = 'Max:<br>' + avr[0].temp_max +'<span>&deg;C</span>';\n document.getElementById('min').innerHTML = 'Min:<br> ' + avr[0].temp_min +'<span>&deg;C</span>';\n document.getElementById('humidity').innerText = 'Wilgotność:' + \"\\r\\n\" + avr[0].humidity + '%';\n setVideoBg(avr)\n}", "function showWeather(cityName, data) {\n var dateCurrent = new Date(data.dt *1000);\n var conditions = data.weather[0].main;\n var temperature = data.main.temp;\n var humidity = data.main.humidity;\n var windSpeed = data.wind.speed;\n var currentCity = data.name;\n \n // console.log(temperature);\n iconEl.src =\n \"https://openweathermap.org/img/wn/\" + data.weather[0].icon + \"@2x.png\";\n descriptionEl.textContent = conditions;\n temperatureEl.textContent = temperature + \"°\";\n humidityEl.textContent = humidity + \"%\";\n windSpeedEl.textContent = windSpeed + \" mph\";\n cityEl.textContent = currentCity;\n dateEl.textContent = dateCurrent;\n }", "function displayWeather(response) {\n console.log(response);\n let cityPosition = document.querySelector(\"#city\");\n cityPosition.innerHTML = response.data.name;\n let currentTemp = document.querySelector(\"#currentTemp\");\n let country = document.querySelector(\"#country\");\n let discription = document.querySelector(\"#discription\");\n let humidity = document.querySelector(\"#humidity\");\n let wind = document.querySelector(\"#wind\");\n\n currentTemp.innerHTML = `${Math.round(response.data.main.temp)}°`;\n country.innerHTML = `, ${response.data.sys.country}`;\n discription.innerHTML = response.data.weather[0].description;\n humidity.innerHTML = `${response.data.main.humidity}%`;\n wind.innerHTML = `${Math.round(response.data.wind.speed * 3.6)} km/h`;\n\n //updateing global temperature variable for conversion\n globalTempCelsius = response.data.main.temp;\n\n //icon \n document.querySelector(\"#icon\").innerHTML = `<img src=\"http://openweathermap.org/img/wn/${response.data.weather[0].icon}@2x.png\" width = 90px>`;\n \n // formatting time\n //calculate time difference from UTC at current position \n let localTimestamp = new Date().getTime();\n localOffsetToUTC = new Date().getTimezoneOffset()*60000;\n cityOffsettoUTC = response.data.timezone *1000;\n let timestamp = localTimestamp + localOffsetToUTC + cityOffsettoUTC;\n\n changeTime (timestamp);\n \n}", "function temperatureChanged(obj, greenLed, redLed) {\n var message = new Message(JSON.stringify({\n deviceId: creds.DeviceId, \n temperature: obj.fahrenheit,\n timestamp: new Date(),\n }));\n\n // Send the message\n client.sendEvent(message, function() {\n greenLed.on();\n setTimeout(function() {\n greenLed.off();\n },500);\n });\n\n // Edge processing to see if the temperature is higher than we want\n if (obj.fahrenheit >= alertTemp) {\n redLed.on();\n }\n}", "function displayWeather() {\n document.querySelector('.top').classList.remove('hidden');\n city.textContent = `${weather.city}, ${weather.country}`;\n temp.textContent = Math.round(weather.temperature);\n description.textContent = weather.description;\n icon.innerHTML = `<img src=\"icons/${weather.iconId}.png\" alt=\"Weather Icon\"/>`;\n humidity.textContent = `Humidity: ${weather.humidity} %`;\n feelLike.textContent = `Feels like: ${Math.round(weather.feels_like)} °C`;\n wind.textContent = `Wind: ${Math.round(weather.wind_speed)} m/s`;\n high.textContent = Math.round(weather.temp_high);\n low.textContent = Math.round(weather.temp_low);\n document.querySelector('.credit').classList.remove('hidden');\n const date = new Date(weather.last_updated);\n lastUpdated.textContent = `\n ${date.getHours().toString().padStart('2', '0')} : \n ${date.getMinutes().toString().padStart('2', '0')}`;\n}", "function showWeather(response) {\n let temperature = Math.round(response.data.main.temp);\n let weather = document.querySelector(\"#tempDisplay\");\n weather.innerHTML = `${temperature}°C`;\n let mainCity = document.querySelector(\"h1\");\n mainCity.innerHTML = response.data.name;\n}", "function Temperature({timeStamp, temp, bgColor, className}) {\n\n const date = new Date(timeStamp).toISOString().slice(0, 13);\n\n return (<div className={className}>\n <p>{date}</p>\n <p>{temp}</p>\n </div>);\n}", "function getWeather(location) {\n \n var APIreq;\n if (unit==\"F\"){\n APIreq = \"http://api.openweathermap.org/data/2.5/weather?lat=\" + location.coords.latitude+ \"&lon=\" + location.coords.longitude + \"&APPID=d28f2b67e33e29e7b0c17e04a19ff788&units=imperial\";\n //change buttons to show which unit is selected:\n $(\"#unit1\").css(\"color\", \"black\");\n $(\"#unit1\").css(\"background-color\", \"#d1d3d6\");\n $(\"#unit2\").css(\"color\", \"blue\");\n $(\"#unit2\").css(\"background-color\", \"white\");\n }\n else if(unit==\"C\"){\n APIreq = \"http://api.openweathermap.org/data/2.5/weather?lat=\" + location.coords.latitude+ \"&lon=\" + location.coords.longitude + \"&APPID=d28f2b67e33e29e7b0c17e04a19ff788&units=metric\";\n $(\"#unit2\").css(\"color\", \"black\");\n $(\"#unit2\").css(\"background-color\", \"#d1d3d6\");\n $(\"#unit1\").css(\"color\", \"blue\");\n $(\"#unit1\").css(\"background-color\", \"white\");\n }\n $.getJSON(APIreq,function(weather){\n \tvar weather_data = weather;\n\n \t//collect and format data on sunset and sunrise:\n \tvar sunrise = weather_data[\"sys\"][\"sunrise\"];\n \t//convert UTC time to normal time\n \tvar sunrise_date = new Date(sunrise * 1000);\n \tsunrise = sunrise_date.toLocaleTimeString();\n\n \t//repeat above for sunset:\n \tvar sunset = weather_data[\"sys\"][\"sunset\"];\n \t//convert UTC time to normal time\n \tvar sunset_date = new Date(sunset * 1000);\n \tsunset = sunset_date.toLocaleTimeString();\n\n \t$(\"#sun\").html(\"Today's sunrise is at <span id='sunrise-font'>\" + sunrise + \"</span>, and the sunset is at <span id='sunset-font'>\" + sunset + \"</span>.\");\n \t\n \t//update location name:\n \t$(\"#location\").html(\"You are located in: <span id='city'>\" + weather_data[\"name\"] + \"</span>\");\n\n \t//update temperatures and description:\n \t$(\"#curr_temp\").html(Math.round(weather_data[\"main\"][\"temp\"]) + \"&deg;\");\n \t$(\"#high\").html(\"<b>High: </b>\" + Math.round(weather_data[\"main\"][\"temp_max\"]) + \"&deg;\");\n \t$(\"#low\").html(\"<b>Low: </b> \" + Math.round(weather_data[\"main\"][\"temp_min\"]) + \"&deg;\");\n \t\n \t//format the description:\n \tvar descrip = (weather_data[\"weather\"][\"0\"][\"description\"])[0].toUpperCase() + (weather_data[\"weather\"][\"0\"][\"description\"]).substr(1,);\n \t$(\"#descrip\").html(descrip);\n\n \t//add the icon:\n \t$(\"#icon\").html(\"<img src='http://openweathermap.org/img/w/\" + weather_data[\"weather\"][\"0\"][\"icon\"] + \".png'>\");\n\n \t//humidity, wind and visibility:\n \t$(\"#humidity\").html(\"<b>Humidity:</b> \" + weather_data[\"main\"][\"humidity\"] + \"%\");\n \t$(\"#wind\").html(\"<b>Wind:</b> \" + weather_data[\"wind\"][\"speed\"] + \"m/s at \" + weather_data[\"wind\"][\"deg\"] + \" degrees\");\n \t$(\"#visibility\").html(\"<b>Visibility:</b> \" + weather_data[\"visibility\"] + \" meters\");\n\n $(\"#data\").fadeIn(1000);\n $(\"#location\").fadeIn(1000);\n });\n}" ]
[ "0.67374784", "0.6587126", "0.6560444", "0.6556977", "0.653037", "0.651968", "0.64888483", "0.6462624", "0.6448585", "0.6423811", "0.6419197", "0.64175874", "0.64174104", "0.6394439", "0.6383886", "0.6378228", "0.63521916", "0.63307303", "0.63204944", "0.62951875", "0.6284284", "0.6270368", "0.62665254", "0.6252343", "0.6218121", "0.6195007", "0.61605275", "0.6142695", "0.6141296", "0.61325437", "0.61313534", "0.6127518", "0.61224854", "0.6115235", "0.61140656", "0.6113676", "0.6096482", "0.6092094", "0.608789", "0.6077171", "0.6077078", "0.60720253", "0.60710126", "0.60648704", "0.6056744", "0.604898", "0.60468614", "0.60256815", "0.60249406", "0.60196537", "0.60032266", "0.6002225", "0.5985658", "0.59833384", "0.5976031", "0.5973506", "0.5972526", "0.5966282", "0.59635085", "0.5916187", "0.5912097", "0.58928084", "0.58887184", "0.58795774", "0.58767635", "0.58748454", "0.5862541", "0.5858356", "0.5855892", "0.58544546", "0.58517224", "0.5847395", "0.5847068", "0.58463264", "0.5843365", "0.5841102", "0.58331984", "0.5829527", "0.58122855", "0.58053654", "0.58024", "0.57944226", "0.5792066", "0.57916343", "0.57890165", "0.57873034", "0.5784283", "0.57772374", "0.5765781", "0.5765153", "0.5752361", "0.57488006", "0.574403", "0.5737626", "0.5725553", "0.57251817", "0.5720789", "0.57179916", "0.5713852", "0.57137555" ]
0.6191725
26
handles response data and formats it accordingly since it is an asynchronous response object all data handling and formatting must be done within this function.
function dataHandler(data) { dataString = JSON.stringify(data); console.log(data.main.temp); formatTemperature(data.main.temp); if (data.main.temp && data.sys) { // display icon if (data.weather) { var imgURL = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png"; $("#weatherImg").attr("src", imgURL); $("#weather-text").html(data.weather[0].description); } // display wind speed if (data.wind) { var knots = data.wind.speed * 1.9438445; $windText.html(knots.toFixed(1) + " Knots"); } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async handleResponse () {\n\t\tif (this.gotError) {\n\t\t\treturn super.handleResponse();\n\t\t}\n\n\t\t// return customized response data to New Relic\n\t\tthis.responseData = {\n\t\t\tpost: Utils.ToNewRelic(this.codeError, this.post, this.users)\n\t\t};\n\t\treturn super.handleResponse();\n\t}", "async handleResponse () {\n\t\tif (this.gotError) {\n\t\t\treturn super.handleResponse();\n\t\t}\n\n\t\t// only return a full response if this was the user's first company\n\t\tif (this.transforms.additionalCompanyResponse) {\n\t\t\tthis.log('NOTE: sending additional company response to POST /companies request');\n\t\t\tthis.responseData = this.transforms.additionalCompanyResponse;\n\t\t\tthis.teamId = this.responseData.teamId;\n\t\t\tthis.userId = this.responseData.userId;\n\t\t} else {\n\t\t\tthis.userId = this.user.id;\n\t\t\tif (this.transforms.createdTeam) {\n\t\t\t\tthis.responseData.team = this.transforms.createdTeam.getSanitizedObject({ request: this });\n\t\t\t\tthis.responseData.team.companyMemberCount = 1;\n\t\t\t\tthis.teamId = this.transforms.createdTeam.id;\n\t\t\t}\n\t\t\tif (this.transforms.createdTeamStream) {\n\t\t\t\tthis.responseData.streams = [\n\t\t\t\t\tthis.transforms.createdTeamStream.getSanitizedObject({ request: this })\n\t\t\t\t]\n\t\t\t}\n\t\t\tif (this.transforms.newAccessToken) {\n\t\t\t\tthis.responseData.accessToken = this.transforms.newAccessToken;\n\t\t\t}\n\t\t}\n\n\t\tif (this.transforms.userUpdate) {\n\t\t\tthis.responseData.user = this.transforms.userUpdate;\n\t\t\tif (this.responseData.user.$set) {\n\t\t\t\tdelete this.responseData.user.$set.nrUserInfo;\n\t\t\t}\n\t\t}\n\n\t\tthis.log('NEWRELIC IDP TRACK: CS company was created');\n\t\treturn super.handleResponse();\n\t}", "responseHandler(data) {\n if(this.build) {\n if(data.length + this.curResponse.accumulated > this.curResponse.size) {\n throw new Error('Ending response length did match reported size');\n } else {\n this.curResponse.data = Buffer.concat([this.curResponse.data, data]);\n this.curResponse.accumulated += data.length;\n }\n\n if(this.curResponse.accumulated === this.curResponse.size) {\n this.build = false;\n let correlationMethod = this.getCorrelation(this.curResponse.header.correlationId);\n correlationMethod(null, this.curResponse.data);\n }\n return;\n }\n\n var header, offset, size;\n\n [size, offset] = types.decodeInt32(data, 0);\n\n [header, offset] = parser.decode(Header.response, data, offset);\n\n if(this.requestCount < header.correlationId) {\n return this.onError(new Error('Unknown correlation id received from broker'));\n }\n\n let bufLength = data.length - types.INT32_SIZE;\n if(size !== bufLength) {\n this.build = true;\n this.curResponse = {\n header: header,\n size: size,\n accumulated: bufLength,\n data: data.slice(offset)\n };\n } else {\n this.build = false;\n let correlationMethod = this.getCorrelation(header.correlationId);\n correlationMethod(null, data.slice(offset));\n }\n }", "function processResponse(data) {\n\n if (data.status === constants.PROPERTY_API.status.SUCCESS) {\n showResultsPage(data);\n }\n else if (data.status === constants.PROPERTY_API.status.AMBIGUOUS) {\n showLocationsState(data);\n }\n else { // error\n showErrorState(data);\n }\n }", "handleResponse (responseData) {\n\t\t// put all our deleted objects in the response\n\t\t['posts', 'codemarks', 'reviews', 'codeErrors', 'markers'].forEach(collection => {\n\t\t\tresponseData[collection] = this.transforms[`${collection}Deleted`];\n\t\t});\n\n\t\t// if a parent post, codemark, and/or review were touched, put those in the response\n\t\tif (this.transforms.updatedPost) {\n\t\t\tresponseData.posts.push(this.transforms.updatedPost);\n\t\t}\n\t\tif (this.transforms.updatedGrandParentPost) {\n\t\t\tresponseData.posts.push(this.transforms.updatedGrandParentPost);\n\t\t}\n\t\tif (this.transforms.updatedCodemark) {\n\t\t\tresponseData.codemarks = responseData.codemarks || [];\n\t\t\tresponseData.codemarks.push(this.transforms.updatedCodemark);\n\t\t}\n\t\tif (this.transforms.updatedReview) {\n\t\t\tresponseData.reviews = responseData.reviews || [];\n\t\t\tresponseData.reviews.push(this.transforms.updatedReview);\n\t\t}\n\t\tif (this.transforms.updatedCodeError) {\n\t\t\tresponseData.codeErrors = responseData.codeErrors || [];\n\t\t\tresponseData.codeErrors.push(this.transforms.updatedCodeError);\n\t\t}\n\n\t\t// if any related codemarks were touched, add that to the response\n\t\tif (this.transforms.unrelatedCodemarks) {\n\t\t\tresponseData.codemarks.push(...this.transforms.unrelatedCodemarks);\n\t\t}\n\t}", "handleResponse(dataString) {\n let [activationsData, textData, predData, labels, topNeurons, topNeuronsByCategory] = JSON.parse(dataString);\n this.processData(activationsData, textData, predData, labels, topNeurons, topNeuronsByCategory);\n // trigger query update when data loads to render default query\n this.handleQueryChange(this.state.query);\n // switch from controls page to visualizations page\n this.toggleControls();\n }", "function processResponse(){\n //\n }", "function handleResponse(data) {\n // sections\n var $container = $('.feeds', '#' + data.category),\n feed, $feed, item, $item, id;\n\n // recent list\n var $list_container = $('.recent-list', '#' + data.category),\n $list_grid = $('.list-grid', '#' + data.category);\n\n if (data.success == false) {\n $container.html('ERROR: ' + data.errmsg);\n } else {\n $list_grid.empty();\n $list_grid.append($(tpl_recent({\n type: data.category,\n items: data.list\n })));\n\n $container.empty();\n for (id in data.feeds) {\n feed = data.feeds[id];\n $feed = $(tpl_feed({\n type : data.category,\n title : (data.category == 'contributors') ? feed.author : feed.title,\n items : feed.items\n }));\n $feed.appendTo($container);\n }\n\n // cache that we have retrieved\n cache[data.category] = true;\n }\n }", "function responseReceivedHandler() {\r\n //this function is called when data is received\r\n if (this.status == 200) {\r\n if (this.response.error) {\r\n //put error message\r\n document.querySelector(\"#quotes\").innerHTML = this.response.error;\r\n } \r\n else {\r\n let html = \"<ol>\";\r\n for (let c = 0; c < this.response.length; c++) {\r\n const quote = this.response[c].quote;\r\n const source = this.response[c].source;\r\n html += `<li>${quote} - ${source}</li>`;\r\n }\r\n html += \"</ol>\";\r\n\r\n document.querySelector(\"#quotes\").innerHTML = html;\r\n }\r\n } \r\n}", "function handle_response(data) {\n\tvar line = data.line;\n\t$(\"body\").append(\"<p>\" + line + \"</p>\");\n\n\tif (calculation.length > 0) {\n\t\tline_array = line.split(\" \");\n\t\tsend_request(line_array[line_array.length-1], calculation.shift(), calculation.shift());\n\t}\n}", "function ProcessResponse(data) {\n\n if (data.meta.status !== 200) {\n\n if (force === true) {\n\n BaseMessage();\n DisplayMessage();\n\n }\n\n return;\n }\n\n if (typeof setuptools.tmp.updatecheck === 'undefined') setuptools.tmp.updatecheck = {\n expires: Date.now() + setuptools.config.updatecheckTTL,\n data: data\n };\n\n // head of renders check\n var currentRendersData = rendersVersion.match(setuptools.config.regex.renderscheck);\n var currentRenders = new Date(currentRendersData[1], currentRendersData[2] - 1, currentRendersData[3], currentRendersData[4], currentRendersData[5], currentRendersData[6]);\n var latestRenders = new Date(currentRendersData[1], currentRendersData[2] - 1, currentRendersData[3], currentRendersData[4], currentRendersData[5], currentRendersData[6]);\n var latestRendersName = currentRendersData[7];\n var latestRendersData;\n\n var d = data.data, topver = VERSION, url;\n for (var i = 0; i < d.length; i++) {\n\n // version check\n if (d[i].name.indexOf('renders-') === -1 && cmpver(d[i].name, topver) > 0) {\n topver = d[i].name;\n url = setuptools.config.githubArchive + topver + '.zip';\n }\n\n // middle of renders check\n var rendersData = d[i].name.match(setuptools.config.regex.renderscheck);\n if (typeof rendersData === 'object' && rendersData !== null) {\n\n var newTimestamp = new Date(rendersData[1], rendersData[2] - 1, rendersData[3], rendersData[4], rendersData[5], rendersData[6]);\n if (newTimestamp > latestRenders) {\n latestRenders = newTimestamp;\n latestRendersName = rendersData[7];\n latestRendersData = d[i];\n }\n\n }\n\n }\n\n // tail of renders check\n if (latestRenders > currentRenders) setuptools.app.muledump.notices.add(\n 'New renders update available for ' + latestRendersName,\n function (d, i, rendersData, currentRendersName, latestRendersName) {\n var arg = $.extend(true, [], latestRendersData, rendersData, {\n currentRenders: currentRendersName,\n latestRenders: latestRendersName\n });\n setuptools.app.assistants.rendersupdate(arg);\n },\n [d, i, rendersData, currentRendersData[7], latestRendersName]\n );\n\n // display the lightbox if a url is provided\n window.techlog(\"Update found: \" + url, 'hide');\n\n var notifiedver = setuptools.storage.read('updatecheck-notifier');\n if (url) setuptools.app.muledump.notices.add(\n 'Muledump v' + topver + ' now available!',\n checkupdates,\n true\n );\n\n if (url && (force === true || (!force && options.updatecheck === true && (typeof notifiedver === 'undefined' || (typeof notifiedver === 'string' && cmpver(notifiedver, topver) > 0))))) {\n\n DoDisplayMessage = true;\n setuptools.lightbox.build('muledump-about', ' \\\n <div style=\"width: 100%; border: #ffffff solid 2px; padding: 10px; background-color: #111;\">\\\n Jakcodex/Muledump v' + topver + ' is now available! \\\n <br><br><a download=\"muledump-' + topver + '.zip\" href=\"' + url + '\">' + url + '</a> \\\n </div>\\\n ');\n\n setuptools.storage.write('updatecheck-notifier', topver);\n\n }\n\n if (force === true && !url) {\n\n DoDisplayMessage = true;\n BaseMessage();\n\n }\n\n if (DoDisplayMessage === true) DisplayMessage();\n\n }", "async handleResponse () {\n\t\tif (this.gotError) {\n\t\t\treturn super.handleResponse();\n\t\t}\n\t\tthis.responseData = {\n\t\t\tuser: Object.assign({ id: this.user.id }, this.transforms.userUpdate)\n\t\t};\n\t\tawait super.handleResponse();\n\t}", "function process_response(response) {\n\tif (!response) {\n\t\thandle_error();\n\t\treturn;\n\t}\n\tresponse = JSON.parse(response);\n\tswitch (response.type) {\n\t\tcase \"deleted\":\n\t\t\twindow.location.reload();\n\t\t\tbreak;\n\t\tcase \"requested\":\n\t\t\tclear_divs();\n\t\t\tbreak;\n\t\tcase \"trade\":\n\t\t\tif (response.error) {\n\t\t\t}\n\t\t\telse {\n\t\t\t\tclear_divs();\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"update\":\n\t\t\tupdate_divs(response);\n\t}\n}", "function processResponse() {\n // readyState of 4 signifies request is complete\n if (xhr.readyState == 4) {\n // status of 200 signifies sucessful HTTP call\n if (xhr.status == 200) {\n pageChangeResponseHandler(xhr.responseText);\n }\n }\n }", "function cb (_error, _response, _context) {\n if(_error) {\n callback({errorMessage: _error.message, errorCode: _error.code},null,_context);\n } else if (_response.statusCode >= 200 && _response.statusCode <= 206) {\n var parsed = JSON.parse(_response.body);\n parsed = new GetAClientResponse(parsed);\n callback(null,parsed,_context);\n } else {\n callback({errorMessage: \"HTTP Response Not OK\", errorCode: _response.statusCode, errorResponse: _response.body}, null, _context);\n }\n }", "processGETRequest(response){\n if (response.readyState === 4 && response.status === 200){\n\n let data = '';\n let error = '';\n\n try {\n data = JSON.parse(response.responseText);\n } catch (e){\n this.setState({\n 'failed': true\n })\n error = 'Not JSON';\n }\n\n if (!data.hasOwnProperty('events')){\n this.setState({\n 'failed': true\n })\n\n error = 'No events property';\n }\n\n if (error !== ''){\n console.log(error);\n console.log(response);\n }\n\n this.setState({\n 'dataReceived': true,\n 'data': this.transformEvents(JSON.parse(response.responseText)['events'])\n });\n }\n else if (response.readyState === 4){\n\n console.log('Response status of '+response.status);\n console.log(response);\n\n this.setState({\n 'failed': true\n })\n }\n }", "function HandleResponse(response) {\n if (response.status !== 200) {\n console.log('Looks like there was a problem. Status Code: ' +\n response.status);\n return;\n }\n\n // Examine the text in the response\n response.json().then(function (data) {\n console.log(data);\n });\n}", "function cb (_error, _response, _context) {\r\n if(_error) {\r\n callback({errorMessage: _error.message, errorCode: _error.code},null,_context);\r\n } else if (_response.statusCode >= 200 && _response.statusCode <= 206) {\r\n var parsed = JSON.parse(_response.body);\r\n parsed = new GetSchedulesResponse(parsed);\r\n callback(null,parsed,_context);\r\n } else if (_response.statusCode == 400) {\r\n callback({errorMessage: \"Bad Request\", errorCode: 400, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 401) {\r\n callback({errorMessage: \"Unauthorized/Missing Token\", errorCode: 401, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 403) {\r\n callback({errorMessage: \"Forbidden\", errorCode: 403, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 404) {\r\n callback({errorMessage: \"Not Found\", errorCode: 404, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 500) {\r\n callback({errorMessage: \"Unexpected error\", errorCode: 500, errorResponse:_response.body}, null, _context);\r\n } else {\r\n callback({errorMessage: \"HTTP Response Not OK\", errorCode: _response.statusCode, errorResponse: _response.body}, null, _context);\r\n }\r\n }", "function cb (_error, _response, _context) {\n if(_error) {\n callback({errorMessage: _error.message, errorCode: _error.code},null,_context);\n } else if (_response.statusCode >= 200 && _response.statusCode <= 206) {\n var parsed = JSON.parse(_response.body);\n parsed = new UpdateAClientResponse(parsed);\n callback(null,parsed,_context);\n } else {\n callback({errorMessage: \"HTTP Response Not OK\", errorCode: _response.statusCode, errorResponse: _response.body}, null, _context);\n }\n }", "function parse() {\n if(this.status >= 200 && this.status < 300){\n let parsedData = JSON.parse(this.responseText);\n renderText(parsedData.message);\n } else {\n console.error(\"Invalid status\" + this.status);\n }\n}", "function cb (_error, _response, _context) {\n if(_error) {\n callback({errorMessage: _error.message, errorCode: _error.code},null,_context);\n } else if (_response.statusCode >= 200 && _response.statusCode <= 206) {\n var parsed = JSON.parse(_response.body);\n parsed = new MessageResponse(parsed);\n callback(null,parsed,_context);\n } else if (_response.statusCode == 400) {\n callback({errorMessage: \"Metadata is invalid.\", errorCode: 400, errorResponse:_response.body}, null, _context);\n } else if (_response.statusCode == 429) {\n callback({errorMessage: \"Too many requests.\", errorCode: 429, errorResponse:_response.body}, null, _context);\n } else if (_response.statusCode == 500) {\n callback({errorMessage: \"Unexpected internal error.\", errorCode: 500, errorResponse:_response.body}, null, _context);\n } else {\n callback({errorMessage: \"HTTP Response Not OK\", errorCode: _response.statusCode, errorResponse: _response.body}, null, _context);\n }\n }", "function cb (_error, _response, _context) {\n if(_error) {\n callback({errorMessage: _error.message, errorCode: _error.code},null,_context);\n } else if (_response.statusCode >= 200 && _response.statusCode <= 206) {\n var parsed = JSON.parse(_response.body);\n parsed = new MessageResponse(parsed);\n callback(null,parsed,_context);\n } else if (_response.statusCode == 400) {\n callback({errorMessage: \"Metadata is invalid.\", errorCode: 400, errorResponse:_response.body}, null, _context);\n } else if (_response.statusCode == 429) {\n callback({errorMessage: \"Too many requests.\", errorCode: 429, errorResponse:_response.body}, null, _context);\n } else if (_response.statusCode == 500) {\n callback({errorMessage: \"Unexpected internal error.\", errorCode: 500, errorResponse:_response.body}, null, _context);\n } else {\n callback({errorMessage: \"HTTP Response Not OK\", errorCode: _response.statusCode, errorResponse: _response.body}, null, _context);\n }\n }", "function cb (_error, _response, _context) {\n if(_error) {\n callback({errorMessage: _error.message, errorCode: _error.code},null,_context);\n } else if (_response.statusCode >= 200 && _response.statusCode <= 206) {\n var parsed = JSON.parse(_response.body);\n parsed = new MessageResponse(parsed);\n callback(null,parsed,_context);\n } else if (_response.statusCode == 429) {\n callback({errorMessage: \"Too many requests.\", errorCode: 429, errorResponse:_response.body}, null, _context);\n } else if (_response.statusCode == 500) {\n callback({errorMessage: \"Unexpected internal error.\", errorCode: 500, errorResponse:_response.body}, null, _context);\n } else {\n callback({errorMessage: \"HTTP Response Not OK\", errorCode: _response.statusCode, errorResponse: _response.body}, null, _context);\n }\n }", "function cb (_error, _response, _context) {\n if(_error) {\n callback({errorMessage: _error.message, errorCode: _error.code},null,_context);\n } else if (_response.statusCode >= 200 && _response.statusCode <= 206) {\n var parsed = JSON.parse(_response.body);\n parsed = new MessageResponse(parsed);\n callback(null,parsed,_context);\n } else if (_response.statusCode == 429) {\n callback({errorMessage: \"Too many requests.\", errorCode: 429, errorResponse:_response.body}, null, _context);\n } else if (_response.statusCode == 500) {\n callback({errorMessage: \"Unexpected internal error.\", errorCode: 500, errorResponse:_response.body}, null, _context);\n } else {\n callback({errorMessage: \"HTTP Response Not OK\", errorCode: _response.statusCode, errorResponse: _response.body}, null, _context);\n }\n }", "function cb (_error, _response, _context) {\n if(_error) {\n callback({errorMessage: _error.message, errorCode: _error.code},null,_context);\n } else if (_response.statusCode >= 200 && _response.statusCode <= 206) {\n var parsed = JSON.parse(_response.body);\n parsed = new MessageResponse(parsed);\n callback(null,parsed,_context);\n } else if (_response.statusCode == 429) {\n callback({errorMessage: \"Too many requests.\", errorCode: 429, errorResponse:_response.body}, null, _context);\n } else if (_response.statusCode == 500) {\n callback({errorMessage: \"Unexpected internal error.\", errorCode: 500, errorResponse:_response.body}, null, _context);\n } else {\n callback({errorMessage: \"HTTP Response Not OK\", errorCode: _response.statusCode, errorResponse: _response.body}, null, _context);\n }\n }", "function cb (_error, _response, _context) {\n if(_error) {\n callback({errorMessage: _error.message, errorCode: _error.code},null,_context);\n } else if (_response.statusCode >= 200 && _response.statusCode <= 206) {\n var parsed = JSON.parse(_response.body);\n parsed = new MessageResponse(parsed);\n callback(null,parsed,_context);\n } else if (_response.statusCode == 429) {\n callback({errorMessage: \"Too many requests.\", errorCode: 429, errorResponse:_response.body}, null, _context);\n } else if (_response.statusCode == 500) {\n callback({errorMessage: \"Unexpected internal error.\", errorCode: 500, errorResponse:_response.body}, null, _context);\n } else {\n callback({errorMessage: \"HTTP Response Not OK\", errorCode: _response.statusCode, errorResponse: _response.body}, null, _context);\n }\n }", "function handleResponse(dataId, urlId, xhr) {\n const pre = document.getElementById(dataId);\n const response = xhr.responseText;\n const body = JSON.stringify(JSON.parse(response), null, 4);\n pre.textContent = body;\n const url = document.getElementById(urlId);\n url.textContent = xhr.responseURL;\n }", "function cb (_error, _response, _context) {\n if(_error) {\n callback({errorMessage: _error.message, errorCode: _error.code},null,_context);\n } else if (_response.statusCode >= 200 && _response.statusCode <= 206) {\n var parsed = JSON.parse(_response.body);\n parsed = new Metadata(parsed);\n callback(null,parsed,_context);\n } else if (_response.statusCode == 404) {\n callback({errorMessage: \"Item not found.\", errorCode: 404, errorResponse:_response.body}, null, _context);\n } else if (_response.statusCode == 500) {\n callback({errorMessage: \"Unexpected internal error.\", errorCode: 500, errorResponse:_response.body}, null, _context);\n } else {\n callback({errorMessage: \"HTTP Response Not OK\", errorCode: _response.statusCode, errorResponse: _response.body}, null, _context);\n }\n }", "function responseReceivedHandler() {\n if ( !this.response[ \"error\" ] ) {\n let html = \"<ol>\";\n this.response.forEach( elm => {\n html += `<li>${ elm.quote } - ${ elm.source }</li>`;\n });\n html += \"</ol>\";\n document.querySelector(\"#quotes\").innerHTML = html;\n } else {\n document.querySelector(\"#quotes\").innerHTML = this.response[ \"error\" ];\n }\n}", "AsyncProcessResponse() {\n\n }", "function handleResponse(response) {\n\n var str = '';\n response.on('data', function (chunk) {\n // Add data as it returns.\n str += chunk;\n });\n\n response.on('end', function () {\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Access-Control-Allow-Origin', '*');\n res.end(str);\n\n });\n }", "function handleSuccess( response ) {\n\t\t return( response.data.responseObject);\n\t\t }", "function handleResponse(response) {\n\n var str = '';\n response.on('data', function (chunk) {\n // Add data as it returns.\n str += chunk;\n });\n\n response.on('end', function () {\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Access-Control-Allow-Origin', '*');\n\n res.end(str);\n\n });\n }", "function dataHandler (response) {\n\t// Unauthorized or bad credential\n\tif (response.status === 401) {\n\t\tlocalStorage.removeItem('naledi|token');\n\t\tlogged = false;\n\t\tconsole.log('401: unlogged');\n\t}\n\t// json parse\n\treturn response.json();\n}", "function cb (_error, _response, _context) {\n if(_error) {\n callback({errorMessage: _error.message, errorCode: _error.code},null,_context);\n } else if (_response.statusCode >= 200 && _response.statusCode <= 206) {\n var parsed = JSON.parse(_response.body);\n parsed = new Metadata(parsed);\n callback(null,parsed,_context);\n } else if (_response.statusCode == 404) {\n callback({errorMessage: \"User not found.\", errorCode: 404, errorResponse:_response.body}, null, _context);\n } else if (_response.statusCode == 500) {\n callback({errorMessage: \"Unexpected internal error.\", errorCode: 500, errorResponse:_response.body}, null, _context);\n } else {\n callback({errorMessage: \"HTTP Response Not OK\", errorCode: _response.statusCode, errorResponse: _response.body}, null, _context);\n }\n }", "function cb (_error, _response, _context) {\r\n if(_error) {\r\n callback({errorMessage: _error.message, errorCode: _error.code},null,_context);\r\n } else if (_response.statusCode >= 200 && _response.statusCode <= 206) {\r\n var parsed = JSON.parse(_response.body);\r\n parsed = new CreateScheduleResponse(parsed);\r\n callback(null,parsed,_context);\r\n } else if (_response.statusCode == 400) {\r\n callback({errorMessage: \"Bad Request\", errorCode: 400, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 401) {\r\n callback({errorMessage: \"Unauthorized/Missing Token\", errorCode: 401, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 403) {\r\n callback({errorMessage: \"Forbidden\", errorCode: 403, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 404) {\r\n callback({errorMessage: \"Not Found\", errorCode: 404, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 422) {\r\n callback({errorMessage: \"Unprocessable Entity\", errorCode: 422, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 500) {\r\n callback({errorMessage: \"Unexpected error\", errorCode: 500, errorResponse:_response.body}, null, _context);\r\n } else {\r\n callback({errorMessage: \"HTTP Response Not OK\", errorCode: _response.statusCode, errorResponse: _response.body}, null, _context);\r\n }\r\n }", "function cb(error,response,body){\n\n parseData(body);\n}", "function handleSharpResponse(err, data, info) {\n logger.info(\"Handling Sharp Response\")\n return new Promise((resolve, reject) => {\n if (err) {\n reject(err)\n } else {\n //pushing output image data from \"data\" into \"info\" json \n //info json also contains some information about image like format, size which are useful while sending response to client\n info.data = data\n resolve(info);\n }//end if-else\n })//end Promise\n}//end handleSharpResponse", "function cb (_error, _response, _context) {\n if(_error) {\n callback({errorMessage: _error.message, errorCode: _error.code},null,_context);\n } else if (_response.statusCode >= 200 && _response.statusCode <= 206) {\n var parsed = JSON.parse(_response.body);\n parsed = new ItemsResponse(parsed);\n callback(null,parsed,_context);\n } else if (_response.statusCode == 429) {\n callback({errorMessage: \"Too many requests.\", errorCode: 429, errorResponse:_response.body}, null, _context);\n } else if (_response.statusCode == 500) {\n callback({errorMessage: \"Unexpected internal error.\", errorCode: 500, errorResponse:_response.body}, null, _context);\n } else {\n callback({errorMessage: \"HTTP Response Not OK\", errorCode: _response.statusCode, errorResponse: _response.body}, null, _context);\n }\n }", "function handleResponse(response) {\n var data = response.data;\n var statusCode = response.status;\n \n /* Set an error message and class on request failure or on receiving invalid data */\n var errorMessage = null;\n var errorClass = undefined;\n if (statusCode < 200 || statusCode >= 400) {\n var serverErrorMessage = data && data[\"error-message\"] || response.statusText;\n if (serverErrorMessage) {\n errorMessage = serverErrorMessage;\n } else {\n errorMessage = \"Network error (status \" + statusCode + \")\";\n errorClass = wrm.core.NetworkError;\n }\n } else {\n if (!data) {\n errorMessage = \"Received malformed response from back-end\";\n } else {\n if (options.validator && !options.validator(data)) {\n errorMessage = \"Received invalid response from back-end\";\n }\n }\n }\n \n /* If there was a problem, return an appropriate error object or throw an appropriate error */\n if (errorMessage || errorClass) {\n var errorResult = errorClass || options.errors && options.errors[statusCode];\n if (errorResult === undefined) {\n errorResult = Error;\n }\n if (typeof errorResult !== \"function\") {\n return errorResult;\n }\n throw new errorResult(errorMessage || \"\");\n }\n \n /* Transform the result data */\n if (options.transformer) {\n data = options.transformer(data, response.headers());\n }\n \n return data;\n }", "function responseFn() {\n if (req.readyState === 4) {\n try {\n // Success response\n if (req.status >= 200 && req.status < 400) {\n resolve({\n data: JSON.parse(req.responseText),\n status: req.status,\n config: Object.assign({}, opts)\n });\n } else {\n reject({\n error: req.responseText,\n status: req.status,\n config: Object.assign({}, opts)\n });\n }\n } catch (e) {\n // Error response\n reject({\n error: e,\n status: req.status,\n config: Object.assign({}, opts)\n });\n } \n }\n }", "static response(response, status, msgCode, message, data) {\n data = data || {};\n const dat = {\n code: status,\n date: DateHelper.now(),\n message,\n msgCode,\n data,\n };\n\n response.status(status).json(dat);\n }", "function processTransactionResponse(arg0) {\n\n var bc = arg0.badcookie || false,\n ioResponseObj = arg0.resp,\n responseData = arg0.responseData,\n cb = arg0.cb,\n txId = arg0.id,\n status = ioResponseObj.status,\n rd = '',\n r = ERROR,\n responseText,\n contentType;\n\n // TODO: What about 304 (Not changed) ?\n if (status !== 200 && status !== 201 && status !== OK) {\n\n // Y.log('Error response received from server.', 'warn', NAME);\n // this is an error case\n // server failure single '=' just in case we get a '200' string\n if (status === 0) {\n r = (ioResponseObj.statusText === E_TIMEOUT) ?\n E_TIMEOUT :\n E_ABORT;\n } else {\n rd = E_SERVER;\n _errorReporter.error(E_SERVER, 'A server error occurred: ',\n { responseObject: ioResponseObj });\n }\n\n completeRequest.call(this, {\n txId: txId,\n method: FAILURE_CB,\n result: r,\n resultDetail: rd + ' ' + status,\n cb: cb\n });\n } else {\n //not an error\n // Y.log('Valid response received, processing...', 'warn', NAME);\n\n responseText = ioResponseObj.responseText;\n contentType = ioResponseObj.getResponseHeader('Content-Type');\n\n // Test here is faster than regex.\n if (contentType.indexOf('Multipart/Related') !== -1) {\n reportUnsupportedOperation('multi-part response');\n completeRequest.call(this, {\n cb: cb,\n method: FAILURE_CB,\n result: ERROR,\n resultDetail: E_RESULT_BADFORMAT\n });\n return;\n }\n\n _responseProcessor.processResponse(responseData.resps[0],\n { cb: cb }, bc);\n }\n }", "function cb (_error, _response, _context) {\r\n if(_error) {\r\n callback({errorMessage: _error.message, errorCode: _error.code},null,_context);\r\n } else if (_response.statusCode >= 200 && _response.statusCode <= 206) {\r\n var parsed = JSON.parse(_response.body);\r\n parsed = new GetScheduleByIdResponse(parsed);\r\n callback(null,parsed,_context);\r\n } else if (_response.statusCode == 400) {\r\n callback({errorMessage: \"Bad Request\", errorCode: 400, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 401) {\r\n callback({errorMessage: \"Unauthorized/Missing Token\", errorCode: 401, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 403) {\r\n callback({errorMessage: \"Forbidden\", errorCode: 403, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 404) {\r\n callback({errorMessage: \"Not Found\", errorCode: 404, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 410) {\r\n callback({errorMessage: \"Gone\", errorCode: 410, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 500) {\r\n callback({errorMessage: \"Unexpected error\", errorCode: 500, errorResponse:_response.body}, null, _context);\r\n } else {\r\n callback({errorMessage: \"HTTP Response Not OK\", errorCode: _response.statusCode, errorResponse: _response.body}, null, _context);\r\n }\r\n }", "handleResponse(response){\n this.#addTransactionToView(response.transaction);\n console.log(response) //TODO Continue\n }", "function parseResponse(resp) {\n hideStatus();\n return '';\n }", "function handleSuccess( response ) {\n return( response.data );\n }", "function handleSuccess( response ) {\n return( response.data );\n }", "function callbackResult(res,data){\n\n\t\tconsole.log(\"final response >>>>>\");\n\t//Preparing error if any error case\n\t//var error = prepareError();\n\t//var result = responseWrapper(data,error);\n\n\tvar result = responseWrapper(data);\n\n\treturn res.json(result);\n\t\n}", "function Mesibo_onHttpResponse(mod, cbdata, response, datalen) {\n\tvar rp_log = \" ----- Recieved http response ----\";\n\tmesibo_log(mod, rp_log, rp_log.length);\n\tmesibo_log(mod, response, datalen);\n\n\tp = JSON.parse(cbdata);\n\tmesibo_log(mod, rp_log, rp_log.length);\n\n\treturn MESIBO_RESULT_OK;\n}", "function handleResponse(resp) {\n // console.log(resp)\n if (resp.data.error) {\n for (let err in resp.data.error) {\n $(`#${err}-err`).append(`<p>${resp.data.error[err]}</p>`)\n }\n }\n else {\n $(\"#lucky-results\").append(`<p>Your lucky number is ${resp.data.num.num} (${resp.data.num.fact})</p>`)\n $(\"#lucky-results\").append(`<p>Your birth year is ${resp.data.year.year} (${resp.data.year.fact})</p>`)\n }\n}", "function handleSuccess( response ) {\n return( response.data.responseObject);\n }", "function handleSuccess( response ) {\n return( response.data );\n }", "function processResponse(){\n for(var key in returnData){\n\n //collecting the data in ref to identifier\n var data = returnData[key+\"\"];\n\n //Splitting up the values to send through\n //to load images\n var newData = data.split(\",\");\n var img = newData[0];\n var panoVal = newData[1];\n var title = newData[2];\n var Direction = newData[3];\n\n if (Direction != \"\" && DirectionCount%2 == 1 || subCount == 5) {\n //Appending journey to the planner\n $( \"#journ\" ).append( \"<div id='pathDirection'>\"+ getIcon(Direction)+\" \"+ Direction +\"<div>\" );\n };\n\n if (subCount > 1) {\n //show preloader\n $('#journeyForm').hide();\n $('.pre-circle').show(0).delay(300).hide(0).promise().then(function(){\n $('.hide').delay(300).show('slow');\n $('#journ').delay(300).show('slow');\n subCount = 0;\n });\n // $('#journ').show(0).delay(500);\n };\n\n //Load the image into the overlay\n loadImage(img,panoVal,title);\n }\n\n }", "function processResponse (response) {\n // if not a 2xx response, cb with error\n if (!response.ok) {\n const message = `response ${response.status} from GET ${url}`\n return cb(new Error(message))\n }\n\n // process the body of the response, cb with error on error\n response.json().then(cbWithData).catch(cb)\n }", "function handleSuccess( response ) {\n return( response.data );\n }", "function handleSuccess( response ) {\n return( response.data );\n }", "function handleSuccess( response ) {\n return( response.data );\n }", "function handleResponse(){\n\tif((request.status == 200)&&(request.readyState == 4)){\n\t\tvar jsonString = request.responseText;\n\t\treceiveJSON(jsonString);\n\t}\n}", "_resolveResponseData() {\n return ( !this._options.type || this._options.type === 'text' ) ? this._xhr.responseText : this._xhr.response;\n }", "function cb (_error, _response, _context) {\r\n if(_error) {\r\n callback({errorMessage: _error.message, errorCode: _error.code},null,_context);\r\n } else if (_response.statusCode >= 200 && _response.statusCode <= 206) {\r\n var parsed = JSON.parse(_response.body);\r\n parsed = new CreateScheduleTimeWindowResponse(parsed);\r\n callback(null,parsed,_context);\r\n } else if (_response.statusCode == 400) {\r\n callback({errorMessage: \"Bad Request\", errorCode: 400, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 401) {\r\n callback({errorMessage: \"Unauthorized/Missing Token\", errorCode: 401, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 403) {\r\n callback({errorMessage: \"Forbidden\", errorCode: 403, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 404) {\r\n callback({errorMessage: \"Not Found\", errorCode: 404, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 422) {\r\n callback({errorMessage: \"Unprocessable Entity\", errorCode: 422, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 500) {\r\n callback({errorMessage: \"Unexpected error\", errorCode: 500, errorResponse:_response.body}, null, _context);\r\n } else {\r\n callback({errorMessage: \"HTTP Response Not OK\", errorCode: _response.statusCode, errorResponse: _response.body}, null, _context);\r\n }\r\n }", "function getDataCallback(response, status, headers, config) {\n return response.data;\n }", "function cb (_error, _response, _context) {\n if(_error) {\n callback({errorMessage: _error.message, errorCode: _error.code},null,_context);\n } else if (_response.statusCode >= 200 && _response.statusCode <= 206) {\n var parsed = JSON.parse(_response.body);\n parsed = new UsersResponse(parsed);\n callback(null,parsed,_context);\n } else if (_response.statusCode == 429) {\n callback({errorMessage: \"Too many requests.\", errorCode: 429, errorResponse:_response.body}, null, _context);\n } else if (_response.statusCode == 500) {\n callback({errorMessage: \"Unexpected internal error.\", errorCode: 500, errorResponse:_response.body}, null, _context);\n } else {\n callback({errorMessage: \"HTTP Response Not OK\", errorCode: _response.statusCode, errorResponse: _response.body}, null, _context);\n }\n }", "function handleSuccess( response ) {\n\n return( response.data );\n\n }", "function handleSuccess( response ) {\n\n return( response.data );\n\n }", "function handleSuccess( response ) {\n\n return( response.data );\n\n }", "function handleSuccess( response ) {\n\n return( response.data );\n\n }", "function parseFetchResponse (data) {\n if (data.data) {\n sampleDataManager.setSampleData(data.data)\n }\n return data\n }", "function handleResponse(response) {\n\n console.log('HANDLE LOAD HIDE CALLED');\n\n Loading.hide();\n if (response.status === 204) {\n // Loading.hide();\n return '';\n } else if (response.status === 404) {\n // Loading.hide();\n return null;\n } else if (response.status === 400) {\n // Loading.hide();\n // return null;\n } else {\n // console.log('RESPONSETIME: ', response.data);\n // Loading.hide();\n return response.data;\n }\n\n}", "function handleResponse() {\n\n\t/*\n\t * xhr.readyState\n\t *\n\t * Value Constant (W3C) Description\n\t * -------------------------------------------------------------------\n\t * 0 UNSENT open() has not been called yet.\n\t * 1 OPENED send() has not been called yet.\n\t * 2 HEADERS_RECEIVED send() has been called, and headers\n\t * and status are available.\n\t * 3 LOADING Downloading; responseText holds partial data.\n\t * 4 DONE The operation is complete.\n\t */\n\n\tif (xhr.readyState !== 4 && xhr.readyState !== 3) {\n\t\treturn;\n\t}\n\n\t// the server returned error\n\t// try ... catch block is to work around bug in IE8\n\ttry {\n\t\tif (xhr.readyState === 3 && xhr.status !== 200) {\n\t\t\treturn;\n\t\t}\n\t} catch (e) {\n\t\treturn;\n\t}\n\tif (xhr.readyState === 4 && xhr.status !== 200) {\n\t\thandleError(xhr);\n\t\treturn;\n\t}\n\n\t// In konqueror xhr.responseText is sometimes null here...\n\tif (xhr.responseText === null) {\n\t\treturn;\n\t}\n\n\t// in case we were called before finished processing\n\tif (inProgress) {\n\t\treturn;\n\t} else {\n\t\tinProgress = true;\n\t}\n\n\t// extract new whole (complete) lines, and process them\n\twhile (xhr.prevDataLength !== xhr.responseText.length) {\n\t\tif (xhr.readyState === 4 &&\n\t\t xhr.prevDataLength === xhr.responseText.length) {\n\t\t\tbreak;\n\t\t}\n\n\t\txhr.prevDataLength = xhr.responseText.length;\n\t\tvar unprocessed = xhr.responseText.substring(xhr.nextReadPos);\n\t\txhr.nextReadPos = processData(unprocessed, xhr.nextReadPos);\n\t} // end while\n\n\t// did we finish work?\n\tif (xhr.readyState === 4 &&\n\t xhr.prevDataLength === xhr.responseText.length) {\n\t\tresponseLoaded(xhr);\n\t}\n\n\tinProgress = false;\n}", "function beautifyResponse () {\n var responseText,\n responseLanguage;\n _.forEach($('.formatted-responses'), function (responseDiv) {\n responseDiv = $(responseDiv);\n responseText = responseDiv.text();\n responseLanguage = responseDiv.attr('data-lang');\n try {\n responseText = JSON.parse(responseText);\n responseText = JSON.stringify(responseText, null, 2);\n }\n catch (e) {\n }\n populateSnippet(responseDiv, responseText, responseLanguage);\n });\n}", "function response(event)\n{\n if ( event.data instanceof ArrayBuffer ) {\n responseArrayBuffer(event.data);\n }\n else if ( typeof(event.data) == 'string' ) {\n responseString(event.data);\n }\n else {\n console.log(\"Unhandled response type: \" + typeof(event.data));\n }\n}", "function cb (_error, _response, _context) {\n if(_error) {\n callback({errorMessage: _error.message, errorCode: _error.code},null,_context);\n } else if (_response.statusCode >= 200 && _response.statusCode <= 206) {\n var parsed = JSON.parse(_response.body);\n parsed = parsed.map(function(model){\n return new RetrieveAListOfAllClientsResponse(model);\n });\n callback(null,parsed,_context);\n } else {\n callback({errorMessage: \"HTTP Response Not OK\", errorCode: _response.statusCode, errorResponse: _response.body}, null, _context);\n }\n }", "function handleSuccess( response ) {\n\n return response.data;\n }", "function parseData( asyncRequest )\n{\n // if request has completed successfully process the response\n if ( asyncRequest.readyState == 4 && asyncRequest.status == 200 )\n { \n // convert the JSON string to an Object\n var data = JSON.parse(asyncRequest.responseText); \n displayNames( data ); // display data on the page\n } // end if\n} // end function parseData", "mutateResponse(responseData, response) {\n return response;\n }", "function response(err, data) {\n if (err) {\n console.err(err);\n }\n showText(data[0].label);\n}", "function cb (_error, _response, _context) {\r\n if(_error) {\r\n callback({errorMessage: _error.message, errorCode: _error.code},null,_context);\r\n } else if (_response.statusCode >= 200 && _response.statusCode <= 206) {\r\n var parsed = JSON.parse(_response.body);\r\n parsed = new UpdateScheduleTimeWindowByIdResponse(parsed);\r\n callback(null,parsed,_context);\r\n } else if (_response.statusCode == 400) {\r\n callback({errorMessage: \"Bad Request\", errorCode: 400, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 401) {\r\n callback({errorMessage: \"Unauthorized/Missing Token\", errorCode: 401, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 403) {\r\n callback({errorMessage: \"Forbidden\", errorCode: 403, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 404) {\r\n callback({errorMessage: \"Not Found\", errorCode: 404, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 422) {\r\n callback({errorMessage: \"Unprocessable Entity\", errorCode: 422, errorResponse:_response.body}, null, _context);\r\n } else if (_response.statusCode == 500) {\r\n callback({errorMessage: \"Unexpected error\", errorCode: 500, errorResponse:_response.body}, null, _context);\r\n } else {\r\n callback({errorMessage: \"HTTP Response Not OK\", errorCode: _response.statusCode, errorResponse: _response.body}, null, _context);\r\n }\r\n }", "function extractResponse() {\n // parse user login name, add it to the html\n setLoginName(validUserNameJason.login);\n // create html for repositories, pass repos url api and number of repositories\n setRepositories(validUserNameJason.repos_url, validUserNameJason.public_repos);\n // create html for followers repositories, pass followers url api and number of followers\n setFollowers(validUserNameJason.followers_url, validUserNameJason.followers);\n // show the user info html the was generated from the response\n let userSection = document.getElementById(\"userInfo\");\n showElement(userSection);\n }", "function parse_response_body(data) {\n\tvar response = {'headers':{}, 'body':''};\n\tpass(split(/\\n\\n/, \"\"+data, 2)).on(function(headers, body) {\n\t\tforeach(headers.split(\"\\n\")).do(function(line) {\n\t\t\tpass(split(/: */, \"\"+line, 2)).on(function(name, value) {\n\t\t\t\tresponse.headers[(\"\"+name).toLowerCase()] = value;\n\t\t\t});\n\t\t});\n\t\tif (body) {\n\t\t\tresponse.body = body;\n\t\t}\n\t});\n\treturn response;\n}", "async function formatTrackingResponse(response) {\n\n return {\n trackingNumber: response.trackingNumber,\n deliveryDateTime: response.deliveryDate,\n packages: [\n {\n packaging: {\n id: \"03318192-3e6c-475f-a496-a4f17c1dbcae\",\n description: response.packages[0].description,\n requiresWeight: true,\n requiresDimensions: false\n },\n dimensions: {\n length: response.packages[0].length,\n width: response.packages[0].width,\n height: response.packages[0].height,\n unit: response.packages[0].dimUnit,\n },\n weight: {\n value: response.packages[0].weight,\n unit: response.packages[0].weightUnit,\n }\n }\n ],\n events: [\n {\n name: response.trackingEvents[0].description,\n dateTime: response.deliveryDate,\n status: mapStatusCodes(response.trackingEvents[0].statusCode),\n isError: (response.trackingEvents[0].length == 0 ? false : true),\n code: response.trackingEvents[0].statusCode,\n description: response.trackingEvents[0].description,\n address: {\n company: response.trackingEvents[0].companyName,\n addressLines: [response.trackingEvents[0].addressLine1],\n cityLocality: response.trackingEvents[0].city,\n stateProvince: response.trackingEvents[0].state,\n postalCode: response.trackingEvents[0].zip,\n country: response.trackingEvents[0].country,\n isResidential: (response.trackingEvents[0].addressType == \"residential\" ? true : false)\n },\n signer: {\n title: response.signedBy.salutation,\n given: response.signedBy.firstName,\n middle: response.signedBy.middleName,\n family: response.signedBy.lastName,\n suffix: response.signedBy.suffix\n },\n notes: response.notes,\n }\n ]\n }\n}", "function handleSuccess( response ) {\n return( response.data );\n }", "_onResponse(msg) {\n let _this = this;\n\n let event = {\n type: msg.type,\n url: msg.body.source,\n code: msg.body.code\n };\n\n if (_this._onResponseHandler) {\n _this._onResponseHandler(event);\n }\n }", "function processBodyAndResponse(){\n console.log('Received : ', data)\n res.end('Received and Done')\n }", "function handleResponse(res) {\n // Handle errors\n if (res.error) {\n // Log if not cancellation\n if (!Crisp.isCancel(res.error)) {\n // TODO\n console.error(res.error);\n }\n return;\n }\n\n // Handle payload\n showProducts(res.payload);\n }", "function handleResponse(bookListObj) {\n\tvar bookList = bookListObj.items;\n\n\t/* where to put the data on the Web page */ \n\tvar bookDisplay = document.getElementById(\"bookDisplay\");\n\n\t/* write each title as a new paragraph */\n\tfor (i=0; i<bookList.length; i++) {\n\t\tvar book = bookList[i];\n\t\tvar title = book.volumeInfo.title;\n\t\tvar titlePgh = document.createElement(\"p\");\n\t\t/* ALWAYS AVOID using the innerHTML property */\n\t\ttitlePgh.textContent = title;\n\t\tbookDisplay.append(titlePgh);\n\t}\t\n}", "function cb (_error, _response, _context) {\n if(_error) {\n callback({errorMessage: _error.message, errorCode: _error.code},null,_context);\n } else if (_response.statusCode >= 200 && _response.statusCode <= 206) {\n var parsed = JSON.parse(_response.body);\n parsed = new BulkPostResponse(parsed);\n callback(null,parsed,_context);\n } else if (_response.statusCode == 400) {\n callback({errorMessage: \"Body is missing.\", errorCode: 400, errorResponse:_response.body}, null, _context);\n } else if (_response.statusCode == 429) {\n callback({errorMessage: \"Too many requests.\", errorCode: 429, errorResponse:_response.body}, null, _context);\n } else if (_response.statusCode == 500) {\n callback({errorMessage: \"Unexpected internal error.\", errorCode: 500, errorResponse:_response.body}, null, _context);\n } else {\n callback({errorMessage: \"HTTP Response Not OK\", errorCode: _response.statusCode, errorResponse: _response.body}, null, _context);\n }\n }", "function cb (_error, _response, _context) {\n if(_error) {\n callback({errorMessage: _error.message, errorCode: _error.code},null,_context);\n } else if (_response.statusCode >= 200 && _response.statusCode <= 206) {\n var parsed = JSON.parse(_response.body);\n parsed = new BulkPostResponse(parsed);\n callback(null,parsed,_context);\n } else if (_response.statusCode == 400) {\n callback({errorMessage: \"Body is missing.\", errorCode: 400, errorResponse:_response.body}, null, _context);\n } else if (_response.statusCode == 429) {\n callback({errorMessage: \"Too many requests.\", errorCode: 429, errorResponse:_response.body}, null, _context);\n } else if (_response.statusCode == 500) {\n callback({errorMessage: \"Unexpected internal error.\", errorCode: 500, errorResponse:_response.body}, null, _context);\n } else {\n callback({errorMessage: \"HTTP Response Not OK\", errorCode: _response.statusCode, errorResponse: _response.body}, null, _context);\n }\n }", "function processData(responseData) {\n const showDataHtml = responseData.resultsPage.results.event.map(function(obj) {\n return generateHTML(obj);\n }).join('');\n\n $('#results').html(showDataHtml);\n $('#results').prepend(generateTableHeader());\n}", "function handleResponse(response) {\n console.log('Handling the response.');\n\n // response.text() returns a Promise, because the response is a stream of\n // content and not a simple variable.\n const textPromise = response.text();\n\n // When the response is converted to text, pass the result into the\n // addDataToDom() function.\n textPromise.then(addDataToDom);\n}", "function handleResponse(response) {\n console.log('Handling the response.');\n\n // response.text() returns a Promise, because the response is a stream of\n // content and not a simple variable.\n const textPromise = response.text();\n\n // When the response is converted to text, pass the result into the\n // addQuoteToDom() function.\n textPromise.then(addQuoteToDom);\n}", "function handleSuccess(response) {\n return response.data;\n }", "_onControlSocketData(chunk) {\n this.log(`< ${chunk}`);\n // This chunk might complete an earlier partial response.\n const completeResponse = this._partialResponse + chunk;\n const parsed = (0, parseControlResponse_1.parseControlResponse)(completeResponse);\n // Remember any incomplete remainder.\n this._partialResponse = parsed.rest;\n // Each response group is passed along individually.\n for (const message of parsed.messages) {\n const code = parseInt(message.substr(0, 3), 10);\n const response = { code, message };\n const err = code >= 400 ? new FTPError(response) : undefined;\n this._passToHandler(err ? err : response);\n }\n }", "function transformResponse(data) {\n return data;\n }", "function handleResponse (rows) {\n \n if (params.format === 'json') {\n \n // send as an array of json objects\n var apiRes = {};\n apiRes.account = account;\n apiRes.startTime = range.start.format();\n apiRes.endTime = range.end.format();\n apiRes.timeIncrement = params.timeIncrement;\n apiRes.results = [];\n \n if (viewOpts.reduce === false) {\n \n rows.forEach(function(d){\n apiRes.results.push({\n time : moment.utc(d.value[1]).format(),\n type : d.value[0],\n txHash : d.value[2],\n ledgerIndex : parseInt(d.id, 10)\n });\n });\n \n } else if (params.timeIncrement) {\n rows.forEach(function(d){\n d.value.time = moment.utc(d.key.slice(1)).format();\n apiRes.results.push(d.value); \n }); \n \n } else {\n apiRes.results = rows[0] ? rows[0].value : {};\n }\n \n return callback(null, apiRes);\n \n } else {\n var data = [], keys = {}, nKeys = 0;\n \n if (viewOpts.reduce === false) {\n data.push([\"time\",\"type\",\"txHash\",\"ledgerIndex\"]);\n \n for (var i=0; i<rows.length; i++) {\n data.push([\n moment.utc(rows[i].value[1]).format(), \n rows[i].value[0], //type\n rows[i].value[2], //tx_hash\n parseInt(rows[i].id, 10) //ledger_index\n ]);\n }\n \n } else {\n \n rows.forEach(function(row){\n\n for (var key in row.value) {\n if (typeof keys[key] === 'undefined') keys[key] = nKeys++;\n }\n });\n \n rows.forEach(function(row) {\n var r = [];\n \n for (var j in keys) {\n r[keys[j]] = row.value[j] || 0;\n }\n \n r.unshift(row.key ? moment.utc(row.key.slice(1)).format() : range.start.format());\n data.push(r);\n });\n \n data.unshift([\"time\"].concat(_.keys(keys)));\n }\n \n \n if (params.format === 'csv') {\n\n var csvStr = _.map(data, function(row){\n return row.join(', ');\n }).join('\\n');\n \n // provide output as CSV\n return callback(null, csvStr);\n\n\n } else {\n //no format or incorrect format specified\n return callback(null, data); \n } \n } \n }", "function handleResponse(response) {\n // console.log(response.text());\n return response.text().then(text => {\n // console.log((JSON.parse(text).polls).find(x => x.creator == \"5c489f668665512ec004db37\"))\n const data = text && JSON.parse(text);\n if (!response.ok) {\n const error = (data && data.message) || response.statusText;\n console.log(error);\n return Promise.reject(error);\n }\n return data;\n });\n}", "dataParser(data) {\n console.log(\"Je commence fini\");\n for (var i = 0; i < data.results; i++) {\n this.responses[i] = data.response[i];\n this.tabInt[i] = i;\n }\n }", "function handleResponseData(cardsData) {\n\n // recupero il codice html dal template HANDLEBARS\n var cardTemplate = $('#music-card-template').html();\n\n // compilo il template HANDLEBARS, lui mi restituisce un funzione\n var cardFunction = Handlebars.compile(cardTemplate);\n\n // ciclo su tutto l'array composto dai dati ricevuti dal server\n for (var i = 0; i < cardsData.length; i++) {\n\n // creo un oggetto con i dati da inserire nella singola card\n var context = {\n 'author': cardsData[i].author,\n 'genre': cardsData[i].genre,\n 'poster': cardsData[i].poster,\n 'title': cardsData[i].title,\n 'year': cardsData[i].year\n };\n\n // chiamo la funzione generata da HANDLEBARS per popolare il template\n // passo alla funzione l'oggetto che contiene i valori che andranno a sostituire i placeholder,\n var card = cardFunction(context);\n\n // aggiungo nella mia pagina il codice HTML generato da HANDLEBARS\n $('.cards-container').append(card);\n\n } // end for\n}", "function fetchDataCallback(data) {\n document.getElementById(\"response\").innerHTML = data.content;\n}", "function responseHandler(srcResponse, numer)\n{\n camz[numer].headers = srcResponse.headers;\n srcResponse.on('data', function(chunk) {dataHandler(chunk, numer)});\n}", "function loadResponse() {\n var status = getStatusCode()\n var error = errorFromStatusCode(status)\n var response = {\n body: getBody(),\n statusCode: status,\n statusText: xhr.statusText,\n raw: xhr\n }\n if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE\n response.headers = parseHeaders(xhr.getAllResponseHeaders())\n } else {\n response.headers = {}\n }\n\n callback(error, response, response.body)\n }" ]
[ "0.6804455", "0.67501444", "0.6715168", "0.6626038", "0.66049457", "0.6534635", "0.6480883", "0.6446233", "0.64378303", "0.641549", "0.6364803", "0.63436383", "0.6339988", "0.62782764", "0.62723976", "0.6267327", "0.62149894", "0.621362", "0.61977434", "0.619102", "0.61782974", "0.61782974", "0.6163135", "0.6163135", "0.6163135", "0.6163135", "0.61379707", "0.613427", "0.61243427", "0.610003", "0.6098186", "0.60773605", "0.6075933", "0.60712385", "0.6050614", "0.6046821", "0.6045135", "0.5998608", "0.59904945", "0.5971603", "0.5970538", "0.59473664", "0.5942105", "0.5940684", "0.594059", "0.5920622", "0.59145725", "0.59145725", "0.5906896", "0.59007716", "0.5899173", "0.5898841", "0.58927035", "0.58810747", "0.5867894", "0.58497494", "0.58497494", "0.58497494", "0.5843285", "0.5841011", "0.58398783", "0.5830291", "0.58285415", "0.58228344", "0.58228344", "0.58228344", "0.5822827", "0.58186394", "0.581707", "0.5817059", "0.580609", "0.58025396", "0.57940555", "0.57846725", "0.5775204", "0.57709885", "0.5767251", "0.57628983", "0.5760044", "0.57568365", "0.5752653", "0.5752039", "0.5738559", "0.5735929", "0.57356584", "0.57226056", "0.57168794", "0.57168794", "0.5710402", "0.5708255", "0.57044476", "0.56973505", "0.5696962", "0.5684841", "0.56833124", "0.56789106", "0.56771094", "0.56753665", "0.56749386", "0.56620467", "0.5655908" ]
0.0
-1
This calls the api with the correct coordinates provided by the getLocation function
function getWeather(locdata) { console.log("getWeather has been called.") var lat = locdata.lat; var lon = locdata.lon; var apiURI = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&appid=6c788c55fe75c1f415d3cfdc814d0218"; if (locdata){ console.log("success"); $("#city-text").html(locdata.city + ", " + locdata.region); } else { console.log("fail"); } //call weather api for weather data console.log("success getWeather"); console.log(apiURI); return $.ajax({ url: apiURI, dataType: "json", type: "GET", async: "true", }).done(dataHandler); // display location name }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "updateLocation() {\n this.api.exec('getLocation');\n }", "function getLocation() {\n var currentLon = \"\";\n var currentLat = \"lat=\";\n if (navigator.geolocation) {\n navigator.geolocation.getCurrentPosition(function(loc) {\n //set currentLon & currentLat\n currentLon += loc.coords.longitude;\n currentLat += loc.coords.latitude;\n //fucntions called built on longitude and latitude location\n buildApi(currentLon, currentLat);\n //drawCoords(currentLon, currentLat);\n });\n } else {\n alert(\"You're lost and we can't find you.\");\n }\n }", "function getLocation() {\n\n navigator.geolocation.getCurrentPosition(success, fail);\n\n async function success(position) {\n let key = \"Q6NBLIK5NWGiVhHZwd4vZyiw4A1IgD9Z\";\n let lng = position.coords.longitude;\n let lat = position.coords.latitude;\n console.log(position)\n let address = await fetch(`http://open.mapquestapi.com/geocoding/v1/reverse?key=${key}&location=${lat},${lng}&includeRoadMetadata=true&includeNearestIntersection=true`)\n\n address = await address.json();\n let city = address.results[0].locations[0].adminArea5;\n let state = address.results[0].locations[0].adminArea3;\n let country = address.results[0].locations[0].adminArea1;\n document.querySelector(\"#location\").innerHTML = `welcome all from ${city},${state},${country}`;\n }\n\n function fail(msg) {\n document.querySelector(\"#location\").innerHTML= msg.message;\n }\n }", "function askForCoords(){\n navigator.geolocation.getCurrentPosition(handleGeoSuccess, handleGeoError)\n}", "function fechLocation() {\n navigator.geolocation.getCurrentPosition(success);\n\n async function success(position) {\n lat = position.coords.latitude\n lon = position.coords.longitude;\n // console.log(lat);\n // console.log(lon);\n\n let resp = await fetch(`http://open.mapquestapi.com/geocoding/v1/reverse?key=${Geolocation_API_Key}&location=${lat},${lon}`);\n resp = await resp.json();\n // console.log(resp);\n\n const city = resp.results[0].locations[0].adminArea5\n const state = resp.results[0].locations[0].adminArea3\n const country = resp.results[0].locations[0].adminArea1\n const zip = resp.results[0].locations[0].postalCode\n\n document.querySelector(\"#address\").innerHTML = `Welcome all from ${city}, ${state}, ${zip}, ${country}!`;\n };\n }", "function locationInfoCall(lat,long,callback){\n var queryURL1 =`https://developers.zomato.com/api/v2.1/locations?lat=${lat}&lon=${long}&apikey=${apiKey}`;\n $.ajax({\n url: queryURL1,\n method: \"GET\"\n }).then(function(zomatoResponse) {\n \n cityId = zomatoResponse.location_suggestions[0].city_id;\n cityStateName = zomatoResponse.location_suggestions[0].title;\n entityType = zomatoResponse.location_suggestions[0].entity_type;\n entityId = zomatoResponse.location_suggestions[0].entity_id;\n\n var parameters = {\n cityId: cityId,\n cityStateName: cityStateName,\n entityType: entityType,\n entityId: entityId,\n }\n callback();\n });\n \n }//end locationInfoCall function", "function setLocation (lat, lon) {\n curLat = lat.toString();\n curLon = lon.toString();\n\n if (unitStatus == \"1F\") {\n urlWeather = 'http://api.openweathermap.org/data/2.5/weather?lat='+curLat+'&lon='+curLon+'&APPID=ca658d6c3e2f5efdebb110ead41e152b&callback=?&units=imperial';\n urlForecast = 'http://api.openweathermap.org/data/2.5/forecast?lat='+curLat+'&lon='+curLon+'&APPID=ca658d6c3e2f5efdebb110ead41e152b&callback=?&units=imperial';\n }\n else {\n urlWeather = 'http://api.openweathermap.org/data/2.5/weather?lat='+curLat+'&lon='+curLon+'&APPID=ca658d6c3e2f5efdebb110ead41e152b&callback=?&units=metric';\n urlForecast = 'http://api.openweathermap.org/data/2.5/forecast?lat='+curLat+'&lon='+curLon+'&APPID=ca658d6c3e2f5efdebb110ead41e152b&callback=?&units=metric';\n }\n/*console.log(curLat);\n console.log(curLon);\n console.log(urlWeather);\n console.log(urlForecast);\n*/\n}", "function geolocationCoordinates(coordinatesRequestUrl, citySearched){\n $.ajax({\n url: coordinatesRequestUrl,\n method: 'GET',\n }).then(function (response){\n var lat = response[0].lat;\n var lon = response[0].lon;\n\n var requestUrl = 'https://api.openweathermap.org/data/2.5/onecall?lat='+lat+'&lon='+lon+'&units=imperial&id=524901&appid=ab7266a3a00f62e9f68c69fe3c45b0e5'\n\n fetchWeatherData(requestUrl, citySearched);\n });\n}", "function getCoords(location) {\n const latitude = location.coords.latitude;\n const longitude = location.coords.longitude;\n const id = \"location1\";\n\n fetchCurrentWeather(latitude, longitude, id);\n}", "getLocation() {\n navigator.geolocation.getCurrentPosition((position) => {\n this.setState({lat: position.coords.latitude, lon: position.coords.longitude});\n // if successful, proceed to make API request\n this.getCurrent();\n }, (error) => this.setState({errorMessage: error}))\n }", "geolocate () {\n this.updateGeolocation ((geolocation, position) => {\n this.updateCoordinates(geolocation)\n })\n }", "function getCityLocation(data) {\n if (data) {\n let { results: res } = data;\n let { 0: obj } = res;\n let city = obj.address_components[0].long_name;\n let location = obj.geometry.location;\n let { lat, lng: lon } = location;\n lat = parseFloat(lat).toFixed(3);\n lon = parseFloat(lon).toFixed(3);\n APIrqs(lat, lon, city);\n\n }\n\n}", "function geolocation() {\n\n let Key = \"nOkTZJzGcN8wKdZbHtemhMf4zHkvJBVG\";\n\n navigator.geolocation.getCurrentPosition(success);\n\n async function success(position) {\n\n long = position.coords.longitude;\n lat = position.coords.latitude;\n\n let theLocation = await fetch(`http://www.mapquestapi.com/geocoding/v1/reverse?key=${Key}&location=${lat},${long}&includeRoadMetadata=true&includeNearestIntersection=true`)\n theLocation = await theLocation.json()\n\n const city = theLocation.results[0].locations[0].adminArea5;\n const state = theLocation.results[0].locations[0].adminArea3;\n const address = document.getElementById('address')\n address.innerHTML = `welcome all from ${city}, ${state}`;\n }\n }", "function yourLocationWeather( latitude, longitude ) {\n console.log(\"latitude\" + latitude)\n console.log(\"longitude \" + longitude)\n var queryURL = `https://api.opencagedata.com/geocode/v1/json?q=${latitude}+${longitude}&key=3620c85faf154e74a7e16400eae1d31e`;\n \n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).then(function (response) {\n fetchCityWeather(response.results[0].components.town)\n })\n}", "function getLocation() {\n window.navigator.geolocation.getCurrentPosition((location) => {\n userLat = location.coords.latitude;\n userLon = location.coords.longitude;\n checkParkCoord();\n })\n }", "function useLatAndLong(result) {\n let api = `https://cors-anywhere.herokuapp.com/http://api.openweathermap.org/data/2.5/onecall?lat=${result.lat}&lon=${result.lon}&appid=${appid}&units=metric`;\n fetch(api)\n .then(function (res) {\n return res.json();\n })\n .then(function (resp) {\n console.log(resp);\n showHourWeather(resp.hourly.slice(0, 12));\n showDailyWeather(resp.daily);\n });\n}", "getLocationApi(location) {\n var mapurl = `https://maps.googleapis.com/maps/api/geocode/json?address=${location}&key=${googlekey}`;\n console.log(mapurl)\n axios.get(mapurl).then(response => {\n this.setState({\n lat: response.data.results[0].geometry.location.lat,\n lon: response.data.results[0].geometry.location.lng,\n })\n console.log(response.data.results[0].formatted_address)\n this.getWeatherApi(this.state.lat,this.state.lon);\n }).catch(function (error) {\n console.log(error);\n });\n }", "function getCoords(data) {\n latitude = data.results[0].geometry.location.lat;\n longitude = data.results[0].geometry.location.lng;\n console.log(\"Lat: \" + latitude + \"Long: \" + longitude);\n url = \"?zipInput=\" + zipInput + \"&addressInput=\" + addressInput + \"&cityInput=\" + cityInput + \"&stateInput=\" + stateInput + \"&longitude=\" + longitude + \"&latitude=\" + latitude;\n url = url.replace(/ /g, '') // Remove White Space\n console.log(url);\n getURL(url);\n}", "function geoCoords(searchInputVal){\n var coordUrl = 'https://api.openweathermap.org/geo/1.0/direct?q=' + searchInputVal + apiKey;\n\n fetch(coordUrl)\n .then(function (response){\n return response.json();\n })\n .then(function (data){\n // console.log(data);\n // console.log(data[0].lat);\n // console.log(data[0].lon);\n var lattitude = data[0].lat;\n var longitude = \"&lon=\" + data[0].lon;\n searchWeather(lattitude, longitude);\n })\n}", "function acceslocationfun() {\n fetch(`http://www.mapquestapi.com/geocoding/v1/reverse?key=etyxXJEu28EtN6ySr5iCsUO9QrMuUc0m&location=${latitude1},${longitude1}&includeRoadMetadata=true&includeNearestIntersection=true`\n , { method: \"GET\" }\n )\n\n .then(res => res.json())\n .then(sec => {\n console.log(geolocationData)\n\n geolocationData = sec;\n //accessed geolocation variable na\n let geo1 = geolocationData.results[0].locations[0].adminArea1\n let geo2 = geolocationData.results[0].locations[0].adminArea3\n let geo3 = geolocationData.results[0].locations[0].adminArea5\n\n document.getElementById(\"geolocation_id\").innerHTML =\"Welcome To \"+ \" \"+ geo3 + \" \" + geo2 + \" \" + geo1\n }\n )\n .then(err => { console.log(err) })\n }", "fetchGeographicLocation() {\n\t\t//First check if the browser supports geo locations\n\t\tif (navigator.geolocation){\n\t\t\tnavigator.geolocation.getCurrentPosition(\n\t\t\t\t/*anonymous method passed as the first argument used by the getCurrentPosition\n\t\t\t\t method when it was successful, else it calls the error function */\n\t\t\t\t(position) => {\n\t\t\t\t\t//creating a variable to store the coordinates\n\t\t\t\t\tlet crds = position.coords;\n\t\t\t\t\tthis.fetchWeatherData(crds.latitude, crds.longitude);\n\t\t\t\t},\n\t\t\t\t//the method that gets called when an error occurs\n\t\t\t\t() => {\n\t\t\t\t\twindow.alert(\"Error has occurred\");\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t}", "getLocation() {\n navigator.geolocation.getCurrentPosition((position) => {\n this.setState({lat: position.coords.latitude, lon: position.coords.longitude});\n // if successful, proceed to make API request\n this.getLocationName();\n }, (error) => this.setState({errorMessage: error}))\n }", "async function oneCall(location) {\n const coords = await getCoordsAndLocation(location);\n const data = await fetch(\n ` https://api.openweathermap.org/data/2.5/onecall?lat=${coords[0]}&lon=${coords[1]}&appid=${key}&units=${getUnits()}`,\n {mode: 'cors'},\n );\n return [data, coords[2]];\n}", "async getCurrentCoords(coords) {\n const response = await fetch(\n `https://api.openweathermap.org/data/2.5/weather?lat=${coords.latitude}&lon=${coords.longitude}&units=${this.units}&APPID=${this.key}`\n );\n\n const data = await response.json();\n\n return data;\n }", "function getCordinates(query, locationtype, countrycode, admindistrictcode) {\n query = query.replace(/ /g, \"+\")\n var url = \"https://\" + config.credentials.weather.username + \":\" + config.credentials.weather.password + \"@\" + config.credentials.weather.host + \":\" + config.credentials.weather.port + \"/api/weather/v3/location/search?query=\" + query + \"&locationType=\" + locationtype + \"&countryCode=\" + countrycode + \"&adminDistrictCode=\" + admindistrictcode + \"&language=en-US\";\n var options = {\n method: 'GET',\n url: url\n }\n request(options, function(error, response, body) {\n\n if (!error && response.statusCode == 200) {\n var result = JSON.parse(body)\n //console.log(result)\n var longitude = result.location.longitude[0];\n var latitude = result.location.latitude[0];\n //console.log(longitude, latitude);\n getWeather(longitude, latitude)\n } else {\n console.log(\"Error getting cordinates\")\n }\n });\n\n}", "function getLocation(position) {\n\t//console.log(position.coords);\n\tvar lat = position.coords.latitude;\n var lng = position.coords.longitude;\n \n\tif (!lat || !lng) {\n \talert('Could not retrieve location');\n return;\n }\n // fetch the API results based on this location\n getRestrooms(lat,lng);\n}", "function queryApi(coords) {\n Show_Loading_Overlay(view);\n\n fldInfo.coords = {\n latitude: coords.latitude,\n longitude: coords.longitude\n }\n\n var elevApiUrl = \"https://ned.usgs.gov/epqs/pqs.php?x=\" + coords.longitude\n + \"&y=\" + coords.latitude + \"&units=Feet&output=json\";\n\n //National Flood Data API call\n $.ajax({ \n url: 'Home/GetFloodDataByCoordinates',\n type: 'GET',\n dataType: 'json',\n traditional: true,\n data: {\n latitude: coords.latitude,\n longitude: coords.longitude\n },\n success: function (response) {\n fldInfo.hasInfo = true\n fldInfo.zone = response.data.floodZone;\n fldInfo.zoneDes = response.data.zoneDescription;\n fldInfo.fldZoneDes = response.data.floodZoneDesciption;\n fldInfo.bfe = response.data.elevation;\n fldInfo.hasBFE = response.data.baseFloodElevationAvailable; \n fldInfo.specFldHzdArea = response.data.specialFloodHazardArea;\n\n //USGS Elevation API call\n $.ajax({\n url: elevApiUrl,\n type: 'GET',\n success: function (response) {\n fldInfo.elevation = response.USGS_Elevation_Point_Query_Service.Elevation_Query.Elevation;\n Show_Popup(view, fldInfo);\n },\n error: function () {\n fldInfo.elevation = null;\n }\n });\n },\n error: function () {\n fldInfo.hasInfo = false;\n Show_Popup(view, fldInfo)\n }\n });\n }", "function updateLocation(data) {\n\n var payload = {\n operation: \"location\",\n lat: data.latitude,\n lon: data.longitude\n }\n\n fetch(\"https://dz0qr7yoti.execute-api.us-east-1.amazonaws.com/dev/test\", {\n method: \"POST\",\n body: JSON.stringify(payload)\n });\n\n}", "function getCity(coordinates) { \n\tvar xhr = new XMLHttpRequest(); \n\tvar lat = coordinates[0]; \n\tvar lng = coordinates[1]; \n\n\t// Paste your LocationIQ token below.\n\txhr.open('GET', \"https://us1.locationiq.com/v1/reverse.php?key=pk.db6b5613a34db29a0d33169822c6d0b7&lat=\" + \n\tlat + \"&lon=\" + lng + \"&format=json\", true); \n\txhr.send(); \n\txhr.onreadystatechange = processRequest; \n\txhr.addEventListener(\"readystatechange\", processRequest, false); \n\n\tfunction processRequest(e) { \n\t\tif (xhr.readyState == 4 && xhr.status == 200) { \n\t\t\tvar response = JSON.parse(xhr.responseText); \n\t\t\tvar city = response.address.city; \n console.log(city); \n getWeatherDetail(city);\n\t\t\treturn ; \n\t\t} \n\t} \n}", "function getLocation(){\n\t\t\tif(navigator.geolocation){\n\t\t\t\tnavigator.geolocation.getCurrentPosition(showPosition);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tdisplayCoords.innerHTML=\"Geolocation API not supported by your browser\";\n\t\t\t}\n\t\t\t\n\t\t}", "function weatherInCurrentLocation(){\n \n function fetchWeatherFromCoords(position) {\n let myLat = position.coords.latitude;\n let myLong = position.coords.longitude;\n let APIUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${myLat}&lon=${myLong}&appid=${APIKey}&units=metric&lang=${myLang}`; \n\n console.log(APIUrl);\n fetch(APIUrl)\n .then((response) => response.json())\n .then((json) => {\n updateCurrentInfoInApp(json);\n })\n .catch((error) => console.log(error));\n }\n\n function fetchForecastFromCoords(position) {\n let myLat = position.coords.latitude;\n let myLong = position.coords.longitude;\n let APIUrl2 = `https://api.openweathermap.org/data/2.5/onecall?lat=${myLat}&lon=${myLong}&exclude=current,minutely,hourly,alerts&appid=${APIKey}&units=metric&lang=${myLang}`;\n \n console.log(APIUrl2);\n \n fetch(APIUrl2)\n .then(response => response.json())\n .then(json => {\n updateForecastInfoInApp(json);\n })\n }\n navigator.geolocation.getCurrentPosition(fetchWeatherFromCoords);\n navigator.geolocation.getCurrentPosition(fetchForecastFromCoords);\n}", "function getLocation(currLoc){\n latitude = Math.floor(currLoc.lat * 10000 + 0.5) / 10000;\n longitude = Math.floor(currLoc.lng * 10000 + 0.5) / 10000;\n\n let cityCord = {appid: weatherAPIId, lat: latitude, lon: longitude, units: \"imperial\" };\n let formatted = queryBuilder(cityCord);\n\n processRequest(formatted);\n}", "function getLocation(city) {\n document.getElementById(\"spinner\").style.display = \"block\";\n fetch(\n `https://geocode.search.hereapi.com/v1/geocode?q=${city}&apiKey=${hereAPIKey}` //getting the location of the city\n )\n .then((items) => {\n document.getElementById(\"spinner\").style.display = \"none\";\n return items.json();\n })\n .then(calcLonLat);\n // console.log(calcLonLat());\n}", "function doWeatherRequestForLocation(coordinates) {\n // Construct the url\n var completeUrl = \n DEFAULT_WEATHER_API_URL + \n coordinates.latitude + \",\" + coordinates.longitude + \n DEFAULT_EXCLUDE_WEATHER_DATA + DEFAULT_METRICS;\n\n // Do a get request for the weather\n https.get(completeUrl, (response) => {\n \n if(response.statusCode == 200){\n // Recieve the data\n var completeData = '';\n response.on(\"data\", (data) => completeData += data);\n response.on(\"end\", () => weatherRequestComplete(completeData, response.statusCode));\n }\n\n // Report error when connection failed\n }).on(\"error\", (error) => {\n console.log(error);\n });\n}", "function getLocation() {\n var options = {\n enableHighAccuracy: true,\n timeout: 5000,\n maxAge: 10000\n };\n\n if (!coord && navigator.geolocation) {\n navigator.geolocation.getCurrentPosition(showSuccess,showError,options);\n } else if (navigator.geolocation){\n watchHandler = navigator.geolocation.watchPosition(showSuccess,showError,options);\n }else {\n location = \"Geolocation is not supported by this browser.\";\n }\n\n\n function showSuccess(pos) {\n errorCount = 0;\n\n coord = pos.coords;\n\n distance = getDistanceFromLatLonInKm(coord.latitude,coord.longitude,target.latitude,target.longitude);\n\n //Update the meter needle position\n handleMeter();\n\n //decide whether to play or stop current audio tracks\n handleAudioPlayback(distance);\n }\n\n function showError(err){\n errorCount++;\n console.warn(`ERROR(${err.code}) - (${errorCount}) bad calls`);\n\n if (errorCount > 10){\n window.location.href = \"/profile\";\n }\n }\n}", "function getStreet() {\n var apikey = '8iMbHQoKISbmKAynwHsO7ZlMhuPhWgtu';\n $.ajax({\n url: 'https://www.mapquestapi.com/geocoding/v1/reverse',\n dataType: 'json',\n method: 'GET',\n data: {\n location: lat + \",\" + lon,\n key: apikey,\n }\n }).then(function (response) {\n //On succesful of good response: set Ticket Master Quiries off of retured info\n searchAddress = response.results[0].locations[0].street;\n searchCity = response.results[0].locations[0].adminArea5;\n searchState = response.results[0].locations[0].adminArea3;\n startPoint = searchAddress + \", \" + searchCity + \", \" + searchState;\n\n main(); //call to main to get other defualt values not obtained through location servies permissions\n });\n }", "function cinemasLocation(lat, lon) {\n\n $.ajax({\n url: 'https://api-gate2.movieglu.com/cinemasNearby/?n=10',\n method: 'GET',\n headers: {\n 'api-version': 'v200',\n 'x-api-key': 'WB67S8ateD3ogaE882ltx6npSbbJIKIt4nzhcRN0',\n 'territory': 'ES',\n 'authorization': 'Basic VU5JVl8zNDpiV0xlOGxvamZSd2I=',\n 'client': 'UNIV_34',\n 'device-datetime': '2019-12-14T16:24:17.000Z',\n 'geolocation': `${lat.toFixed(3)};${lon.toFixed(3)}`\n },\n success: function (data) {\n console.log(data)\n cinemas = data.cinemas;\n\n AddPoints(cinemas,map);\n }\n });\n\n}", "function getCurrentLocation() {\n \n function success(position) {\n //if permission granted set call [setAddress()] to convert lat and long to street adresss\n lat = position.coords.latitude;\n lon = position.coords.longitude;\n setAddress();\n }\n function denied() {\n // if permission is denied set Ticket Master queries to defualt to \"Washington\"(city) and DC (state)\n // console.log('Unable to retrieve your location');\n searchAddress=\"\";\n searchCity = \"Washington\";\n searchState = \"DC\";\n startPoint = searchCity + \", \" + searchState;\n // Call to main to set defualts other than location [setTime() default && setCategory() defualt]\n main();\n }\n if (!navigator.geolocation) {\n // console.log('Geolocation is not supported by your browser');\n } else {\n // console.log('Locating…');\n navigator.geolocation.getCurrentPosition(success, denied);\n }\n }", "function myLocation(position) {\n console.log(position);\n let lat = position.coords.latitude;\n let lon = position.coords.longitude;\n let apiKey = \"47b783e374dd1d17b34b52141082af29\";\n let apiUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric`;\n\n axios.get(apiUrl).then(showWeather);\n\n apiUrlFor = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric`;\n axios.get(apiUrlFor).then(showForecast);\n}", "function findLocation() {\n var key = \"\";\n var post = \"https://www.googleapis.com/geolocation/v1/geolocate?key=\" + key;\n $.post(post, function (data) {\n if (data.accuracy < 3000) {\n var geocoder = new google.maps.Geocoder;\n geocodeLatLng(geocoder, data.location.lat, data.location.lng);\n }\n });\n }", "function getCoordintes() { \n\tvar options = { \n\t\tenableHighAccuracy: true, \n\t\ttimeout: 5000, \n\t\tmaximumAge: 0 \n\t}; \n\tfunction success(pos) { \n\t\tvar crd = pos.coords; \n\t\tvar lat = crd.latitude.toString(); \n\t\tvar lng = crd.longitude.toString(); \n\t\tvar coordinates = [lat, lng]; \n\t\tgetCity(coordinates); \n\t\treturn; \n\t} \n\tfunction error(err) { \n\t\tconsole.warn(`ERROR(${err.code}): ${err.message}`); \n\t} \n\tnavigator.geolocation.getCurrentPosition(success, error, options); \n}", "function getGPSLocation(){\n\tconsole.log('whereami');\n var success = function(position) {\n console.log(JSON.stringify(position));\n whatcity(position);\n };\n var failure = function() {\n console.log(\"error\");\n };\n navigator.geolocation.getCurrentPosition(success, failure, {\n enableHighAccuracy: true\n });\n}", "function accessingCoordinates(cleaned_location){\n const mapquestKey = 'ZGADDfaBd92GKnmxjk6sAupluGqbaZgG'\n fetch('https://www.mapquestapi.com/geocoding/v1/address?key=' + mapquestKey + '&location=' + cleaned_location)\n .then(response =>{\n if(response.ok){\n return response.json()\n }\n })\n .then(mapquestResponse =>{\n if(mapquestResponse.results[0].locations[0].adminArea1 === 'US'){\n return cleanCoordinates(mapquestResponse);\n }else{\n alert(\"This location cannot be found. Please double check that the address, city, or zip code you have entered is valid in the United States\");\n }\n })\n .catch(error => alert(\"Uh-Oh Something Went Wrong! Try Again Later!\"));\n}", "function posSuccess(pos) {\n var crd = pos.coords;\n var API_KEY = `AIzaSyAn__qjdqcfvl6zXthkIeltbb-8wmEPmgY`;\n var geo_url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${crd.latitude},${crd.longitude}&key=${API_KEY}`;\n\n console.log(geo_url);\n \n console.log(`Latitude : ${crd.latitude}`);\n console.log(`Longitude: ${crd.longitude}`);\n console.log(`More or less ${crd.accuracy} meters.`);\n\n \n fetch(geo_url)\n .then(\n function(response) {\n if (response.status !== 200) {\n console.log(`Looks like there was a problem. Status Code: ${response.status}`);\n return;\n }\n \n response.json().then(function(data) {\n console.log(data);\n document.getElementById('start').value = data.results[0].formatted_address;\n console.log(data.results);\n });\n }\n )\n}", "function getLocation() {\r\n if (navigator.geolocation)\r\n navigator.geolocation.getCurrentPosition(success);\r\n else\r\n alert('Geolocation not supported');\r\n\r\n function success(position) {\r\n latitude = position.coords.latitude;\r\n longitude = position.coords.longitude;\r\n\r\n // send latitude and longitude to gmap to get full address\r\n gmap = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude;\r\n\r\n //call fetchWeather to get the data\r\n fetchWeather();\r\n\r\n // cal getAddress to get full address\r\n getAddress();\r\n }\r\n}", "async _getLocation() {\n let me = this;\n let { status } = await Permissions.askAsync(Permissions.LOCATION);\n if (status !== 'granted') {\n Alert.alert('Location permission was denied');\n return;\n }\n this.setState({isLoading: true});\n this.watchID = this.geoLoc.watchPosition(position => {\n const location = JSON.stringify(position);\n me.setState({ isLoading:false, region: {latitude: position.coords.latitude, longitude: position.coords.longitude,\n latitudeDelta: 0.0122,\n longitudeDelta: 0.0021}});\n },\n error => {\n me.setState({isLoading:false});\n Alert.alert('Error while getting location', error.message)\n },\n { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 });\n }", "_getLocation() {\n navigator.geolocation.getCurrentPosition(\n (position) => {\n var crd = position.coords;\n this.setState({\n location: {lat: crd.latitude, long: crd.longitude, city: null},\n located: true\n });\n console.log(crd);\n },\n (error) => alert(error.message),\n {enableHighAccuracy: true, timeout: 10000, maximumAge: 0}\n );\n }", "function LatLong_Complete(result) { //function LatLong_Complete is defined\n var lat = result.results[0].geometry.location.lat;\n var lng = result.results[0].geometry.location.lng;\n var local = lat + \",\" + lng;\n var city = result.results[0].address_components[1].long_name;\n var state = result.results[0].address_components[3].short_name;\n locationName = result.results[0].formatted_address;\n console.log(lat,lng,local,city,state);\n\n\n var darkSkyUrl =\"https://api.darksky.net/forecast/9a451f009690bf1c4cb3b721e22d623e/\" + lat + \",\" + lng;\n \n var ask = { \n url: darkSkyUrl,\n dataType: \"jsonp\",\n success: darkSky\n };\n $.ajax(ask); \n\n} //function LatLong_Complete defined has ended", "async function location(params) {\n let location = params.cp + ' ' + params.street + ' ' + params.suburb + ',' + params.city + ' ' + params.state + ' Mexico';\n var lat, lon;\n await axios.get('https://maps.googleapis.com/maps/api/geocode/json', {\n params: {\n address: location,\n key: 'AIzaSyDgRN1AR5CnGjgdcc3f93CzMho80a2yWog'\n }\n }).then(function (resp) {\n lat = resp.data.results[0].geometry.location.lat;\n lon = resp.data.results[0].geometry.location.lng;\n });\n\n return {\n lat,\n lon\n }\n}", "getLocation() {\n navigator.geolocation.getCurrentPosition(\n (position) => {\n this.setState(\n () => ({\n latitutde: position.coords.latitude,\n longitude: position.coords.longitude\n }), () => { this.getWeather(); }\n );\n },\n (error) => this.setState({ forecast: error.message }),\n { enableHighAccuracy: true, timeout: 2000, maximumAge: 1000 },\n );\n }", "function getPOIsCOORDS(category, lat, long) {\n // console.log(\"getPOICOORDS - category: \" + category);\n var category = category;\n var lat = lat;\n var long = long;\n\n //yelp query url to search by category and location, with a set radius\n var queryURL = \"https://cors-anywhere.herokuapp.com/http://api.yelp.com/v3/businesses/search?radius=2000&categories=\" + category + \"&latitude=\" + lat + \"&longitude=\" + long;\n\n var settings = {\n \"async\": true,\n \"crossDomain\": true,\n \"url\": queryURL,\n \"method\": \"GET\",\n \"headers\": {\n \"Authorization\": \"Bearer a3QTS8V50rV_Xf4jHgTIeYnfEPmEy74KhtAYhFuPJG2ai4R4NVzM4SebzmbeD5ZYDxjGd4O1ZU4ejWMq_5Z7JUUEwju02BaXT94shIGxKVpWhu7eLArA4JWxaDWuXHYx\",\n \"cache-control\": \"no-cache\",\n \"crossOrigin\": \"null\",\n \"Postman-Token\": \"a926db60-6442-448e-92fa-65bffe0a2bad\"\n }\n }\n\n $.ajax(settings).then(function (response) {\n var locations = response.businesses;\n //loop through the list of JSON responses\n\n if (JSON.stringify(response.businesses).length > 2) {\n for (var i = 0; i < JSON.stringify(locations.length); i++) {\n // console.log(JSON.stringify(locations[i].id));\n getPOIdetails(locations[i].id)\n }\n }\n else {\n alert(\"No results in you your area for \" + selectedButton);\n }\n })\n }", "function getLocation() {\n $.getJSON('https://ipapi.co/json', function(data) {\n currentRegion = data.region;\n currentCountry = data.country;\n currentLat = data.latitude;\n currentLong = data.longitude;\n \n //call the function getWeather and apply the data above to this function\n getWeather();\n });\n }", "function getPOIsCOORDS(category, lat, long) {\n console.log(\"getPOICOORDS - category: \" + category);\n var category = category;\n var lat = lat;\n var long = long;\n\n //yelp query url to search by category and location, with a set radius\n var queryURL = \"https://cors-anywhere.herokuapp.com/http://api.yelp.com/v3/businesses/search?radius=2000&categories=\" + category + \"&latitude=\" + lat + \"&longitude=\" + long;\n\n var settings = {\n \"async\": true,\n \"crossDomain\": true,\n \"url\": queryURL,\n \"method\": \"GET\",\n \"headers\": {\n \"Authorization\": \"Bearer a3QTS8V50rV_Xf4jHgTIeYnfEPmEy74KhtAYhFuPJG2ai4R4NVzM4SebzmbeD5ZYDxjGd4O1ZU4ejWMq_5Z7JUUEwju02BaXT94shIGxKVpWhu7eLArA4JWxaDWuXHYx\",\n \"cache-control\": \"no-cache\",\n \"crossOrigin\": \"null\",\n \"Postman-Token\": \"a926db60-6442-448e-92fa-65bffe0a2bad\"\n }\n }\n\n $.ajax(settings).then(function (response) {\n var locations = response.businesses;\n //loop through the list of JSON responses\n \n if (JSON.stringify(response.businesses).length > 2) {\n for (var i = 0; i < JSON.stringify(locations.length); i++){\n console.log(JSON.stringify(locations[i].id));\n getPOIdetails(locations[i].id)\n }\n }\n else {\n alert(\"No results in you your area for \" + selectedButton);\n } \n }) \n }", "function currentLocationPull() {\n \n // if successfull\n function success(position) {\n const latitude = position.coords.latitude;\n const longitude = position.coords.longitude;\n \n // console.log(\"Successfully got position\");\n // console.log(\"latitude = \" + latitude);\n // console.log(\"longitude = \" + longitude);\n\n // construct URL for current weather by lat/long API request\n let weatherByCoordsURL = \"https://api.openweathermap.org/data/2.5/weather?lat=\" + latitude + \"&lon=\" + longitude + \"&APPID=7c1d14299c12aa7faada3a48e18af17b&units=imperial\";\n\n // send request for current weather data\n $.ajax({\n url: weatherByCoordsURL,\n method: \"GET\"\n }).then(function(response) {\n // display response\n displayCurrentWeather(response);\n });\n\n // construct URL for forecast by lat/long API request\n let forecastByCoordsURL = \"https://api.openweathermap.org/data/2.5/forecast?lat=\" + latitude + \"&lon=\" + longitude + \"&APPID=7c1d14299c12aa7faada3a48e18af17b&units=imperial\";\n\n // send request for forecast data\n $.ajax({\n url: forecastByCoordsURL,\n method: \"GET\"\n }).then(function(response) {\n // display response\n display5DayForecast(response);\n });\n\n\n }\n \n function error() {\n console.log(\"Unable to retrieve your location\");\n }\n \n if (!navigator.geolocation) {\n console.log(\"Geolocation is not supported by your browser\");\n } else {\n navigator.geolocation.getCurrentPosition(success, error);\n }\n}", "function getLocation() {\n if (navigator.geolocation) {\n navigator.geolocation.getCurrentPosition(getCoordinates);\n } else {\n alert(\"Geolocation is not supported by this browser.\");\n }\n}", "async getCoords() {\n try {\n const data = await getCurrentLocation();\n this.coords = [data.coords.latitude, data.coords.longitude];\n } catch (error) {\n console.log(error);\n }\n }", "function locationInfoByCoords(lat,lon) {\n var coords= {lat: lat, lng: lon};\n\n geoCodingService.geocode({'location': coords, 'bounds': searchBound}, function(results, status) {\n if (status === 'OK') {\n if (results[0]) {\n processPlaceObject(results[0]);\n } else {\n window.alert('Oops! Cannot find your location name!');\n $('#search').removeClass('searchBarLoading');\n }\n } else {\n window.alert('Oops! Finding your area name failed due to: ' + status);\n $('#search').removeClass('searchBarLoading');\n }\n });\n}", "async function locations(zone, type, coord){\r\n \r\n let query, headers, queryURL\r\n \r\n let locationTypes = ['PARKING_ZONE','TRAFFIC_LANE','WALKWAY']\r\n \r\n // (typeof(coord) === undefined) ? tenant.bbox : coord\r\n if (coord === undefined) {coord = '-90:-180,90:180'}\r\n \r\n if (type === 'bbox') {\r\n console.debug('querying locations by bbox')\r\n query = '/locations/search?bbox='+coord\r\n } else if (locationTypes.indexOf(type) >= 0) {\r\n console.debug('querying locations by locationType')\r\n query = '/locations/search?bbox='+coord+'&q=locationType:'+type \r\n } else {\r\n console.debug('querying locations by locationUid')\r\n query = '/locations/'+type\r\n }\r\n\r\n headers = {authorization: 'Bearer '+client_token, 'predix-zone-id': zone} \r\n queryURL = tenant.metadataservice+query\r\n console.log('Query URL: '+queryURL)\r\n \r\n let response = (await request(queryURL,headers))\r\n return (response.content === undefined) ? response : response.content \r\n }", "function initialLocation() {\n var IPapiKey = \"602f8d85bc584bb4b0b520771a9d3287\";\n var IPapi = \"https://ipgeolocation.abstractapi.com/v1/?api_key=\" + IPapiKey;\n fetch(IPapi)\n .then((r) => r.json())\n .then((d) => {\n // assign user's lat/long to variables place them on the map\n searchLat = d.latitude;\n searchLng = d.longitude;\n initMap()\n });\n}", "function getLocation(location) {\n lat = location.coords.latitude;\n lng = location.coords.longitude;\n }", "function coordinatesLookup (url, city) { // Passed in NominatimUrl and user input\n fetch(url + city) // Call the Nominatim Api with the completed url\n .then(res => res.json()) // Return the JSON response\n .then(function (data) { // Extract the Latitude and Longitude of the user input city\n let lat = data[0].lat;\n let lon = data[0].lon;\n\n const weatherUrl = `https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&units=metric&appid=${apiKey}`; // Template Literal for API call construction\n\n weatherLookup(weatherUrl); // Call the Open Weather Api with the returned Latitude and Longitude values input into the API call\n })\n}", "function getCoordintes() { \n\tvar options = { \n\t\tenableHighAccuracy: true, \n\t\ttimeout: 5000, \n\t\tmaximumAge: 0 \n\t}; \n\n\tfunction success(pos) { \n\t\tvar crd = pos.coords; \n\t\tvar lat = crd.latitude.toString(); \n\t\tvar lng = crd.longitude.toString(); \n\t\tvar coordinates = [lat, lng]; \n\t\tconsole.log(`Latitude: ${lat}, Longitude: ${lng}`); \n\t\tgetCity(coordinates); \n\t\treturn; \n\n\t} \n\n\tfunction error(err) { \n\t\tconsole.warn(`ERROR(${err.code}): ${err.message}`); \n\t} \n\n\tnavigator.geolocation.getCurrentPosition(success, error, options); \n}", "requestCurrentPosition() {\n\n var options = {\n enableHighAccuracy: true,\n timeout: 5000,\n maximumAge: 0\n }\n if (navigator.geolocation) {\n navigator.geolocation.getCurrentPosition((pos) => {\n var crd = pos.coords;\n const x = crd.latitude;\n const y = crd.longitude;\n this.setState({\n userLat: x\n });\n this.setState({\n userLng: y\n });\n }, this.error, options);\n }\n\n }", "function getLocation(locale) {\n const URL = \"https://api.weather.gov/points/\" + locale; \n // NWS User-Agent header (built above) will be the second parameter \n fetch(URL, idHeader) \n .then(function(response){\n if(response.ok){ \n return response.json(); \n } \n throw new ERROR('Response not OK.');\n })\n .then(function (data) { \n // Let's see what we got back\n console.log('Json object from getLocation function:'); \n console.log(data);\n // Store data to localstorage \n storage.setItem(\"locName\", data.properties.relativeLocation.properties.city); \n storage.setItem(\"locState\", data.properties.relativeLocation.properties.state); \n \n // Next, get the weather station ID before requesting current conditions \n // URL for station list is in the data object \n let stationsURL = data.properties.observationStations;\n let forecastHourly= data.properties.forecastHourly; \n // Call the function to get the list of weather stations\n getStationId(stationsURL); \n getHourly(forecastHourly);\n }) \n .catch(error => console.log('There was a getLocation error: ', error)) \n} // end getLocation function", "function getLongLat(err, result) {\n if (err) {\n console.log(err);\n }\n else {\n \n var lat1 = result.results[0].geometry.location.lat;\n // console.log(lat1);\n var long1 = result.results[0].geometry.location.lng;\n console.log('Your latitude is:' + lat1 + ' and longitude is: ' + long1);\n requestJson.requestJSON(getTemperature,'https://api.darksky.net/forecast/ee6f6a17b2a847dcf14b7cfe66833206/'+lat1 +','+long1);\n \n }\n }", "function gbDidSuccessGetLocation ( lat, long )\n{\n\tvar api_url = \"http://api.wunderground.com/api/\" + APIKEY + \"/conditions/q/\" + lat + \",\" + long + \".json\";\n\tgbRequest ( api_url, '1', 'YES' );\n}", "function CoordinateResponse(response) {\n var data = \"\";\n var sdata = \"\";\n var latitude = \"\";\n var longitude = \"\";\n\n response.on('data', function(chunk) {\n data += chunk;\n });\n\n response.on('end', function() {\n sdata = JSON.parse(data);\n latitude = sdata.results[0].locations[0].displayLatLng.lat;\n longitude = sdata.results[0].locations[0].displayLatLng.lng;\n placeSearch(latitude, longitude, 50000);\n });\n }", "function fetch_location(){\n console.log(\"Pta ni kya yaar!\");\n}", "function getLocation() {\n\t\tTitanium.Geolocation.getCurrentPosition( updatePosition );\n\t}", "function getLocation() {\n console.log('start getLocation');\n\tif(navigator.geolocation) {\n\t\tnavigator.geolocation.getCurrentPosition(\n\t\t\tfunction (position) {\n\t\t\t\t//do succes handling\n\t\t\t\tshowPosition(position)\n\t\t\t},\n\t\t\tfunction errorCallback(error) {\n\t\t\t\t//do error handling\n\t\t\t\tmsg = locationError(error)\n\t\t\t\talert(msg)\n\t\t\t},\n\t\t\t{\n\t\t\t\tmaximumAge: 0,\n\t\t\t\ttimeout: 5000,\n\t\t\t\tenableHighAccuracy: true\n\t\t\t}\n\t\t);\n\t}\n}", "function geolocate() {\n if (navigator.geolocation && state.getGeoLocation == false) {\n navigator.geolocation.getCurrentPosition(function (position) {\n var geolocation = {\n lat: position.coords.latitude,\n lng: position.coords.longitude\n };\n var params = {\n latlng: geolocation.lat + \",\" + geolocation.lng,\n key: \"AIzaSyAbWcPOXZQgFeeM2OHtK1Y-Gje8yl6KU1Y\"\n };\n var url = \"https://maps.googleapis.com/maps/api/geocode/json\";\n $.getJSON(url, params)\n .done(callbackGeolocate)\n .fail(function() {\n console.log(\"Error in geolocate...\");\n });\n });\n }\n}", "function locate() {\n if('geolocation' in navigator) {\n console.log('geolocation available');\n navigator.geolocation.getCurrentPosition(async position => {\n const lat = position.coords.latitude;\n const lng = position.coords.longitude;\n const data = {lat,lng};\n const options = {\n method:'POST',\n headers:{\n 'Content-Type': 'application/json'\n },\n body:JSON.stringify(data)\n };\n\n const response = await fetch('store/', options);\n const json = await response.json();\n store_number = json[0];\n });\n\n }\n}", "function actualizarPosicion(posicion){\r\n\r\n /* Prueba: Mostrar lat y long\r\n $respuesta.text(`latitud: ${posicion.coords.latitude} longitud: ${posicion.coords.longitude}`);\r\n */ \r\n var api_dir='https://reverse.geocoder.api.here.com/6.2/reversegeocode.json'; \r\n\r\n $.ajax({\r\n url: api_dir,\r\n type: 'GET',\r\n dataType: 'jsonp',\r\n jsonp: 'jsoncallback',\r\n data:{\r\n prox: `${posicion.coords.latitude},${posicion.coords.longitude},10`,\r\n mode: 'retrieveAddresses',\r\n maxresults: '1',\r\n app_id: app_id,\r\n app_code: app_code\r\n },\r\n success: function(response) {\r\n //console.log(response.Response.View[0].Result[0].Location.Address.City);\r\n $('#busqueda').val(response.Response.View[0].Result[0].Location.Address.Label);\r\n $respuesta.text(\"Tu lugar fue encontrado correctamente\");\r\n },\r\n error:function(e){\r\n $respuesta.text(\"no se obtuvo posición\");\r\n }\r\n }); \r\n}", "function _getLocation() {\n if (navigator.geolocation) {\n App.Modules.GPS.state=STATES.ON;\n navigator.geolocation.getCurrentPosition(_getLocation_return);\n } else {\n App.Modules.GPS.state=STATES.NOT_SUPPORTED;\n _dispatchUpdateCallbacks( );\n }\n }", "function getLocation(request, response) {\r\n let searchQuery = request.query.data;\r\n console.log(searchQuery)\r\n let url = `https://maps.googleapis.com/maps/api/geocode/json?address=${searchQuery}&key=${process.env.GEOCODE_API_KEY}`;\r\n // console.log(superagentResults);\r\n\r\n superagent.get(url).then(superagentResults => {\r\n let results = superagentResults.body.results[0];\r\n // console.log('results: ', results)\r\n const formatted_address = results.formatted_address;\r\n const lat = results.geometry.location.lat;\r\n const long = results.geometry.location.lng;\r\n const newLocation = new Location(searchQuery, formatted_address, lat, long);\r\n\r\n console.log('sending location')\r\n response.send(newLocation);\r\n }).catch(error => {\r\n console.log('=====================halp');\r\n console.error(error);\r\n response.status(500).send(error.message);\r\n })\r\n}", "function geoLocate (url, call) {\n\n $.ajax({\n url: url,\n success: function (res) {\n if (call == \"search\") {\n App.city.address = res.results[0].formatted_address;\n } else {\n App.city.address = res.results[0].address_components[res.results[0].address_components.length - 2].long_name + \", \" + res.results[0].address_components[res.results[0].address_components.length - 1].long_name;\n }\n App.city.longitude = res.results[0].geometry.location.lng;\n App.city.latitude = res.results[0].geometry.location.lat;\n }\n }).done(function() {\n getWeatherInfo();\n });\n\n }", "function getCoords() {\n // Making use of the navigator.geolocation property which gives access to user location\n if (navigator.geolocation) {\n // After declaring variable and learning we are using the navigator.geolocation property, we are not calling for the position and asking for display of position\n navigator.geolocation.getCurrentPosition(displayPosition);\n\n // Making use of an else statement which says to say not available otherwise\n } else {\n userLocation.innerHTML = \"Not available\";\n }\n}", "function geoLocationWeather() {\n navigator.geolocation.getCurrentPosition(function(position) {\n fetch(API + \"lat=\" + position.coords.latitude + \"&lon=\" + position.coords.longitude + \"&APPID=\" + KEY + \"&units=metric\")\n .then((resp) => resp.json())\n .then((data) => {\n getWeatherData(data);\n })\n .catch(function(error) {\n console.log(\"Wystąpił błąd: \" + error);\n })\n });\n }", "function giveCoordsWeather(response) {\n let apiWeather = Math.round(response.data.main.temp);\n let todaysTemp = document.querySelector(\".todaysTemp\");\n let apiWeatherDescription = response.data.weather[0].description;\n let weatherType = document.querySelector(\".weatherType\");\n let humidity = document.querySelector(\"#humidity\");\n let apiHumidity = response.data.main.humidity;\n let wind = document.querySelector(\"#wind\");\n let apiWind = Math.round(response.data.wind.speed);\n\n let apiIconCode = response.data.weather[0].icon;\n let weatherIcon = document.querySelector(\".weatherIcon\");\n weatherIcon.setAttribute(\n \"src\",\n `https://openweathermap.org/img/wn/${apiIconCode}@2x.png`\n );\n\n let location = response.data.name;\n let currentLocation = document.querySelector(\".searchedCity\");\n currentLocation.innerHTML = `${location}`;\n\n if (apiWeather > -99) {\n todaysTemp.innerHTML = `${apiWeather}`;\n weatherType.innerHTML = `${apiWeatherDescription}`;\n humidity.innerHTML = `${apiHumidity}`;\n wind.innerHTML = `${apiWind}`;\n }\n\n fahrenheitTemp = response.data.main.temp;\n\n currentLocationForForecast = response.data.name;\n}", "function Loc1(city, state, postCode) { // function loc is defined\n\n var area = \"\"; \n if (postCode.length != 0) {\n area = postCode.trim();\n }\n else if (city.length != 0 && state != 0) {\n area = city.trim() + \", \" + state;\n }\n else {\n return; \n }\n\n var googleUrl = \"https://maps.googleapis.com/maps/api/geocode/json?address=\" + area + \"&key=AIzaSyDkN5p4kquTOqQ_1ZHFdEkZk2MIMbZhFy0\";\n\n var ask = { \n url: googleUrl,\n dataType: \"jsonp\",\n success: LatLong_Complete\n\n};\n\n $.ajax(ask); \n} // function loc defined ended", "function getLocation() {\n if (navigator.geolocation) {\n var geoObject = navigator.geolocation.watchPosition(showPosition,\n handleError,options = {\n enableHighAccuracy: true\n }\n );\n }\n}", "async getLocation() {\n const location = await Location.getCurrentPositionAsync({ enableHighAccuracy: true });\n return {\n \"latitude\": location.coords.latitude, \n \"longitude\": location.coords.longitude, \n \"latitudeDelta\": 0.04,\n \"longitudeDelta\": 0.05 \n };\n }", "function FXweatherGeolocation () {\n // The URL to query the ip-API\n var queryURL = \"https://ipapi.co/json/\";\n // AJAX call to ip-API\n $.ajax({\n url: queryURL,\n method: \"GET\"\n })\n // Stores all of the retrieved data inside of an object called \"response\"\n .then(function(response) {\n // Assigns response object to global variable \n localLocation = response;\n console.log(\"ip-api lat\" + localLocation.latitude);\n console.log(\"ip-api lon\" + localLocation.longitude);\n FXdisplayLocalWeather();\n });\n \n }", "async getLocation() {\n if (status === 'granted') {\n const result = await Location.getCurrentPositionAsync({}).catch((e) => console.log(e));\n\n if (result) {\n this.props.onSend({\n createdAt: '',\n user: this.props.user,\n location: {\n latitude: result.coords.latitude,\n longitude: result.coords.longitude,\n },\n });\n }\n }\n }", "function getLocation(){\n navigator.geolocation.getCurrentPosition(connectionManager.geolocationSuccess, \n connectionManager.geolocationError, \n { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }\n );\n}", "getCoordsByAddress() {\n //API call to google to get coords when user input is an address\n var address = this.state.location.replace(' ', '+');\n var key = 'AIzaSyCrkf6vpb_McrZE8p4jg4oUH-oqyGwFdUo';\n var url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&key=' + key;\n console.log('are you in here?', url);\n fetch(url, {\n method: 'GET',\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n }\n }).then((res) => {\n return res.json(); \n }).then((resJson) => {\n this.setState({latitude: resJson.results[0].geometry.location.lat});\n this.setState({longitude: resJson.results[0].geometry.location.lng});\n })\n .then((res) => {\n this._onForward()\n })\n .catch((err) => {\n console.log('There is an error. It\\'s sad day D=', err.status, err);\n });\n }", "function getLocation() {\n\t if (navigator.geolocation) {\n\t navigator.geolocation.getCurrentPosition(getWeather);\n\t } else {\n\t alert(\"Geolocation is not supported by this browser.\");\n\t }\n\t}", "function getUserLocation() {\n fetch(`https://ipapi.co/json`)\n .then(function(response) {\n return response.json();\n })\n .then(function(recievedData) {\n displayUserLocation(recievedData);\n });\n}", "function sunRiseSunSet(latitude, longitude){\n const sunAPIKey = 'adf056764b2641d1a74b3b927c167240'\n fetch('https://cors-anywhere.herokuapp.com/https://api.ipgeolocation.io/astronomy?apiKey=' + sunAPIKey + '&lat=' + latitude + '&long=' + longitude )\n .then(response =>{\n if(response.ok){\n return response.json();\n }\n })\n .then(sunResponseJson => hereComesTheSun(sunResponseJson))\n .catch(error => alert(\"The sun's location cannot be found at this time.\"));\n}", "function success(pos) {\n currentLocation = { lat: pos.coords.latitude, \n lng: pos.coords.longitude };\n\n //map connection to HTML\n var resultsMap = new google.maps.Map(\n document.getElementById(\"map_canvas\"), {\n center: currentLocation,\n zoom: 13,\n mapTypeId: google.maps.MapTypeId.ROADMAP\n });\n\n var marker = new google.maps.Marker({\n position: currentLocation,\n map: resultsMap,\n title: 'You!'\n });\n\n //define requests for finding locations of nearests areas\n var requestAirport = {\n location: currentLocation,\n radius: '500',\n query: 'airport'\n };\n var requestSchool = {\n location: currentLocation,\n radius: '500',\n query: 'university'\n };\n console.log(\"Current Location: \"+currentLocation);\n\n}", "function geocode(){\n let address='';\n address+=$(\"#Street\").val()\n address+=' '\n address+=$(\"#City\").val()\n address+=' '\n address+=$(\"#State option:selected\").val()\n\n axios.get(\"https://maps.googleapis.com/maps/api/geocode/json\",\n {params:{\n address:address,\n key:'AIzaSyCI_QxDY3ucy2hRw7RzyKEEN4Cfq85WNU0'\n }\n})\n.then(function(response){\n var location_result=response.data.results[0].geometry.location\n var lat=location_result.lat\n var lng=location_result.lng\n formatAddress=response.data.results[0][\"formatted_address\"]\n loc = `${lat},${lng}`\n // console.log(response)\n console.log('geocode function loc',loc)\n // haha=\"http://127.0.0.1:8080/data\"\n haha=\"https://jessica-weather-app.wl.r.appspot.com/data\"\n axios.get(haha,\n {params:{\n loc:loc\n }}).then((response)=>{\n // console.log(response.data);\n weather=response.data.data.timelines\n hour=weather[0].intervals\n day=weather[1].intervals\n displayWeatherCard()\n displayWeatherTb()\n\n })\n})\n.catch(function(error){\n console.log(error);\n});\n return false\n}", "function getLocation() {\n coord = null;\n // coord = Alloy.Globals.getCurrentLocation();\n if (Ti.Geolocation.locationServicesEnabled) {\n Ti.Geolocation.purpose = \"Receive User Location\";\n Titanium.Geolocation.getCurrentPosition(function(e) {\n coord = e.coords;\n // coord = {\n // latitude : 19.0760,\n // longitude : 72.8777\n // };\n //Ti.API.info('current locations ' + JSON.stringify(coord));\n if (coord != null) {\n\n if (args.inStore) {\n //Ti.API.info('do nthing');\n getDirectionforInStore();\n } else {\n ///\n\n showLoader($.findStore);\n //now calling store locator web service\n var param = {\n latitude : coord.latitude,\n longitude : coord.longitude,\n filter : \"All\",\n storetype : \"All\"\n };\n\n var requestMethod = Alloy.Globals.commonUrl.storeList;\n var requestParams = JSON.stringify(param);\n //Ti.API.info('request Param--->' + requestParams);\n Alloy.Globals.webServiceCall(requestMethod, requestParams, _getStoreListSuccessCallback, _getStoreListErrorCallback, \"POST\", $.findStore);\n ////\n }\n } else {\n coord = null;\n //display message that location is not enabled\n setTimeout(function() {\n geolocation();\n }, 1500);\n showAlert($.findStore, \"Allow location access for D'Decor app by going to Settings\");\n\n }\n\n });\n } else {\n coord = null;\n setTimeout(function() {\n geolocation();\n }, 1500);\n //display message that location is not enabled\n showAlert($.findStore, \"Allow location access for D'Decor app by going to Settings\");\n\n }\n\n}", "function getLocation(location) {\n\t lat = location.coords.latitude;\n\t lng = location.coords.longitude;\n\t\tgetVenues();\n\t}", "function submitLocation() {\n fetch(apiURL)\n .then((response) => response.json())\n .then((data) => {\n setWeather(data.weather[0].description);\n setTemperature(data.main.temp);\n setMin(data.main.temp_min);\n setMax(data.main.temp_max);\n setHumidity(data.main.humidity);\n setWind(data.wind.speed);\n setIcon(data.weather[0].icon);\n return;\n });\n }", "function requestPosition(busid) {\n var urlString = 'http://112.78.3.114/api/ShuttleBusesTrackings/' + busid;\n $http({\n method: 'GET',\n url: urlString,\n }).then(function successCallback(response) {\n var outcome = response.data;\n GlobalJSONString += JSON.stringify(outcome) + \",\";\n $scope.Longitude = outcome.Longitude;\n $scope.Latitude = outcome.Latitude;\n var newMarker = {\n lat: $scope.Latitude,\n long: $scope.Longitude\n };\n markers.push(newMarker);\n console.log(markers.length);\n }, function errorCallback(error) {\n console.log(error);\n });\n }", "function getAQI(lat,lon) {\n fetch(`${temp.base}lat=${lat}&lon=${lon}&appid=${temp.key}`)//fetching data from api\n .then(aqi => {\n return aqi.json();\n }).then(displayResults);//function call to display results\n}", "function getLocation() {\n if (navigator.geolocation) {\n navigator.geolocation.getCurrentPosition(createMap);\n } \n }", "async function findlocation(lat, long) {\n try {\n const res = await fetch(\n `https://api.opencagedata.com/geocode/v1/json?q=${lat}+${long}&key=c8105eebae7b4212a76c2d1f7510cc67`\n );\n const data = await res.json();\n\n console.log(data);\n weather(data.results[0].components.city);\n } catch (err) {\n console.log(err);\n }\n}", "function getUserLocation() {\n let url = \"https://www.googleapis.com/geolocation/v1/geolocate?key=\" + MAPSKEY;\n const request = new Request(url, {method: \"POST\"});\n return new Promise((resolve, reject) => {\n if (navigator.geolocation) {\n navigator.geolocation.getCurrentPosition(function(position) {\n userLocation = {lat: position.coords.latitude, lng: position.coords.longitude};\n userActualLocation = userLocation;\n resolve(userLocation);\n }, function() {\n fetch(request).then(response => {\n if (response.status == 400 || response.status == 403 || response.status == 404) {\n reject(\"User location failed\");\n } else {\n response.json().then(jsonresponse => {\n userLocation = jsonresponse[\"location\"];\n userActualLocation = userLocation;\n resolve(userLocation);\n });\n }\n });\n });\n } else {\n fetch(request).then(response => {\n if (response.status == 400 || response.status == 403 || response.status == 404) {\n reject(\"User location failed\");\n } else {\n response.json().then(jsonresponse => {\n userLocation = jsonresponse[\"location\"];\n userActualLocation = userLocation;\n resolve(userLocation);\n });\n }\n });\n }\n });\n}", "function getLocation() {\n // var x;\n // function getLocation() {\n // if (navigator.geolocation) {\n // document.getElementById(\"start\").value = 34.0666664 , -118.167332664;\n // navigator.geolocation.watchPosition(showPosition);\n // } else { \n // x = \"Geolocation is not supported by this browser.\";}\n // } \n \n // function showPosition(position) {\n // // lat: 34.0666664 , lng: -118.167332664\n // x= position.coords.latitude +\",\"+ position.coords.longitude;\n \n // }\n}", "async function geoCityToCoords(conv, city, gender, occasion) {\n var lat;\n var lng;\n // Connecting to maps api\n await axios.get(`https://maps.googleapis.com/maps/api/geocode/json?address=${city}}&key=AIzaSyDRzIANAmqLQ3Dyl5yJzuy49oJBzlmhBQA`)\n .then((result) => {\n console.log(result);\n lat = result.data.results[0].geometry.location.lat;\n lng = result.data.results[0].geometry.location.lng;\n console.log(`The lattitude is ${lat} and longitude is ${lng}`);\n })\n .catch((error) => {\n console.log(\"Trouble getting lattitude and longitude.\");\n console.log(error);\n });\n return getLocationIdForAccuweather(conv, lat, lng, city, gender, occasion);\n\n}" ]
[ "0.7399205", "0.73102677", "0.7000668", "0.69905716", "0.69310445", "0.6811851", "0.6776365", "0.6757845", "0.6723161", "0.6683847", "0.6683749", "0.66799676", "0.66645867", "0.6647183", "0.66125035", "0.6608227", "0.6607157", "0.6599003", "0.65953654", "0.6591343", "0.6572172", "0.6559486", "0.6511429", "0.65097886", "0.6509172", "0.64933825", "0.6485593", "0.6479396", "0.64663696", "0.64623666", "0.6460306", "0.645273", "0.6438339", "0.64356345", "0.6422169", "0.6393182", "0.63912034", "0.63800406", "0.6379855", "0.63746965", "0.6363401", "0.6362685", "0.6359183", "0.6358246", "0.63577324", "0.63480574", "0.6338902", "0.63357127", "0.6332553", "0.6332381", "0.63169175", "0.63141125", "0.63140136", "0.62986135", "0.6296285", "0.62911105", "0.6290187", "0.62874997", "0.6283037", "0.6279903", "0.6264034", "0.6260545", "0.625959", "0.6257208", "0.6255848", "0.62538517", "0.6251777", "0.6247551", "0.6243257", "0.62421834", "0.6235093", "0.62293255", "0.6224413", "0.6219186", "0.6214981", "0.6204867", "0.61965036", "0.6193324", "0.61918104", "0.6189269", "0.6189169", "0.61864763", "0.6184556", "0.6182328", "0.6181032", "0.61805445", "0.6179246", "0.6177369", "0.61743164", "0.6170207", "0.61672586", "0.6164694", "0.61634815", "0.6158879", "0.6153401", "0.6152351", "0.6150511", "0.614627", "0.61452115", "0.6142132", "0.613915" ]
0.0
-1
a variable that used to record the starting temperature during an automatic heating process ///////////////////////////// A basic device
function Device(listen_port) { //a basic device. Many functions are stubs and or return dummy values //listen_port: listen for http requests on this port // HEL.call(this,'cmd',listen_port); //init device info this.port = listen_port; this.status = "ready"; //other options are "logging" this.state = "none"; //no other state for such a simple device this.uuid = this.computeUUID(); //some device state this.logging_timer = null; this.manager_port = null; this.manager_IP = null; //standard events this.addEventHandler('getCode',this.getCodeEvent); this.addEventHandler('getHTML',this.getHTMLEvent); this.addEventHandler('info',this.info); this.addEventHandler('ping',this.info); this.addEventHandler('acquire',this.acquire); //implementation specific events //TODO: REPLACE THESE TWO EVENTS WITH YOUR OWN this.addEventHandler('startLog',this.startLogging); this.addEventHandler('stopLog',this.stopLogging); this.addEventHandler('heatOn',this.heaton); this.addEventHandler('heatOff',this.heatoff); this.addEventHandler('heatAutomatic',this.heatpwm); this.addEventHandler('heatAutomaticEnd', this.heatAutomaticEnd); this.addEventHandler('desiredTemp',this.desiredTemp); this.addEventHandler('cellphoneNumber',this.cellphoneNumber); //manually attach to manager. this.manager_IP = 'bioturk.ee.washington.edu'; this.manager_port = 9090; this.my_IP = OS.networkInterfaces().eth0[0].address; this.sendAction('addDevice', {port: listen_port, addr: this.my_IP}, function(){}); //advertise that i'm here every 10 seconds until i'm aquired /*var this_device = this; this.advert_timer = setInterval(function(){ this_device.advertise('224.250.67.238',17768); },10000);*/ }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function temp_sensor() {\r\n var celsius = temp.value();\r\n var fahrenheit = celsius * 9.0/5.0 + 32.0;\r\n console.log(celsius + \" degrees Celsius, or \" +\r\n Math.round(fahrenheit) + \" degrees Fahrenheit\");\r\n\r\n deviceClient.publish(\"status\",\"json\",'{\"d\" : { \"temperature\" : '+ celsius +'}}');\r\n setTimeout(temp_sensor,1000);\r\n\r\n}", "constructor(temperature = 20) {\n this.temperature = temperature;\n this._minTemp = 10;\n this.powerSave = true;\n this._maxTemp = 25;\n }", "function getTemperature (event) {\n // read variables from the event\n let ev = JSON.parse(event.data);\n let evData = ev.data; // the data from the argon event: \"pressed\" or \"released\"\n let evDeviceId = ev.coreid; // the device id\n let evTimestamp = Date.parse(ev.published_at); // the timestamp of the event\n let alrtDevice = 0;\n\n // helper variables that we need to build the message to be sent to the clients\n let message = \"Verbindung zu deinem smarten Brandmelder ist aktiv.\";\n var floatValue = parseFloat(evData);\n var correctednewTempValue = ((floatValue - 4)*10)/10;\n let difference = correctednewTempValue-correctedoldTempValue;\n correctedoldTempValue = correctednewTempValue;\n let newTempValue = correctednewTempValue;\n if( difference > 0.5 ){\n alrtDevice = 1;\n }\n else{\n alrtDevice = 0;\n }\n // send data to all connected clients\n sendData(\"temperature\", newTempValue, message, evDeviceId, evTimestamp, alrtDevice);\n}", "constructor(tempf) {\n this._temperature = tempf;\n }", "temperature() {\n this.setup();\n\n // in order to read multiple bytes the high bit of the sub address must be asserted\n return twos_comp(this.i2c_bus.read_word_data(this.addr, TEMP_OUT_L|0x80), 12);\n }", "function create_temperature_synth(){\n var bus_num = create_new_bus(context.destination);\n var convolver = add_convolution(bus_num);\n dry_wet(bus_num, 1, 10);\n var filter = add_filter(bus_num, \"lowpass\", 3000, 30);\n var mod1 = add_osc_modulator(bus_num, 0, 0, \"frequency\", 440, 4, 25)\n var mod2 = add_osc_modulator(bus_num, 0, 0, \"frequency\", 440, 2, 50)\n add_ADHSR_env(bus_num, 0.01, 0.2, 0, 0, 0.2);\n //add_osc_modulator(bus_num, 2, 0, \"frequency\", 1, 0.1, 75)\n set_bus_gain(bus_num, 0.03);\n return [buses[bus_num][0][0], convolver, filter, mod1, mod2]\n}", "get temperature() {\n // convertimos los grados F a C\n this.temperature_F = 5 / 9 * (this.temperature_F - 32)\n return this.temperature_F;\n }", "function setSensor(temHum) {\n TEM_SENSOR.currentTemperature = temHum.temperature;\n\n temSensor.getService(Service.TemperatureSensor)\n .setCharacteristic(Characteristic.CurrentTemperature, TEM_SENSOR.getTemperature());\n}", "function monitorTemperature() {\n var prev = 0;\n \n setInterval(function() {\n var currentTemp = board.getTemperature();\n var currentLight = board.getLight();\n board.message(\"Temperature: \" + currentTemp);\n board.message(\"Light Level: \" + currentLight, 1);\n\n // check if fire alarm should be triggered\n if (prev < config.ALARM_THRESHOLD && currentTemp >= config.ALARM_THRESHOLD) {\n events.emit(\"start-alarm\");\n }\n\n if (prev >= config.ALARM_THRESHOLD && currentTemp < config.ALARM_THRESHOLD) {\n events.emit(\"stop-alarm\");\n }\n\n prev = currentTemp;\n \n //AUTOMATION LOGIC\n /**\n\n //TOO COLD\n if ( flueTemp < 150 ){\n fireStatus = low;\n\n //// Fire is just starting\n if( flameSensor == true ){\n notify(\"Keep an eye on it.\");\n damper.position = 100;\n }\n\n //fire is dying\n if( flameSensor == false ){\n alarm();\n notify(\"Low fire. Creosote danger. Add wood.\");\n damper.position = 0;\n\n }\n }\n\n // JUST RIGHT\n if ( flueTemp > 150 && flueTemp <= 400){\n fireStatus = good;\n alarm();\n notify(\"Nice fire.\")\n damper.position = 50;\n }\n\n //TOO HOT\n if ( flueTemp > 400 && flueTemp <= 600){\n fireStatus = hot;\n if( flameSensor == true ){\n alarm();\n notify(\"The fire is too hot. Adjusting damper.\"\n) damper.position = 20;\n }\n if( flameSensor == false ){\n alarm();\n notify(\"Your fire is out but your chimney is on fire.\"\n) damper.position = 0;\n }\n }\n\n **/\n \n \n //monitor Button\n //readButtonValue(); \n\n \n \n \n \n \n }, 500);\n}", "function getTemperature() {\n local supplyVoltage = hardware.voltage();\n local voltage = supplyVoltage * Temperature.read() / 65535.0;\n local c = (voltage - 0.5) * 100 ;\n local celsius = format(\"%.01f\", c);\n return(celsius);\n}", "get temperature() {\n return (5 / 9) * (this.fahrenheit - 32);\n }", "function setTemperature() {\n setInterval(function() {\n var change = genValue(-5, 5);\n if ((temperature + change) > tR[1] || (temperature + change) < tR[0]) {\n return temperature;\n } else {\n temperature += change;\n return temperature;\n }\n }, 30000);\n}", "function readSensor(){\n sensor.read(SENSORTYPE, GPIOPIN, function(err, temperature, humidity) {\n if (!err) {\n console.log('temp: ' + temperature.toFixed(1) + 'C, ' + 'humidity: ' + humidity.toFixed(1) + '%');\n } else {\n console.log(err);\n }\n });\n}", "function connectHardware() {\n const sensorDriver = require('node-dht-sensor');\n var sensor = {\n //Initialize sensor \n initialize: function () {\n return sensorDriver.initialize(11, model.temperature.gpio); //#A\n },\n // Read sensor\n read: function () {\n //Read temperature and humidity values\n var readout = sensorDriver.read();\n var temperatureValue = parseFloat(readout.temperature.toFixed(2));\n var humidityValue = parseFloat(readout.humidity.toFixed(2)); //#C\n \n //Update Temparature and Humidity model \n model.temperature.value = temperatureValue;\n model.humidity.value = humidityValue;\n\n //observe temperature resource model to watch critical value \n var critiaclTemp = observe(model.temperature);\n critiaclTemp.value = parseFloat(temperatureValue);\n \n //Check sensor values on console \n //console.log(\"Temparature is:\" +temperatureValue)\n //console.log(\"Humidity is:\" + humidityValue) \n\n //Send sensor data on web socket\n ws.send(model.temperature.value)\n\n // Set interval time for sensor\n setTimeout(function () {\n sensor.read();\n }, model.temperature.interval);\n }\n };\n\n if (sensor.initialize()) {\n console.info('Hardware temperature & humidity sensor is started!');\n sensor.read();\n } else {\n console.warn('Hardware temperature & humidity is failed to initialize !');\n }\n}", "function fdibTemp(h){\r\n\tthis.drawTemp = h;\r\n}", "function sensorCheck() {\n console.log( '\\u001B[2J\\u001B[0;0f' )\n var temperatureC = ( analogPin0.read()*5.0/1024.0 - 0.5 ) * 100\n var temperatureF = temperatureC * 9/5.0 + 32\n console.log( \"Temperature is \" + temperatureF + \" degrees F\" );\n var photosense = ( 512 - analogPin1.read() );\n console.log( \"Light reading is \" + photosense + \" brightness\" );\n var audiosense = ( analogPin2.read() );\n console.log( \"Ambient noise reading is \" + audiosense );\n}", "function temperatureHandler( event, device, controlId ) {\n var thermostat = $(\"#\" + device.id);\n thermostat.val(device.state); \n\n //udpate the server with data set by remote control\n var data = JSON.stringify(device)\n updateDevice(data);\n\n $( document ).trigger( \"confirmTemperatureEvent\", [ controlId, device.state ] );\n }", "function temperature_change(){\n a_FAO_i='temperature_change';\n initializing_change();\n change();\n}", "function makess(){\r\n class Thermostat{\r\n constructor(temp)\r\n { //private variable\r\n this._temp=5/9*(temp-32) // celsius \r\n }\r\n //getter\r\n get temperature(){\r\n return this._temp;\r\n }\r\n set temperature(updatedtemp){\r\n this._temp=updatedtemp;\r\n }\r\n }\r\n return Thermostat;\r\n}", "function updateHVACDriverTempDisplay(temp) {\n\t$(\"#environmentData .temperature .value\").text(temp);\n}", "async function measureTemperature() {\n try {\n const temperature = await bme680.temperatureSensor.read();\n console.log(`Temperature (degrees C): ${temperature}`);\n } catch(err) {\n console.error(`Failed to measure temperature: ${err}`);\n }\n}", "function startCurrentTempInterval(){\n setInterval(function(){\n getCurrentTemp();\n }, CURRENT_TEMP_TIMER);\n}", "function controlTemperature(now) {\n var requestedPower = state.power;\n var target = 72;\n\n // currently just supporting one control mode: manage enclosure temperature\n if (config.mode == constants.ENCLOSURE) {\n // control enclosure temperature\n target = state.enclosureTemp;\n } else if (config.mode == FERMENTATION) {\n // control the fermentation temperature\n // TODO Implement!\n var error = state.fermentationTemp - config.fermentationTemp;\n var target = config.fermentationTemp - (10 * error);\n if (target < config.minEnclosureTemp) {\n target = config.minEnclosureTemp;\n }\n }\n\n // due to considerable heat capacity in the refrigeration system, the enclosure\n // will continue to cool for a while after the power is turned off.\n if (target > config.targetEnclosureTemp + 1) {\n requestedPower = 1;\n } else if (target < config.targetEnclosureTemp) {\n requestedPower = 0;\n }\n\n return requestedPower;\n}", "function sensor(num,sense)\n{\t\n\tvar i;\n\tbase = Number(num);\n\tbase_h = 40\n\tsensorNum = Number(sense)\n\talarm = 0\n\terror = 0\n\trownumber=0\n\twhile(true)\n\t{\tvar r1 = getRandomInt(1,101) // Random event generator for temperature\n\t\tif(r1>=91 && r1<=95)\t\t// 5% chance for -3 to -8\n\t\t{\n\t\t\tt = base + getRandomInt(-8,-2)\n\t\t}\n\t\telse if(r1>=95 && r1<=100)\t\t// 5% chance for 3 to 8\n\t\t{\t\n\t\t\tt = base + getRandomInt(3,9)\n\t\t}\n\t\telse if(r1>=81 && r1<=90)\t\t// 10% chance for error number\n\t\t{\t\n\t\t\tt = 999\n\t\t\terror+=1\n\t\t}\n\t\telse\n\t\t{\t\n\t\t\tt = base + getRandomInt(-2,2)\n\t\t}\n\t\tvar r1 = getRandomInt(1,101) // Random event generator for temperature\n\t\tif(r1>=91 && r1<=95)\t\t// 5% chance for -3 to -8\n\t\t{\n\t\t\th = base_h + getRandomInt(-40,-9)\n\t\t}\n\t\telse if(r1>=95 && r1<=100)\t\t// 5% chance for 3 to 8\n\t\t{\t\n\t\t\th = base_h + getRandomInt(10,41)\n\t\t}\n\t\telse if(r1>=81 && r1<=90)\t\t// 10% chance for error number\n\t\t{\t\n\t\t\th = 999\n\t\t\terror+=1\n\t\t}\n\t\telse\n\t\t{\t\n\t\t\th = base_h + getRandomInt(-2,2)\n\t\t}\n\t\tvar d= new Date()\n\t\tvar timestamp=d.toLocaleString();\n\t\t\n\t\tvar data = {\n\t\t\t\"id\" : ++rownumber,\n\t\t\t\"Timestamp\" : timestamp,\n\t\t\t\"sensorid\" : sensorNum,\n\t\t\t\"Temperature\" : t,\n\t\t\t\"Humidity\" : h,\n\t\t\t\"Alarm_Count_Temp\" : alarm,\n\t\t\t\"Alarm_Count_Hum\" : alarm,\n\t\t\t\"ErrorCount\" : error\n\t\t}\n\n\t\tprocess.send(data);\t// sends data to mysql\n\t\tsleep(10000);\n\t};\n}", "function setHeat(state){\r\n if(ENV==\"devel\") digitalWrite(HEAT_PIN,state);\r\n else digitalWrite(HEAT_PIN,!state);\r\n}", "get tempF (){\n console.log('calculating temp in F');\n return this.tempC * (9/5) + 32;\n }", "async setDeviceCharacteristic() {\n const service = await this.device.gatt.getPrimaryService(0xfff1);\n const vendor = await service.getCharacteristic(\n \"d7e84cb2-ff37-4afc-9ed8-5577aeb84542\"\n );\n this.cpuVendor = vendor;\n\n const speed = await service.getCharacteristic(\n \"d7e84cb2-ff37-4afc-9ed8-5577aeb84541\"\n );\n this.cpuSpeed = speed;\n }", "function arduino_due_1(result)\n{\n var date = new Date(1528214746 *999);\n console.log(\"arduino_due_1\");\n console.log(result);\n if(first)\n {\n fakehistoricadata(date.toString().substr(0,24))\n first = false\n }\n\n\n updateMovement(result, 1, options)\n updateHumidity(result, 4, options )\n updateDistance(result, options)\n updateTemperature(result,4, options)\n updateSoundLevel(result, 1, options)\n}", "function showTemp(data){\r\n\tconsole.log(data.temp);\r\n\tCurrentTemp = data.temp;\r\n}", "function telemetry() {\n\tlet status = document.getElementById('status');\n\tvar newMeasurement = {};\n\tlet sensor = new Accelerometer();\n\tsensor.addEventListener('reading', function(e) {\n\t\tstatus.innerHTML = 'x: ' + e.target.x + '<br> y: ' + e.target.y + '<br> z: ' + e.target.z;\n\t\tnewMeasurement.x = e.target.x;\n\t\tnewMeasurement.y = e.target.y;\n\t\tnewMeasurement.z = e.target.z;\n\t});\n\tsensor.start();\n\treturn newMeasurement;\n}", "startData() { return {\r\n unlocked: false,\r\n\t\tpoints: new ExpantaNum(0),\r\n arrows: new ExpantaNum(3),\r\n basepoints1: new ExpantaNum(1.0001),\r\n basepoints2: new ExpantaNum(1),\r\n tbasepoints2: new ExpantaNum(1),\r\n tickspeed: new ExpantaNum(0),\r\n tick: new ExpantaNum(0),\r\n }}", "function generateWeatherData() {\n const minTemp = 20;\n const maxTemp = 25;\n const minHum = 35;\n const maxHum = 45;\n\n let temp = minTemp;\n let hum = minHum;\n\n console.log(`Starting generation of weather data`);\n setInterval(function(){ \n \n // Generate new temperature\n let tempStep = +(getRandomValue(-5, 5)/10).toFixed(2);\n if(temp + tempStep > maxTemp || temp + tempStep < minTemp) {\n tempStep*=-1;\n }\n temp+=tempStep;\n\n client.publish('weather/temperature', JSON.stringify({'value': temp, 'timestamp': Date.now}));\n\n // Generate new humidity\n let humStep = +(getRandomValue(-2, 3)/10).toFixed(2);\n if(hum + humStep > maxHum || hum + humStep < minHum) {\n humStep*=-1;\n }\n hum+=humStep;\n\n client.publish('weather/humidity', JSON.stringify({'value': hum, 'timestamp': Date.now}));\n\n\n }, 3000);\n}", "function temperature() {\n var roll = dice.d(20);\n // Its a normal day\n if (roll < 15) {\n return 90 + dice.d(9);\n }\n // extreme heat\n if (roll > 17) {\n return 100 + dice.d(10);\n }\n // random heavy cold front\n if (roll > 14 && roll < 18) {\n return 95 - (dice.d(4) * 10);\n }\n}", "function updateTempIndoor(cb) {\n current.board.temp.getCurrentTemp(function(err, temp) {\n if (!err) {\n current.status.temp_indoor = temp;\n } else log.error(\"error reading Temp indoor: \" + err);\n cb();\n });\n }", "function Trv (currentTemperature, targetTemperature, ambientTemperature, name) {\n this.id = uuidv4()\n this.currentTemperature = currentTemperature || undefined\n this.targetTemperature = targetTemperature || ambientTemperature\n this.ambientTemperature = ambientTemperature || undefined\n this.name = name || undefined\n this.serialId = _generateSerialId()\n this.active = false\n this.activeSchedules = []\n this.metadata = {}\n}", "function Sensor() {\n this.adapters = []\n this.fanSpeed = \"\"\n this.xAxis = ['0']\n this.grid = undefined\n}", "loadTemp() {\n\t\tthis.loadMaxCurrentMinTemp();\n\t\tapiCall('iot/api/temp/hour')\n\t\t\t.then((response) => {\n\t\t\t\tthis.tempData = response;\n\t\t\t\tthis.drawChartTemp();\n\t\t\t});\n\t\twindow.clearInterval(this.interval);\n\t\tthis.interval = window.setInterval(this.loadMaxCurrentMinTemp.bind(this), 1000);\n\t}", "temp(celsius, fahrenheit)\n\n {\n const cTemp = celsius;\n const cToFahr = cTemp * 9 / 5 + 32;\n console.log(\"Celsius to Fahrenheit:\" + celsius + \"to\" + cToFahr); // (°C × 9/5) + 32 = °F\n const fTemp = fahrenheit;\n const fToCel = (fTemp - 32) * 5 / 9;\n console.log(\"Fahrenheit to Celsius:\" + fahrenheit + \"to\" + celsius);\n\n\n }", "startData() { return {\r\n unlocked: false,\r\n points: new Decimal(0),\r\n best: new Decimal(0),\r\n energy: new Decimal(0),\r\n first: 0,\r\n auto: false,\r\n pseudoUpgs: [],\r\n autoExt: false,\r\n }}", "initializeRegularBeaker()\n {\n //Water should be some reasonable value.\n this.water = STARTING_WATER_LEVEL;\n\n //Everything else should be Zero.\n this.red = this.green = this.blue = 0;\n\n this.ph = 7.0;\n\n this.color = Difficulty_1_Colors.WATER;\n\n\n this.temperature = STARTING_TEMPERATURE;\n }", "function setTemperatureMode(){\n var fileName = (tempMode == \"Celsius\" ? \"setF\": \"setC\");\n var req = getHTTPRequestObject(sensorServerURL + fileName);\n\n req.onload = function(e) {\n if (req.readyState == 4 && req.status == 200) {\n console.log(\"Request: \" + sensorServerURL + fileName + \" success\");\n getWeather();\n } else {\n logError(sensorServerURL + fileName);\n }\n };\n req.send(null);\n}", "function dataGenerator() {\r\n return {\r\n temperature: getRandomNumber(20,30),\r\n batteryLevel : getRandomNumber(80, 100),\r\n timeStamp : getTimeStamp(),\r\n msTime: Date.now()\r\n }\r\n}", "function weatherVar(){\n //City Name\n cityName = weather.name;\n //Country Code\n country = weather.sys.country;\n //Weather ID\n weatherId = weather.weather[0].id;\n weatherDescription = weather.weather[0].description;\n //Temperature\n temp = round(weather.main.temp);\n //Get data based on last weather update\n epochUpdate = weather.dt;\n //Type of clouds\n Cloudiness = weather.clouds.all;\n //Wind Speed\n windSpeed = weather.wind.speed;\n windRatio = windSpeed / 200;\n windDegrees = weather.wind.deg;\n //Visibility & Humidity\n visibility = map(weather.visibility, 0, 10000, 0, 255);\n humidity = weather.main.humidity;\n}", "function SmartPlantEater () {\n this.energy = 20\n this.didNotReproduceInPreviousTurn = true\n}", "function setup() {\n cnv = createCanvas(displayWidth / 2, displayHeight / 5);\n cnv.parent(\"termo-container\");\n // Gets a change whenever the temperature sensor changes and sets it to its element\n socket.on('temperature', function(temperature) {\n $(\"#termometer\").val(temperature + \"°C\");\n createPoint(temperature);\n });\n}", "function smarty_startReader() {\n\tvar fs = require('fs'),\n\t\tdate = new Date(),\n\t\ttimestamp,\n\t\tgpioFileName = global.gpio_path+'gpio'+global.gpio_input_pin+'/value',\n\t\tmessage=\"\",\n\t\twatts = 0;\n\n\tmessage += '{';\n\tmessage += '\"term\":\"'+global.location+'.powerConsumption.'+ global.gpio_input_pin+'\"';\n\n\n\tfs.readFile (gpioFileName, function(err, inputValue) {\n\t\tif(err) {\n\t console.log(err);\n\t } else {\n\t\t\tif (smarty.lastValue+0 != inputValue+0 ) {\n\t \t//global.log('gpio_input_pin was '+smarty.lastValue+' and changed to: ' + inputValue +': now=' + new Date().getTime());\n\t\t\t\tsmarty.lastValue = inputValue;\n\t\t\t\ttimestamp = date.getTime();\n\t\t\t\twatts = powerConsumption (timestamp, smarty.secondLastTimestamp, inputValue);\n\n\t\t\t\tmessage += ', \"Watt\":'+watts;\n\t\t\t\tmessage += ', \"timestamp\":' + timestamp;\n\t\t\t\tmessage += '}';\n\t\t\t\n\t\t\t\t// only l trigger to og stuff, if there is a significant power consumption, \n\t\t\t\t// i.e. not at startup or reboot time\n\t\t\t\tif (watts > 1)\n\t\t\t\t\tglobal.eE.emit('pinChange', message);\n\n\t\t\t\tsmarty.secondLastTimestamp = smarty.lastTimestamp;\n\t\t\t\tsmarty.lastTimestamp = timestamp;\n\t\t\t}\n\t\t}\n\t});\n\t\t\n\tglobal.timers.setTimeout (smarty_startReader, smarty.polling_intervall);\n\treturn this;\n}", "function changeTemp() {\n\t\tvar temperature = Math.round(days[document.getElementById(\"slider\").value].\n\t\t\tquerySelector(\"temperature\").textContent);\n\t\tdocument.getElementById(\"currentTemp\").innerHTML = temperature + \"&#8457\";\t\n\t}", "startData() { return {\r\n unlocked: false,\r\n points: new Decimal(0),\r\n best: new Decimal(0),\r\n total: new Decimal(0),\r\n energy: new Decimal(0),\r\n time: new Decimal(0),\r\n auto: false,\r\n first: 0,\r\n pseudoUpgs: [],\r\n }}", "function setup() {\n // Enable register\n rgbSensor.writeByte(0x80|0x00, function(err){});\n\n // Power on and enable RGB sensor\n rgbSensor.writeByte(0x01|0x02, function(err){});\n\t\n // Read results from Register 14 where data values are stored\n // See TCS34725 Datasheet for breakdown\n rgbSensor.writeByte(0x80|0x14, function(err){});\n}", "function VelbusTemperature(config) {\n\n\t\tRED.nodes.createNode(this, config);\n\n\t\tthis.name = config.name;\n\t\t// Retrieve the config node\n\t\tthis.connector = RED.nodes.getNode(config.connector);\n\t\tconnector = this.connector;\n\t\tthis.address = config.addressType === \"MANUAL\" ? parseInt(config.address) : parseInt(config.addressType);\n\t\tthis.mode = parseInt(config.modeType);\n\n\t\tif (connector && connector.velbus) {\n\t\t\tthis.status({fill: \"green\", shape: \"dot\", text: `Velbus ready`});\n\t\t} else {\n\t\t\tthis.status({fill: \"red\", shape: \"dot\", text: `No Velbus connector node found: Add one first!`});\n\t\t\treturn\n\t\t}\n\t\tconnector.velbus.on('onError', msg => {\n\t\t\tthis.status({fill: \"red\", shape: \"dot\", text: msg});\n\t\t});\n\t\tconnector.velbus.on('onStatus', msg => {\n\t\t\tthis.status({fill: \"green\", shape: \"dot\", text: msg});\n\t\t});\n\n\t\tconnector.velbus.on('onSerialPacket', packet => {\n\n\t\t\tif (packet.address === this.address) {\n\n\t\t\t\tif (packet.command === constants.commands.COMMAND_TEMPERATURE_SENSOR_TEMPERATURE) {\n\t\t\t\t\t//console.log(`pushed ${packet.getRawDataAsString()}`);\n\n\t\t\t\t\tconst highByteCurrentSensorTemperature = packet.rawPacket[5];\n\t\t\t\t\tconst lowByteCurrentSensorTemperature = packet.rawPacket[6];\n\n\t\t\t\t\tconst tempC = ((highByteCurrentSensorTemperature << 3) + (lowByteCurrentSensorTemperature >> 5))\n\t\t\t\t\t\t\t* 0.0625 * ((lowByteCurrentSensorTemperature & 0x1F) === 0x1F ? -1 : 1);\n\n\t\t\t\t\tconst tempF = tempC * 9/5 + 32;\n\n\t\t\t\t\tthis.status({\n\t\t\t\t\t\tfill: \"green\",\n\t\t\t\t\t\tshape: \"dot\",\n\t\t\t\t\t\ttext: `Temperature is ${tempC}°C @ ${new Date().toLocaleDateString()} - ${new Date().toLocaleTimeString()}`\n\t\t\t\t\t});\n\n\t\t\t\t\tthis.send(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpayload: tempC,\n\t\t\t\t\t\t\t\tfahrenheit: tempF,\n\t\t\t\t\t\t\t\tcelcius: tempC\n\t\t\t\t\t\t\t});\n\n\t\t\t\t}\n\t\t\t}\n\n\t\t});\n\n\t\tthis.on('input', msg => {\n\t\t\t// console.log(\"input\", msg);\n\t\t\tsendRequest(this);\n\t\t});\n\n\t\t/*\n\t\t(valid range: 10…255s)\n\t\t(5…9 = auto send on temperature change >=0.5°)\n\t\t(1…4 = auto send disabled)\n\t\t(0 = no change on auto send interval)\n\t\t */\n\n\t\tsendRequest(this);\n\n\n\t}", "function temperature(params) {\n var temperature = params[0];\n return Math.floor(temperature) + \"°\";\n }", "function readSensorData() {\n \t bme280.readSensorData()\n .then((data) => {\n // temperature_C, pressure_hPa, and humidity are returned by default.\n temperature = data.temperature_C + 273.15;\n pressure = data.pressure_hPa * 100;\n humidity = data.humidity / 100;\n dewPoint = calculateDewpoint(data.temperature_C, humidity);\n\n //console.log(`data = ${JSON.stringify(data, null, 2)}`);\n\n // create message\n var delta = createDeltaMessage(temperature, humidity, pressure, dewPoint)\n\n // send temperature\n app.handleMessage(plugin.id, delta)\n\n })\n .catch((err) => {\n console.log(`BME280 read error: ${err}`);\n });\n }", "static async updateTemp() { \n\t\tlet weatherData = await Weather.getWeather();\n document.querySelector(\".wind-dir\").innerHTML = `${weatherData[0].wind_deg} <sup>o</sup>`;\n document.querySelector(\".wind-speed\").innerText = `${weatherData[0].wind_speed} km/h`;\n\t\tlet forecasts = Array.from(forecastContents);\n\t\tforecasts.forEach(item => {\n\t\t\tlet temp = Math.round(weatherData[forecasts.indexOf(item)].temp.day);\n\t\t\titem.querySelector(\".degree-num\").innerText = `${temp}`;\t\t\n\t\t})\n\t}", "function getTemp(celsius, bool){\n var temp;\n if(bool == true){\n temp = celsius*1.8 + 32;\n }else{\n temp = celsius;\n }\n return temp.toFixed(1);\n }", "function getColorTemp(temp) {\n//turn the power on, if already on, this will not turn it off\n//Needed because 'set_bright' only works if the bulb is on\n let message;\n if (temp < LOW_TEMP) {\n return \"2700\";\n } else if (temp > HIGH_TEMP) {\n return \"6500\";\n } else {\n let increment = ((6500 - 2700) / (HIGH_TEMP - LOW_TEMP)) || 1;\n return \"\" + (6500 - increment * (temp - LOW_TEMP));\n }\n}", "handleStartMeterReading(event){\n \n this.startMeterReading = event.target.value;\n \n this.updateKmDriven();\n }", "function createLineControllerTemperature(IdElement) {\n let ctx = document.getElementById(IdElement).getContext('2d');\n window.linhaGraficoControllerTemperature = new Chart(ctx, configGraficoControllerTemperature);\n getLastThingSpeakDataControllerTemperature(357142, 7, 20);\n}", "function temperature(sensorNum, options, callback) {\n if (options instanceof Function) {\n callback = options;\n options = {};\n }\n\n fs.readFile(W1_DEVICES_DIR + sensorNum + W1_SLAVE_FILE, 'utf8', function(err, data) {\n if (err) {\n return callback(err);\n }\n\n try {\n return callback(null, parseData(data, options));\n } catch (e) {\n return callback(new Error('Can not read temperature for sensor ' + sensorNum));\n }\n });\n}", "function simulatedValues() {\n var now = new Date().getTime();\n\n // Simluate ESP32 data\n var values = {\n wt: getSinValue(0, 120, now),\n tps: getSinValue(0, 150, now += 500),\n bat: getSinValue(0, 150, now += 500),\n fuel: ((getSinValue(0, 100, now += 500) / 100.0) * 400.0) + 490.0,\n rpm: getSinValue(0, 9000, now += 500),\n map: getSinValue(0, 30, now += 500),\n mat: getSinValue(0, 120, now += 500),\n auxt: getSinValue(0, 120, now += 500),\n afr: getSinValue(0, 23, now += 500),\n gpsFix: 0\n };\n\n if (simulateGPSConnected) {\n values.gpsFix = 1;\n values.gpsLatitude = getSinValue(-90, 90, now += 500);\n values.gpsLongitude = getSinValue(-180, 180, now += 500);\n values.gpsLat = 0;\n values.gpsLon = 0;\n values.gpsSpeed = getSinValue(0, 250, now += 500) / 1.852;\n values.gpsAngle = 0;\n values.gpsAlt = 0;\n values.gpsQual = 0;\n values.gpsSats = 0;\t\n }\n\n return values;\n}", "function temperatureConversion(t, hardware) {\n console.assert(hardware);\n if (t==0 || t==4095) {\n return null; \n }\n var tempHWParam = 100000;\n if (hardware == \"hw33\") {\n tempHWParam = 10000;\n }\n // convert to raw volts \n const soilTempConverted1 = ((t/4095)*3.3);\n const soilTempConverted2 = ((soilTempConverted1*tempHWParam)/(3.3 - soilTempConverted1));\n const soilTempConverted3 = (Math.log(10000/soilTempConverted2))/(Math.log(2.71828));\n const soilTempConverted4 = 3380/((3380/298.15) - soilTempConverted3);\n const soilTemp = soilTempConverted4 - 273.15;\n return soilTemp.toFixed(2);\n}", "onInit () {\n\n this.log('device init');\n this.log('name:', this.getName());\n this.log('class:', this.getClass());\n this.polleri = 0\n\n this.pollInterval = 60000 // 1 minute\n this.polling = false\n\n this.thermostattested = false\n this.thermostatset = false // 2 possibilizties not online not set correct\n this.thermostatconnected = true \n\n\n this.ip = ''\n this.port = ''\n this.thermostatusername = ''\n this.thermostatpassword = ''\n this.thermostattesting = true\n\n this.driver = this.getDriver().id\n this.log(`driver name`, this.driver)\n\n\n\n this.thermostatmethod = 'GET'\n\n // for nt10 averagge temp is temp1 local nt10\n this.thermostatTempCommand = 'OID4.1.13'\n\n // for nt20\n this.thermostatTempOneCommand = 'OID4.3.2.1'\n this.thermostatTempTwoCommand = 'OID4.3.2.2'\n this.thermostatTempThreeCommand = 'OID4.3.2.3'\n\n this.thermostatThermSetbackHeatCommand = 'OID4.1.5'\n this.thermostatThermHvacStateCommand = 'OID4.1.2'\n\n\n\n if (this.driver == 'nt10') {\n\n this.thermostatGetCommand = `/get?${this.thermostatTempCommand}\\\n=&${this.thermostatThermSetbackHeatCommand}\\\n=&${this.thermostatThermHvacStateCommand}=` // = path in req\n // this.registerCapabilityListener('measure_temperature', this.onCapabilityMeasure_temperature.bind(this))\n\n\n }\n\n else if (this.driver == 'nt20') {\n\n this.thermostatGetCommand = `/get?${this.thermostatTempOneCommand}\\\n=&${this.thermostatTempTwoCommand}\\\n=&${this.thermostatTempThreeCommand}\\\n=&${this.thermostatThermSetbackHeatCommand}\\\n=&${this.thermostatThermHvacStateCommand}=` // = path in req\n\n this.registerCapabilityListener('measure_temperature_one', this.onCapabilityMeasure_temperature_one.bind(this))\n this.registerCapabilityListener('measure_temperature_two', this.onCapabilityMeasure_temperature_two.bind(this))\n this.registerCapabilityListener('measure_temperature_three', this.onCapabilityMeasure_temperature_three.bind(this))\n\n\n }\n\n\n // register a capability listener\n \n this.registerCapabilityListener('target_temperature', this.onCapabilityTarget_temperature.bind(this))\n this.registerCapabilityListener('thermostat_mode', this.onCapabilityThermostat_mode.bind(this))\n\n\n\n\n this.settings = this.getSettings();\n\n this.ip = this.settings.ip\n this.port = this.settings.port\n this.thermostatusername = this.settings.user\n this.thermostatpassword = this.settings.password\n\n\n // this.log(`driver `, this.inspect(this.getDriver()))\n this.log(`driver clasname `, this.getDriver().constructor.name)\n this.log(`driver name`, this.getDriver().id)\n\n\n this.log(`settings `, this.settings)\n\n\n // check if thermostat is set\n if (!(this.ip == undefined) && !(this.port == undefined) && !(this.thermostatusername == undefined) && !(this.thermostatpassword == undefined)) {\n this.thermostatset = true;\n\n this.log('test if thermostat is set this.thermostatset = ', this.thermostatset);\n this.pollproliphix();\n } else {\n this.thermostatset = false;\n this.log('test if thermostat is set this.thermostatset = ', this.thermostatset);\n }\n\n \n\n\n // test thermostat \n if (!(this.ip == null) && !(this.port == null) && !(this.thermostatusername == null) && !(this.thermostatpassword == null)) {\n this.req(this.ip, this.port, this.thermostatGetCommand, this.thermostatmethod, this.thermostatusername, this.thermostatpassword);\n this.polleri += 1\n };\n\n \n\n\n\n\n\n\n\n // this.setSettings({\n // ip: \"newValue\",\n // // only provide keys for the settings you want to change\n // })\n // .then(this.log)\n // .catch(this.error)\n\n }", "static createWindchillTemperatureGauge() {\r\n var gauge = new LinearGauge(this.createTemperatureGaugeOpts('windchillTemperatureCanvas'));\r\n LivewindStore.storeGauge('windchillTemperature', gauge);\r\n gauge.draw();\r\n }", "function sensorFunc() {\n\t// calls the success callback if the sesnor is there otherwise calls error\n\t// callback\n\ttizen.humanactivitymonitor.getHumanActivityData(\"HRM\",\n\t\t\tsuccessCallbackHeart, errorCallback); // HeartRate API\n}", "function NTSCEvent()\r\n{\r\n try\r\n {\r\n gb_use_ntsc_arduino = this.checked() ? true : false; \r\n }\r\n catch(err)\r\n { \r\n DebugLog(err.message.toString());\r\n } \r\n}", "startData() { return {\r\n unlocked: false,\r\n points: new Decimal(0),\r\n best: new Decimal(0),\r\n total: new Decimal(0),\r\n energy: new Decimal(0),\r\n first: 0,\r\n }}", "connectHardware () {\n let Gpio = require('onoff').Gpio\n this._actuator = new Gpio(this._model.values['1'].customFields.gpio, 'out')\n\n console.info('Hardware %s actuator started!', this._model.name)\n }", "function processReading(data) {\n var timenow = new Date(); // current time\n var trimmed = data.trim().replace(/>/g,''); // remove unwanted chars\n console.log(\"RH-USB: %s\", trimmed);\n var fields = trimmed.split(',');\n var temp = fields[1];\n var humid = fields[0];\n setTimeout(readRHUSB, period); // schedule next reading\n publish({ // publish sensor reading\n time: timenow.toISOString(),\n temperature: temp,\n humidity: humid\n });\n}", "function convertTemp(temperature, type) {\n if (temperature > 0){\n console.log((temperature - 32) * 5/9 + type);\n} else {\n console.log((temperature * 9/5) + 32 + type);\n}\n}", "function start_temperatures(){\n \tlog_temperatures(\"start create temperatures\");\n \t$.each(temperatures, function(i, item) {\n \t\t\tif( item.type==\"create\" ){\n \t\t\t\tlog_temperatures(\"craete \");\n \t\t\t\tif (!isset (() => item.min)) var min=-30;\n\t\t\t\telse var min=item.min;\n \t\t\t\tif (!isset (() => item.max)) var max=90;\n\t\t\t\telse var max=item.max;\n \t\t\t\tif (!isset (() => item.styleX)) var styleX=\"style1\";\n\t\t\t\telse var styleX=item.styleX;\n\t\t\t\tlog_temperatures(\"--- OK ------ \");\n\t\t\t\tlog_temperatures(\"styleX=\"+styleX);\n\t\t\t\ttemperature_create(item.id, styleX);\n \t\t\t}\n\t\t});\n }", "function initDone(connectedDevices) {\n\n if (connectedDevices.length === 0) {\n writeLog(\"Oops, didn't find any devices! Make sure they are connected and refresh this page!\");\n }\n\n // Store the devices on the global variable\n devices = connectedDevices;\n\n // Get the humidty sensor (includes temperature)\n temperatureSensor = devices.getDeviceByIdentifier(283);\n}", "constructor(project, device) {\n super(project, device);\n\n this._variableId = null;\n this._calculationInterval = null;\n this._refreshedFirstTime = null;\n this._beginIntervalTick = null;\n this._endIntervalTick = null;\n }", "function ds18b20Sensor(config) {\n\n // Create a RED node\n RED.nodes.createNode(this, config);\n\n // Store local copies of the node configuration (as defined in the .html)\n var node = this;\n\n // The root path of the sensors\n var W1PATH = \"/sys/bus/w1/devices\";\n \n // The directories location\n var W1DIRS = \"/sys/devices/\";\n\n // The devices list file\n var W1DEVICES = \"/sys/devices/w1_bus_master1/w1_master_slaves\";\n \n // Save the default device ID\n this.topic = config.topic;\n\n // If we are to return an array\n this.returnArray = false;\n\n // Load information from the devices list\n this.loadDeviceData = function() {\n var deviceList = [];\n var fsOptions = { \"encoding\":\"utf8\", \"flag\":\"r\" };\n var dirs = fs.readdirSync(W1DIRS, \"utf8\");\n for (var iY=0; iY<dirs.length; iY++) {\n if ((dirs[iY].startsWith && dirs[iY].startsWith(\"w1_bus_master\")) ||\n (dirs[iY].indexOf(\"w1_bus_master\") !== -1)) {\n var devs = fs.readFileSync(W1DIRS + dirs[iY] + \n \"/w1_master_slaves\", fsOptions).split(\"\\n\");\n for (var iX=0; iX<devs.length; iX++) {\n if (devs[iX] !== undefined && devs[iX] !== \"\"\n && devs[iX] !== \"not found.\") {\n var fName = W1PATH + \"/\" + devs[iX] + \"/w1_slave\";\n if (fs.existsSync(fName)) {\n var fData = fs.readFileSync(fName, fsOptions).trim();\n // Extract the numeric part\n var tBeg = fData.indexOf(\"t=\")+2;\n if (tBeg >= 0) {\n var tEnd = tBeg+1;\n while (tEnd<fData.length &&\n fData[tEnd]>='0' && fData[tEnd]<='9') {\n tEnd++;\n }\n var temp = fData.substring(tBeg, tEnd);\n var tmpDev = devs[iX].substr(13,2) + devs[iX].substr(11,2) +\n devs[iX].substr(9,2) + devs[iX].substr(7,2) +\n devs[iX].substr(5,2) + devs[iX].substr(3,2);\n \n deviceList.push({\n \"family\": devs[iX].substr(0,2),\n \"id\": tmpDev.toUpperCase(),\n \"dir\": dirs[iY],\n \"file\": devs[iX],\n \"temp\": temp/1000.0\n });\n }\n }\n }\n }\n }\n }\n return deviceList;\n }\n\n // Return the deviceList entry, given a device ID\n this.findDevice = function(deviceList, devId) {\n devId = devId.toUpperCase();\n for (var iX=0; iX<deviceList.length; iX++) {\n if (devId === deviceList[iX].file.substr(3).toUpperCase() ||\n devId === deviceList[iX].id) {\n return deviceList[iX];\n }\n }\n // If it's not in the normalised form\n var tmpDev = devId.substr(13,2) + devId.substr(11,2) +\n devId.substr(9,2) + devId.substr(7,2) +\n devId.substr(5,2) + devId.substr(3,2);\n for (var iX=0; iX<deviceList.length; iX++) {\n if (devId === deviceList[iX].file.substr(3).toUpperCase() ||\n devId === deviceList[iX].id) {\n return deviceList[iX];\n }\n }\n \n return null;\n }\n\n\n // Read the data & return a message object\n this.read = function(inMsg) {\n // Retrieve the full set of data\n var deviceList = this.loadDeviceData();\n\n var msgList = [];\n var msg;\n\n if (this.topic != undefined && this.topic != \"\") {\n // Split a list into devices (or 1 if only 1)\n var sList = this.topic.split(\" \");\n var retArr = [];\n for (var iX=0; iX<sList.length; iX++) {\n // Set up the returned message\n var dev = this.findDevice(deviceList, sList[iX]);\n if (this.returnArray || sList.length > 1) {\n retArr.push(dev);\n } else {\n msg = _.clone(inMsg);\n if (dev === null) { // Device not found!\n msg.family = 0;\n msg.payload = \"\";\n } else {\n msg.file = dev.file;\n msg.dir = dev.dir;\n msg.topic = dev.id;\n msg.family = dev.family;\n msg.payload = dev.temp;\n }\n msgList.push(msg);\n }\n }\n if (this.returnArray || sList.length > 1) {\n msg = _.clone(inMsg);\n msg.topic = \"\";\n msg.payload = retArr;\n msgList.push(msg);\n }\n } else { // No list of devices in the topic\n if (this.returnArray) { // Return as an array?\n msg = _.clone(inMsg);\n msg.topic = \"\";\n msg.payload = deviceList;\n msgList.push(msg);\n } else { // Not an array - a series of messages\n for (var iX=0; iX<deviceList.length; iX++) {\n msg = _.clone(inMsg);\n msg.file = deviceList[iX].file;\n msg.dir = deviceList[iX].dir;\n msg.topic = deviceList[iX].id;\n msg.family = deviceList[iX].family;\n msg.payload = deviceList[iX].temp;\n msgList.push(msg);\n }\n }\n }\n return msgList;\n };\n\n // respond to inputs....\n this.on('input', function (msg) {\n this.topic = config.topic;\n if (msg.topic !== undefined && msg.topic !== \"\") {\n this.topic = msg.topic;\n }\n this.returnArray = msg.array | config.array;\n\n var arr = this.read(msg);\n \n if (arr) {\n node.send([ arr ]);\n }\n });\n\n }", "function addTemp(object) {\nconst temp = object.main.temp;\nconst kToFTemp = (temp - 273.15) * (9/5) + 32;\nreturn `Temperature: ${Math.round(kToFTemp)}`;\n}", "function farenheitCelsius(temp) {\n return temp - 32 * 5 / 9\n }", "function getTemp(weatherData) {\n var tempKelvin = weatherData;\n // console.log(tempKelvin);\n var degFInt = Math.floor(tempKelvin);\n // console.log(degFInt);\n $temp2.html(degFInt + \"\\u00B0F\");\n}", "function toggleTemp() {\n var t1 = 0;\n var suffix = \"Z\";\n if (showTempInCflag_ == 1) {\n t1 = KtoC(tempK_);\n showTempInCflag_ = 0;\n suffix = \"C\";\n }\n else {\n t1 = KtoF(tempK_);\n showTempInCflag_ = 1;\n suffix = \"F\";\n }\n document.getElementById(\"temperature\").innerHTML = t1.toFixed(2) + suffix;\n return t1;\n}", "initChip () {\r\n this.reset();\r\n this.writeRegister(CMD.TModeReg, 0x8D); // TAuto=1; timer starts automatically at the end of the transmission in all communication modes at all speeds\r\n this.writeRegister(CMD.TPrescalerReg, 0x3E); // TPreScaler = TModeReg[3..0]:TPrescalerReg, ie 0x0A9 = 169 => f_timer=40kHz, ie a timer period of 25μs.\r\n this.writeRegister(CMD.TReloadRegL, 30); // Reload timer with 0x3E8 = 1000, ie 25ms before timeout.\r\n this.writeRegister(CMD.TReloadRegH, 0);\r\n this.writeRegister(CMD.TxAutoReg, 0x40); // Default 0x00. Force a 100 % ASK modulation independent of the ModGsPReg register setting\r\n this.writeRegister(CMD.ModeReg, 0x3D); // Default 0x3F. Set the preset value for the CRC coprocessor for the CalcCRC command to 0x6363 (ISO 14443-3 part 6.2.4)\r\n this.antennaOn(); // Enable the antenna driver pins TX1 and TX2 (they were disabled by the reset)\r\n }", "function temperature(req, res) {\n\n // Use a try/catch incase the session has expired. In that case, this code will fail.\n try {\n // Use session data to keep track of the websites that have already triggered a message to Processing\n // This control is kept due to extension signals being received at seemingly random times\n if (!(req.session.history.includes(req.body.URL))) {\n req.session.history.push(req.body.URL);\n \n /******************* TESTING CODE *******************/\n try {\n console.log(\"WEBSITE: \");\n console.log(\"\\t\" + formatColour( (\"URL: \" + req.body.URL), req.body.colour));\n } catch (err) {\n console.log(err);\n }\n /****************************************************/\n \n // Send message to Arduino\n // messageArduino(req, res);\n\n // Control temperature using Johnny-five\n johnnyFiveTemperature(req);\n \n res.end();\n\n }\n\n } catch (err) {\n console.log(\"TEMPERATURE: \" + err);\n\n // If it fails, turn off heating device\n req.body.code = 4;\n johnnyFiveTemperature(req);\n }\n \n}", "start() {\n this.currentTaskType = \"teil-mathe\";\n this.v.setup();\n this.loadTask();\n }", "static createAirTemperatureGauge() {\r\n var gauge = new LinearGauge(this.createTemperatureGaugeOpts('airTemperatureCanvas'));\r\n LivewindStore.storeGauge('airTemperature', gauge);\r\n gauge.draw();\r\n }", "function getTemp(){\n execFile('./scripts/humidity', ['temp'], (error, stdout, stderr) => {\n if (error) {\n console.error('stderr', stderr);\n throw error;\n }\n console.log(stdout);\n readData.temp = stdout\n })\n}", "function startGraphInterval(){\n\n setInterval(function(){\n getTemperature();\n }, GRAPH_TIMER);\n}", "function temperatureChanged(obj, greenLed, redLed) {\n var message = new Message(JSON.stringify({\n deviceId: creds.DeviceId, \n temperature: obj.fahrenheit,\n timestamp: new Date(),\n }));\n\n // Send the message\n client.sendEvent(message, function() {\n greenLed.on();\n setTimeout(function() {\n greenLed.off();\n },500);\n });\n\n // Edge processing to see if the temperature is higher than we want\n if (obj.fahrenheit >= alertTemp) {\n redLed.on();\n }\n}", "function accelerationDevice(){\n var acc;\n $('#ShowBeacons').empty();\n setInterval(function(){navigator.accelerometer.getCurrentAcceleration(\n function(acceleration) {\n acc +='<p>Acceleration X: ' + acceleration.x + '</p>\\n' +\n '<p>Acceleration Y: ' + acceleration.y + '</p>\\n' +\n '<p>Acceleration Z: ' + acceleration.z + '</p>\\n' +\n '<p>Timestamp: ' + acceleration.timestamp + '</p>\\n<p>------------------</p>';\n $('#ShowBeacons').append(acc);\n },\n\n function() {alert('onError!');}\n );},5000);\n }//Ende of accelerationDevice", "function thermostatPointerTempToDeg(temp){\n return (temp * 2) + 20;\n}", "function start(){\n\t starter = setInterval(randomnData, 100);\n\t\n\t\n}", "function getTemperature(tempUnits){\n $.getJSON(api, function(data){\n if (tempUnits ==\"celsius\"){\n var tempSulfix = \"C\";\n var temp = (data.current.temp_c);\n var feelslike = (data.current.feelslike_c);\n }\n else if (tempUnits == \"farenheit\"){\n var tempSulfix = \"F\";\n var temp = (data.current.temp_f);\n var feelslike = (data.current.feelslike_f);\n }\n document.getElementById(\"pTemp\").innerHTML = temp + \"&deg\" + tempSulfix;\n document.getElementById(\"pFeel\").innerHTML = feelslike + \"&deg\" + tempSulfix;\n });\n }", "function convertTemp(){\n //Calculate the temperature here\n fah = parseFloat(document.getElementById(\"f-input\").value);\n console.log(fah);\n let cel = (fah-32)*5/9;\n //Send the calculated temperature to HTML\n document.getElementById(\"c-output\").innerText = cel;\n}", "constructor(power) {\n this._waterAmount = 0;\n this._power = power; // if it will be public you need to use setter also\n console.log(`Coffee machine is created, power: ${power}`);\n }", "function touchStarted(){\n x=0;\n if (osc1control=='enabled'){osc1.start();}\n // if (osc2control=='enabled'){osc2.start();}\n //if (osc3control=='enabled'){osc3.start();}\n //if (osc4control=='enabled'){osc4.start();}\n }", "function getDataStart() {\n return getTempData()[0];\n}", "function displayTemperature(response) {\n // step 5\n let temperature = document.querySelector(\"#temperature\");\n // step 6\n temperature.innerHTML = `${Math.round(response.data.main.temp)}°C`;\n let city = document.querySelector(\"#city\");\n city.innerHTML = response.data.name;\n}", "function serialEvent() {\n inData = serial.readLine();\n let splitData = split(inData, '|');\n if (splitData.length === 7) {\n b1 = int(trim(splitData[0]));\n b2 = int(trim(splitData[1]));\n slider = int(trim(splitData[2]));\n shaked = int(trim(splitData[3]));\n light = int(trim(splitData[4]));\n sound = int(trim(splitData[5]));\n temp = int(trim(splitData[6]));\n newValue = true;\n } else {\n newValue = false;\n }\n}", "start() {\n this._symbolTable = new SymbolTable();\n this._maxTemp = 0;\n }", "function outputDeviceSummary(){\n console.log(\"============================\");\n console.log(\"Power: \" + pCurrent);\n console.log(\"Mode: \" + mCurrent);\n console.log(\"============================\");\n}", "function current() {\n\n $.ajax({\n url: \"https://dataservice.accuweather.com/currentconditions/v1/\" + locationKey + \"?apikey=cEXLg1f8FSe8se6GUurGnlmIVmuXmaWy&details=true\",\n method: \"GET\"\n }).done(function(results) {\n\n currentTemp = results[0].ApparentTemperature.Imperial.Value;\n // console.log(currentTemp);\n // dtag = $(\"<div>\");\n // $(\"#currentTemp\").html(\"The current temperature is \" + currentTemp + \" degrees F\");\n // $(\"h5\").before(dtag);\n\n });\n\n\n\n} // end of current", "function setHardTempo() {\n blinkGapDuration = 1000;\n if (currentRound < 6) {\n blinkDuration = 600;\n } else if (currentRound >= 6 && currentRound < 11) {\n blinkDuration = 500;\n } else {\n blinkDuration = 400;\n }\n}", "function onConnect() {\n // Once a connection has been made, make a subscription and send a message.\n console.log(\"onConnect\");\n client.subscribe(\"iot/raspberry/temperature\");\n\n }", "function getDHT22(){\n\treturn JSON.stringify({\n\t\ttemperature: Math.floor(Math.random() * 33) + 22,\n\t\thumidity: Math.floor(Math.random() * 75) + 10\n\t});\t\n}", "function setTimer() {\n // get the shortRest\n // get the largeRest\n }" ]
[ "0.71547145", "0.7054884", "0.677058", "0.6705686", "0.6502982", "0.6482067", "0.64513284", "0.64264846", "0.64019406", "0.6393715", "0.63694876", "0.61801463", "0.61778504", "0.6173274", "0.61507916", "0.6123816", "0.61215544", "0.6097975", "0.6069061", "0.6034358", "0.59775376", "0.5971159", "0.59522134", "0.59506404", "0.5908811", "0.58859485", "0.58817947", "0.58702815", "0.5861691", "0.5856252", "0.5850986", "0.5846585", "0.5846482", "0.5841832", "0.5834734", "0.58274883", "0.58207786", "0.581892", "0.57995933", "0.57961315", "0.5781225", "0.5772407", "0.57713056", "0.57204616", "0.5719092", "0.5704933", "0.5704645", "0.570163", "0.5682688", "0.56578064", "0.56559426", "0.56446475", "0.5620414", "0.56088316", "0.55687577", "0.55451196", "0.5544976", "0.5541396", "0.5540222", "0.55359197", "0.55333126", "0.5518704", "0.55093694", "0.5497451", "0.5494612", "0.54944766", "0.5489405", "0.5485526", "0.54764074", "0.5474291", "0.5473432", "0.5464456", "0.5463935", "0.54627556", "0.5460246", "0.54489887", "0.5447542", "0.54441875", "0.5442221", "0.5440031", "0.54229474", "0.5419512", "0.541726", "0.5415853", "0.541448", "0.5407477", "0.54019624", "0.539729", "0.5395961", "0.539443", "0.5387262", "0.5384887", "0.53842324", "0.5372044", "0.5358711", "0.5358103", "0.53553075", "0.53514373", "0.53469545", "0.5346018" ]
0.55299413
61
Database URL. Change this to restaurants.json file location on your server.
static get DATABASE_URL() { const port = 8000 // Change this to your server port return `http://localhost:${port}/data/restaurants.json`; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "static get DATABASE_URL() {\r\n\t\tconst port = 8000; // Change this to your server port\r\n\t\treturn `http://localhost:${port}/data/restaurants.json`;\r\n\t}", "static get DATABASE_URL () {\r\n const port = 1337 // Change this to your server port\r\n return `http://localhost:${port}/data/restaurants.json`\r\n }", "static get DATABASE_URL() {\n const protocol = location.protocol;\n const host = location.host;\n return `${protocol}//${host}/data/restaurants.json`;\n }", "static get DATABASE_URL() {\n const port = 8000; // Change this to your server port\n return `http://localhost:${port}/data/restaurants.json`;\n }", "static get DATABASE_URL() {\r\n const port = 8081 // Change this to your server port\r\n // return `http://localhost:${port}/data/restaurants.json`;\r\n return `http://localhost:1337/restaurants`;\r\n }", "static get DATABASE_URL() {\r\n const port = 1337 // Change this to your server port\r\n //return `http://localhost:${port}/data/restaurants.json`;\r\n return `http://localhost:${port}`;\r\n }", "static get DATABASE_URL() {\n // const port = 8000 // Change this to your server port\n const port = 1337 // Change this to your server port\n const path = `http://localhost:${port}/`;\n \n // return `${path}data/restaurants.json`;\n return `${path}`;\n }", "static get DATABASE_URL() {\r\n // const port = 8000 // Change this to your server port\r\n // return `http://localhost:${port}/data/restaurants.json`;\r\n return `http://localhost:${DBHelper.port}/restaurants`;\r\n }", "static get DATABASE_URL() {\r\n const port = 1337; // Change this to your server port\r\n const url = window.location.href;\r\n if(url.startsWith('https')) {\r\n return `https://amroaly.github.io/mws-restaurant-stage-1/data/restaurants.json`;\r\n } \r\n // for dev it shoud be http://localhost:${port}\r\n // instead of https://amroaly.github.io/mws-restaurant-stage-1/\r\n return `http://localhost:${port}/restaurants`;\r\n }", "static get DATABASE_URL() {\n\t\tconst port = 1337; // Change this to your server port\n\t\treturn `http://localhost:${port}/restaurants/`;\n\t}", "static get DATABASE_URL() {\r\n const port = 1337; // Change this to your server port\r\n return `http://localhost:${port}/restaurants`;\r\n }", "static get DATABASE_URL() {\r\n const port = 1337 // Change this to your server port\r\n return `http://localhost:${port}/restaurants`;\r\n }", "static get DATABASE_URL() {\r\n const port = 1337 // Change this to your server port\r\n return `http://localhost:${port}/restaurants`;\r\n }", "static get DATABASE_URL() {\r\n const port = 1337 // Change this to your server port\r\n return `http://localhost:${port}/restaurants`;\r\n }", "static get DATABASE_URL() {\r\n const port = 1337 // Change this to your server port\r\n return `http://localhost:${port}/restaurants`;\r\n }", "static get DATABASE_URL() {\r\n const port = 1337 // Change this to your server port\r\n return `http://localhost:${port}/restaurants`;\r\n }", "static get DATABASE_URL() {\n //const port = 8080 // Change this to your server port\n const url = `http://localhost:${PORT}/restaurants`;\n\n return url;\n }", "static get DATABASE_URL() {\n const port = 1337 // Change this to your server port\n return `http://localhost:${port}/restaurants`;\n }", "static get DATABASE_URL() {\n const port = 1337 // Change this to your server port\n return `http://localhost:${port}/restaurants`;\n }", "static get DATABASE_URL() {\r\n const port = 1337; // Change this to your server port\r\n return `http://localhost:${port}/restaurants`;\r\n }", "get DATABASE_URL() {\r\n const domain = `https://mws-pwa.appspot.com`;\r\n // const domain = 'http://localhost:'\r\n const port = 1337; // Change this to your server port\r\n // const origin = `${domain}${port}`;\r\n const origin = `${domain}`\r\n return {\r\n restaurants: `${origin}/restaurants/`, // GET: All restaurants, or 1 with ID\r\n restaurantsFavorites: `${origin}/restaurants/?is_favorite=true`, // GET: All favorited restaurants\r\n restaurantReviews: `${origin}/reviews/?restaurant_id=`, // GET: All reviews by restaurant ID\r\n reviews: `${origin}/reviews/`, // GET: All reviews, or 1 with ID\r\n faveRestaurant: id => `${origin}/restaurants/${id}/?is_favorite=true`, // PUT: Favorite a restaurant by ID\r\n unfaveRestaurant: id => `${origin}/restaurants/${id}/?is_favorite=false`, // PUT: Unfavorite a restaurant by ID\r\n editReview: id => `${origin}/reviews/${id}` // PUT = update, DELETE = delete review\r\n };\r\n }", "static get DATABASE_URL() {\n const url = \"http://localhost\";\n const port = 1337;\n const param = \"restaurants\";\n\n return url + \":\" + port + \"/\" + param;\n }", "static get DATABASE_URL() {\r\n const port = 1337;\r\n return `http://localhost:${port}/restaurants`;\r\n }", "static get RESTAURANTS_DATABASE_URL() {\r\n return 'https://timothynelson.me/restaurant-reviews-api/restaurants';\r\n }", "static get DATABASE_URL() {\n return `./data/quotes.json`;\n }", "static get DATABASE_URL_REVIEWS() {\n const port = 1337 // Change this to your server port\n return `http://localhost:${port}/reviews`;\n }", "static get DATABASE_URL() {\n\t\tconst port = 1337; // Change this to your server port\n\t\treturn `http://localhost:${port}/`;\n\t}", "static get DATABASE_URL() {\r\n\t\tconst port = 1337; // Change this to your server port\r\n\t\treturn `http://localhost:${port}`;\r\n\t}", "static get DATABASE_URL() {\n\t\tconst port = 1337; // Change this to your server port\n\t\treturn `http://localhost:${port}`;\n\t}", "static get DATABASE_URL () {\r\n const port = 1337; // Change this to your server port\r\n return `http://localhost:${port}/api`;\r\n }", "static get DATABASE_URL() {\r\n const port = 1337 // Change this to your server port\r\n return `http://localhost:${port}`;\r\n }", "static get DATABASE_URL() {\r\n const port = 1337 // Change this to your server port\r\n return `http://localhost:${port}`;\r\n }", "static get DATABASE_URL() {\r\n const port = 1337 // Change this to your server port\r\n return `http://localhost:${port}`;\r\n }", "static get DATABASE_URL() {\n const port = 1337 // Change this to your server port\n return `http://localhost:${port}/`;\n }", "static get DATABASE_URL() {\n const port = 1337 // Change this to your server port\n return `http://localhost:${port}`;\n }", "static get DATABASE_URL() {\r\n const port = 1337;\r\n return 'http://locahost:${port}';\r\n }", "static get DATABASE_URL() {\n const port = 1337;\n return `http://localhost:${port}`;\n }", "static get DATABASE_URL() {\r\n const baseUrl='http://localhost:1337/';\r\n return baseUrl;\r\n }", "function getRestDataLoc(rid) {\n return \"restaurants/\" + rid + \"/\";\n}", "static fetchRestaurants() {\r\n return fetch(DBHelper.DATABASE_URL)\r\n .then( response => {\r\n if (response.ok){\r\n return response.json();\r\n }\r\n }).catch(function(err){\r\n console.log('Fetch error', err);\r\n });\r\n }", "function getDatabaseUri() {\n return (process.env.NODE_ENV === \"test\")\n ? \"ratorly_test\"\n : process.env.DATABASE_URL || \"ratorly\";\n}", "readFromDB() {\n return readFile(\"db/db.json\", \"utf8\");\n }", "function getDatabase() {\r\n const json = fs.readFileSync(path.join(__dirname, \"../../db/db.json\"));\r\n return JSON.parse(json);\r\n}", "static get fetchRestaurants() {\n return Settings.server + '/api/store';\n }", "function queryDb(restaurant_id) {\n}", "function getRestDataLoc(rid) {\n return \"restaurants/\" + rid;\n}", "function getDatabaseUri() {\n return process.env.NODE_ENV === \"test\" ? \"airbnb_test\" : process.env.DATABASE_URL || \"airbnb\"\n}", "static fetchRestaurants(callback) {\n let xhr = new XMLHttpRequest();\n xhr.open('GET', DBHelper.DATABASE_URL);\n xhr.onload = () => {\n if (xhr.status === 200) { // Got a success response from server!\n const json = JSON.parse(xhr.responseText);\n const restaurants = json.restaurants;\n callback(null, restaurants);\n } else { // Oops!. Got an error from server.\n const error = (`Request failed. Returned status of ${xhr.status}`);\n callback(error, null);\n }\n };\n xhr.send();\n }", "function readJSONFile() {\n return JSON.parse(fs.readFileSync(\"db.json\"))[\"places\"];\n}", "static saveToDB(restaurants){\r\n const dbPromise = DBHelper.openDB();\r\n dbPromise.then(db => {\r\n if(!db) return ;\r\n const transaction = db.transaction(\"restaurantList\", \"readwrite\");\r\n const store = transaction.objectStore(\"restaurantList\");\r\n restaurants.forEach(restaurant => {\r\n store.put(restaurant);\r\n });\r\n return transaction.complete;\r\n });\r\n }", "static getRestaurantURL(restaurant) {\n return `restaurant.html?id=${restaurant.id}`\n }", "function populateDb() {\n fs.writeFile(\"db/db.json\", JSON.stringify(notes, \"\\t\"), (err) => {\n if (err) throw err;\n });\n }", "function getDatabaseUri() {\n return process.env.NODE_ENV === \"test\"\n ? \"norieto_test\"\n : process.env.DATABASE_URL || \"norieto\";\n}", "function getDatabaseUri() {\n const dbUser = process.env.DATABASE_USER || \"postgres\"\n //Use turner. If password exists in process, encode it. Else, use postgres.\n const dbPass = process.env.DATABASE_PASS ? encodeURI(process.env.DATABASE_PASS) : \"postgres\"\n const dbHost = process.env.DATABASE_HOST || \"postgres\"\n const dbPort = process.env.DATABASE_PORT || 5432\n const dbName = process.env.DATABASE_NAME || \"postgres\"\n\n //If DATABASE_URI env provided, use that.\n //Else, create the db connection tring outselves.\n return process.env.DATABASE_URL || `postgresql://${dbUser}:${dbPass}@${dbHost}:${dbPort}/${dbName}`\n\n}", "static urlForRestaurant(restaurant) {\n return (`./restaurant.html?id=${restaurant.id}`);\n }", "static urlForRestaurant(restaurant) {\r\n return (`./restaurant.html?id=${restaurant.id}`);\r\n }", "function getData2() {\n let url = \"geocode_data_animal.json\";\n }", "function refreshDB() {\n fs.writeFile(\"./db/db.json\", JSON.stringify(notesData), function (err) {\n if (err) throw err;\n return true;\n });\n}", "function getIdeasFromDB(res, body) {\r\n fs.readFile(path.join(rootPath, 'database', body.user + '.json'), function (err, data) {\r\n if (err) {\r\n console.error(err);\r\n res.writeHead(404, { 'Content-Type': 'text/html' });\r\n } else {\r\n res.writeHead(200, { 'Content-Type': 'text/html' });\r\n res.write(data);\r\n }\r\n res.end();\r\n });\r\n}", "static fetchRestaurants(callback) {\n const dataType = 'restaurants';\n\n // try to get data from network\n DBHelper.fetchDataFromServer((err, data) => {\n // on err, try to get the same data from indexDb\n if (err) {\n /* idbKeyval.get(DBHelper.DB_APP_NAME + dataType)\n .then(dbRes => {\n if(dbRes) {\n callback(null, dbRes);\n } \n })\n .catch(dbErr => {\n console.log('[dbhelper.js] err fetching from db', dbErr, err);\n callback(err, null);\n }) */\n DBHelper.getDataFromDB(dataType, err, callback)\n } else {\n // save in index db\n DBHelper.saveDataInDB(dataType, data);\n callback(null, data);\n }\n }, dataType);\n }", "static get DB_APP_NAME() {\n return 'restaurants-app-data-';\n }", "constructor() {\n // Must call superconstructor first.\n super();\n\n this.activePage = 'guide-book';\n this.guidebook = {\n title: '',\n description: '',\n destinations: [\n {\n url: '',\n description: '',\n },\n ],\n };\n\n // Replace ./data.json with your JSON feed\n fetch('../firebase-config.json')\n .then((response) => {\n return response.json();\n })\n .then((config) => {\n // Work with JSON data here\n console.log(JSON.stringify(config));\n this.databaseAdapter = new FirebaseAdapter(config);\n installRouter((location) => this.navigate(location));\n })\n .catch((err) => {\n // Do something for an error here\n this.databaseAdapter = new IndexedDBAdapter();\n installRouter((location) => this.navigate(location));\n });\n }", "static dbPromise() {\n return idb.open('db', 2, function(upgradeDB) {\n switch(upgradeDB.oldVersion) {\n case 0:\n upgradeDB.createObjectStore('restaurants', {\n keyPath: 'id'\n });\n case 1:\n const reviewsStore = upgradeDB.createObjectStore('reviews', {\n keyPath: 'id'\n });\n // create an index for the reviews relative to restaurant ID\n reviewsStore.createIndex('restaurant', 'restaurant_id');\n }\n })\n }", "static dbPromise() {\n return idb.open('db', 2, function(upgradeDB) {\n switch(upgradeDB.oldVersion) {\n case 0:\n upgradeDB.createObjectStore('restaurants', {\n keyPath: 'id'\n });\n case 1:\n const reviewsStore = upgradeDB.createObjectStore('reviews', {\n keyPath: 'id'\n });\n // create an index for the reviews relative to restaurant ID\n reviewsStore.createIndex('restaurant', 'restaurant_id');\n }\n })\n }", "guardarDB() {\n fs.writeFileSync(this.dbPath, JSON.stringify(this.historial));\n }", "static fetchRestaurants(callback) {\r\n idbPromise.then(db => {\r\n const tx = db.transaction('restaurant-store', 'readwrite');\r\n tx.objectStore('restaurant-store').getAll().then(restaurantsFromDb => {\r\n if (restaurantsFromDb.length > 0) {\r\n return callback(null, restaurantsFromDb);\r\n }\r\n else {\r\n fetch(DBHelper.DATABASE_URL)\r\n .then((res) => {\r\n res.json()\r\n .then((restaurants) => {\r\n // Save JSON into indexedDB\r\n idbPromise.then(db => {\r\n const tx = db.transaction('restaurant-store', 'readwrite');\r\n // Loop through the restaurant list and store in the db\r\n restaurants.forEach((restaurant) => {\r\n tx.objectStore('restaurant-store').put(restaurant);\r\n });\r\n return tx.complete;\r\n });\r\n return callback(null, restaurants);\r\n })\r\n .catch((err) => {\r\n return Promise.reject(Error(err));\r\n });\r\n })\r\n }\r\n });\r\n });\r\n }", "function readJSONFile() {\r\n return JSON.parse(fs.readFileSync(\"db.json\"))[\"ideas\"];\r\n}", "function read() {\n\tvar data = JSON.parse(fs.readFileSync('db/db.json', 'utf-8'));\n\treturn data;\n}", "async loadDatabase() {\n this.__db =\n (await qx.tool.utils.Json.loadJsonAsync(this.__dbFilename)) || {};\n }", "static get FILE_URL() {\n const port = 8000;\n return `http://localhost:${port}/data/vgsales55c93b8.csv`;\n }", "static fetchRestaurantById (id) {\r\n return fetch(`${DBHelper.DATABASE_URL}/restaurants/${id}`).then(res => {\r\n return res.json().then(json => {\r\n return idb.cacheItem('restaurants', json.restaurant).then(() => json.restaurant);\r\n });\r\n });\r\n }", "constructor() {\n let dataFile = `${__dirname}/db.json`;\n super(dataFile);\n }", "static getRestaurants() {\r\n return new Promise((resolve,reject) => {\r\n\r\n DBHelper.openDatabase().then(db => {\r\n let tx = db.transaction('restaurants');\r\n let store = tx.objectStore('restaurants');\r\n store.getAll().then(restaurants => {\r\n if (restaurants && restaurants.length > 0) {\r\n resolve(restaurants);\r\n } else {\r\n DBHelper.updateRestaurants().then(listFromWeb => {\r\n resolve(listFromWeb);\r\n }).catch(reject);\r\n }\r\n });\r\n }).catch(reject);\r\n });\r\n }", "printDatabaseLocation() {\n console.log(FileSystem.documentDirectory + \"SQLite/\" + DATABASE_NAME);\n }", "function databaseFileName() {\n let dates = new Date();\n let month = dates.getMonth() + 1;\n let dateForFileName = dates.getDate() + '-' + month + '-' +\n dates.getFullYear();\n let timeForFileName = dates.getHours() + '-' + dates.getMinutes();\n\n return '/database_date' + dateForFileName + '_time' + timeForFileName + '.json';\n}", "read() {\n return readFileAsync(\"db/db.json\", \"utf8\"); // shows the notes from the database json file (db.json)\n }", "saveDB() {\n const dbpath = path.join(__dirname, \"../db/data.json\");\n fs.writeFileSync(dbpath, JSON.stringify(this.toJson));\n }", "getDataBaseConfig(){\n\t\treturn JSON.parse(fs.readFileSync(\"./config.json\"))[\"database\"];\n\t}", "static storeRestaurant(idbPromise, restaurant) {\n idbPromise.then(db => {\n if (!db) return;\n \n db.transaction('restaurant', 'readwrite')\n .objectStore('restaurant')\n .put(restaurant);\n });\n }", "constructor() {\n this.#database = new Datastore({\n filename: \"./server/database/rooms.db\",\n autoload: true,\n });\n }", "static cacheDataFromDb(){\r\n const dbPromise = DBHelper.openDB();\r\n const restaurants = dbPromise.then(function (db) {\r\n const transaction = db.transaction(\"restaurantList\", \"readonly\");\r\n const store = transaction.objectStore(\"restaurantList\");\r\n return store.getAll();\r\n });\r\n return restaurants;\r\n }", "leerDB() {\n //Verificar si existe el archivo, si no existe, el array de historial queda como se declaro (vacio).\n if (fs.existsSync(this.dbPath)) {\n const info = fs.readFileSync(this.dbPath, { encoding: 'utf-8' });\n const data = JSON.parse(info);\n this.historial = data;\n }\n }", "static createNewDatabase() {\n idb.open(restaurantsDb, 1, upgradeDb => {\n if (!upgradeDb.objectStoreNames.contains(restaurantsTx)) {\n upgradeDb.createObjectStore(restaurantsTx, { keypath: 'id', autoIncrement: true });\n }\n console.log('restaurants-db has been created!');\n });\n }", "function loadDatabase (location) {\n //neste caso, o arquivo é estático e pode ser lido usando o require\n return require(location);\n}", "function seedRestaurantData() {\n const date = faker.date.recent();\n return Restaurant.create({\n name: faker.company.companyName(),\n borough: 'Queens',\n cuisine: 'Mexican',\n addressBuildingNumber: faker.address.streetAddress(),\n addressStreet: faker.address.streetName(),\n addressZipcode: faker.address.zipCode(),\n createdAt: date,\n updatedAt: date});\n}", "static fetchRestaurantById(id) {\r\n // fetch all restaurants with proper error handling.\r\n return fetch(DBHelper.DATABASE_URL_ID(id))\r\n .then( response => {\r\n if (response.ok){\r\n return response.json();\r\n }\r\n }).catch(function(err){\r\n console.log('Fetch error', err);\r\n });\r\n }", "async function readFromDB() {\n return await JSON.parse(fs.readFileSync(path.join(__dirname, '../../db/db.json')));\n}", "guardarDB (){\n const payload ={\n historial: this.historial\n };\n\n fs.writeFileSync(this.dbPath, JSON.stringify(payload));\n\n }", "function loadSharkDB() {\n\n let db = new SharkDB([])\n db['branches'] = BRANCHES\n db['evns'] = EVNS\n db['machines'] = MACHINES\n db['codes'] = PRODUCT_CODES\n\n try {\n var data = fs.readFileSync(`${SHARK_DB}`, 'UTF-8');\n return data ? JSON.parse(data.toString()) : db\n } catch (err) {\n console.error(err)\n return db\n }\n}", "async function Test()\n{\n load_InitiativeDB('./public/json/initiative_DB_46093_Latest.json').then((result) => {\n console.log(\"[TEST] Read Initiative DB = \", JSON.stringify(initiative_DB));\n make_URLinfo();\n });\n\n\n console.log(\"[final-make_URLinfo] Save file = initiative_DB_URL\");\n Save_JSON_file(initiative_DB, \"./public/json/initiative_DB_URL_Latest.json\");\n console.log(\"[final-make_URLinfo] Save end : initiative_DB_URL\");\n}", "static saveRestaurantsIntoIDB(restaurants) {\r\n // const dbPromise = DBHelper.openIDB();\r\n return DBHelper.openIDB().then((db) => {\r\n if(!db) return;\r\n const tx = db.transaction('restaurants', 'readwrite')\r\n const store = tx.objectStore('restaurants');\r\n restaurants.forEach((restaurant) => {\r\n store.put(restaurant);\r\n });\r\n return tx.complete;\r\n });\r\n }", "storeData(jsonData) {\n fs.writeFileSync(dbPath, JSON.stringify(jsonData));\n }", "static openDatabase() {\r\n if(!navigator.serviceWorker){\r\n return Promise.resolve();\r\n }\r\n return idb.open('db', 2, function (upgradeDb) {\r\n switch (upgradeDb.oldVersion) {\r\n case 0:\r\n upgradeDb.createObjectStore('restaurants', {\r\n keyPath: 'id'\r\n });\r\n case 1:\r\n const reviewsStore = upgradeDb.createObjectStore('reviews', {\r\n keyPath: 'id'\r\n });\r\n reviewsStore.createIndex('restaurant', 'restaurant_id');\r\n }\r\n });\r\n }", "static fetchRestaurants(callback) {\r\n DBHelper.fetchRestaurantsFromIDB((error, restaurants) => {\r\n // if there is no data in the indexedDB\r\n // Here's what we will do\r\n // fetch the restaurants from the network\r\n // save it to the indexedDB \r\n if(error) {\r\n DBHelper.fetchRestaurantsFromNetwork((error, restaurants) => {\r\n if(restaurants) {\r\n // save the restaurants into the IDB\r\n DBHelper.saveRestaurantsIntoIDB(restaurants);\r\n \r\n callback(null, restaurants);\r\n }\r\n if(error) {\r\n callback(error, null);\r\n }\r\n });\r\n }\r\n\r\n // restaurants found in IDB\r\n if(restaurants) {\r\n callback(null, restaurants);\r\n }\r\n });\r\n }", "readfnc() {\n return read('./Develop/db/db.json', 'utf8');\n }", "readFile() {\n return fileRead('db/db.json', 'utf8');\n }", "fetchRestaurantById(id) {\n return idbKeyval.get(RESTAURANTS_STORE,Number(id)).then(restaurant => {\n if(!restaurant){\n let DBurl = this.dataBaseUrls().byId(id);\n return fetch(DBurl).then(response => response.json());\n }\n return restaurant;\n });\n }", "static storeRestaurants(idbPromise, restaurants) {\n idbPromise.then(db => {\n if (!db) return;\n \n let store = db.transaction('restaurant', 'readwrite')\n .objectStore('restaurant');\n restaurants.forEach(restaurant => {\n store.put(restaurant);\n });\n });\n }", "function readDB() {\n const data = localStorage.getItem(KEY_BD);\n if (data) {\n registerList = JSON.parse(data);\n }\n renderTable();\n}", "populateOfflineDatabase(){\r\n return fetch(`${DBHelper.DATABASE_URL}/restaurants`)\r\n .then((response)=>{ return response.json(); })\r\n .then((restaurants)=>{ return Promise.all(restaurants.map((response)=>{this.addRecord(DBHelper.RESTAURANT_STORE_NAME, response)}, this)) })\r\n .then(()=>{ console.log(`Database filled`) })\r\n .catch((err)=>{\r\n console.log(`Database not updated with fresh network data: ${err}`)\r\n })\r\n }" ]
[ "0.84931445", "0.8413371", "0.84057564", "0.84032124", "0.8136033", "0.8113079", "0.8041698", "0.7935423", "0.7849609", "0.7781188", "0.76253206", "0.7554343", "0.7554343", "0.7554343", "0.7554343", "0.7554343", "0.75531036", "0.75486785", "0.75486785", "0.7546189", "0.75300664", "0.75174314", "0.7421447", "0.74079674", "0.73250526", "0.7029113", "0.6639576", "0.66327953", "0.6592026", "0.650551", "0.65022725", "0.65022725", "0.65022725", "0.6471304", "0.6453125", "0.63624007", "0.62354785", "0.6139217", "0.60914594", "0.608128", "0.6014221", "0.60094374", "0.59707904", "0.59561884", "0.5931082", "0.5891195", "0.5854985", "0.5838258", "0.568522", "0.5662079", "0.5658386", "0.5654957", "0.56229585", "0.5614553", "0.5562439", "0.55581814", "0.55419457", "0.5521281", "0.5517902", "0.5507482", "0.55021584", "0.5495623", "0.5463107", "0.5463107", "0.5445301", "0.54439247", "0.54433775", "0.54290265", "0.54147965", "0.5413373", "0.5383101", "0.5370463", "0.53695583", "0.53643423", "0.5361283", "0.5348724", "0.5348678", "0.5341765", "0.5336107", "0.5331671", "0.5325278", "0.5322484", "0.5313332", "0.5309052", "0.52990574", "0.52870476", "0.5253951", "0.5241785", "0.5227768", "0.52174", "0.5216793", "0.52146435", "0.52023107", "0.5198077", "0.51845294", "0.51792234", "0.5175457", "0.51612544", "0.51325417", "0.5129506" ]
0.8273619
4
Fetch a restaurant by its ID.
static fetchRestaurantById(id, callback) { // fetch all restaurants with proper error handling. DBHelper.fetchRestaurants((error, restaurants) => { if (error) { callback(error, null); } else { const restaurant = restaurants.find(r => r.id == id); if (restaurant) { // Got the restaurant callback(null, restaurant); } else { // Restaurant does not exist in the database callback('Restaurant does not exist', null); } } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "static fetchRestaurantById(id) {\r\n // fetch all restaurants with proper error handling.\r\n return fetch(DBHelper.DATABASE_URL_ID(id))\r\n .then( response => {\r\n if (response.ok){\r\n return response.json();\r\n }\r\n }).catch(function(err){\r\n console.log('Fetch error', err);\r\n });\r\n }", "fetchRestaurantById(id) {\n return this._updateFromService()\n .then(() => this.db)\n .then(db => {\n const store = this._getStore(db, 'restaurants', false);\n const request = store.get(id);\n return new Promise((resolve, reject) => {\n request.onsuccess = () => { resolve(request.result); };\n request.onerror = reject;\n });\n });\n }", "static getRestaurantById(id) {\n const init = DBHelper.fetchInit('GET');\n const url = `${DBHelper.API_URL}/restaurants/${id}`;\n return DBHelper.makeCall(url, init);\n }", "static fetchRestaurantById (id) {\r\n return fetch(`${DBHelper.DATABASE_URL}/restaurants/${id}`).then(res => {\r\n return res.json().then(json => {\r\n return idb.cacheItem('restaurants', json.restaurant).then(() => json.restaurant);\r\n });\r\n });\r\n }", "static fetchRestaurantById (id) {\r\n return IDB.getRestaurantById(id)\r\n .then(restaurant => {\r\n if (!restaurant) {\r\n return fetch(`http://localhost:1337/restaurants/${id}`)\r\n .then(response => response.json())\r\n .catch(e => console.log('error: ', e))\r\n }\r\n return restaurant\r\n })\r\n }", "static fetchRestaurantById(id) {\r\n // fetch all restaurants with proper error handling.\r\n return new Promise((resolve, reject) => {\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n reject(error);\r\n } else {\r\n const restaurant = restaurants.find(r => r.id == id);\r\n if (restaurant) { // Got the restaurant\r\n resolve(restaurant);\r\n } else { // Restaurant does not exist in the database\r\n reject('Restaurant does not exist', null);\r\n }\r\n }\r\n });\r\n });\r\n }", "fetchRestaurantById(id) {\n return idbKeyval.get(RESTAURANTS_STORE,Number(id)).then(restaurant => {\n if(!restaurant){\n let DBurl = this.dataBaseUrls().byId(id);\n return fetch(DBurl).then(response => response.json());\n }\n return restaurant;\n });\n }", "static fetchRestaurantById(id, callback) {\n\t\t// fetch all restaurants with proper error handling.\n\t\tconst dbPromise = this.OpenDbPromise();\n\t\tdbPromise.then(function(db) {\n\t\t\tif (!db) {\n\t\t\t\tDBHelper.fetchRestaurantByIdFromServer(id, callback);\n\t\t\t}\n\t\t\tconst index = db.transaction('restaurants').objectStore('restaurants');\n\t\t\treturn index.get(id).then(restaurant => {\n\t\t\t\tif (restaurant) {\n\t\t\t\t\tDBHelper.fetchReviewsByRestaurantId(restaurant, callback);\n\t\t\t\t}\n\t\t\t\tDBHelper.fetchRestaurantByIdFromServer(id, callback);\n\t\t\t});\n\t\t});\t\t\n\t}", "static fetchRestaurantById(id, callback) {\n // fetch all restaurants with proper error handling.\n return fetch(\n `${DBHelper.DATABASE_URL}/${id}`, {\n method: 'GET'\n }\n ).then(response => response.json()).then(restaurant => {\n\n if (restaurant) { // Got the restaurant\n callback(null, restaurant);\n } else { // Restaurant does not exist in the database\n callback('Restaurant does not exist', null);\n }\n }).catch(error => {\n callback(error, null);\n });\n }", "static fetchRestaurantById(id, cb) {\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n cb(error, null);\n } else {\n const restaurant = restaurants.find(r => r.id == id);\n if (restaurant) {\n cb(null, restaurant);\n } else {\n cb('Restaurant does not exist', null);\n }\n }\n });\n }", "static fetchRestaurantById(restaurantIDB, id, dbCallback, networkCallback) {\r\n DBHelper._retrieveData(\r\n DBHelper._dataRetrievalUseCase.GET_ON_INDEX,\r\n networkCallback, \r\n dbCallback, \r\n `${DBHelper.RESTAURANTS_DATABASE_URL}/${id}`, \r\n restaurantIDB, \r\n 'id', \r\n 'id', \r\n id);\r\n }", "static fetchRestaurantById(id, callback) {\r\n DBHelper.selectRestaurantFromIDB(id)\r\n .then(function (jsonRestaurant) {\r\n if (jsonRestaurant != null) {\r\n return jsonRestaurant;\r\n }\r\n\r\n return DBHelper.fetchRestaurantFromServer(id);\r\n })\r\n .then(function (jsonRestaurant) {\r\n DBHelper.insertRestaurantToIDB(id, jsonRestaurant);\r\n callback(null, jsonRestaurant);\r\n })\r\n .catch(function (error) {\r\n const errorMsg = (`Request failed. Error message: ${error.message}`);\r\n callback(errorMsg, null);\r\n });\r\n }", "static fetchRestaurantById(id) {\n const data = {\n restaurant: null,\n reviews: null,\n };\n return new Promise((resolve, reject) => {\n // fetch all restaurants with proper error handling.\n DBHelper.getRestaurantById(id).then(restaurant => {\n if (restaurant) { // Got the restaurant\n data.restaurant = restaurant;\n return DBHelper.getReviewsForRestaurant(id);\n } else { // Restaurant does not exist in the database\n reject('Restaurant does not exist');\n }\n }).then(reviews => {\n if (reviews) {\n data.reviews = reviews;\n }\n resolve(data);\n }).catch(error => {\n reject(error);\n });\n });\n }", "static fetchRestaurantById(id, callback) {\r\n // fetch all restaurants with proper error handling.\r\n DBHelper.openDatabase()\r\n .then(db => {\r\n let tx = db.transaction('restaurants');\r\n let store = tx.objectStore('restaurants');\r\n store.get(parseInt(id))\r\n .then(result => {\r\n callback(null,result);\r\n }).catch((e) => {\r\n callback(e,null)\r\n });\r\n });\r\n }", "static fetchRestaurantById(id, callback) {\n // fetch all restaurants with proper error handling.\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n const restaurant = restaurants.find(r => r.id == id);\n if (restaurant) { // Got the restaurant\n callback(null, restaurant);\n } else { // Restaurant does not exist in the database\n callback('Restaurant does not exist', null);\n }\n }\n });\n }", "static fetchRestaurantById(id, callback) {\n // fetch all restaurants with proper error handling.\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n const restaurant = restaurants.find(r => r.id == id);\n if (restaurant) { // Got the restaurant\n callback(null, restaurant);\n } else { // Restaurant does not exist in the database\n callback('Restaurant does not exist', null);\n }\n }\n });\n }", "static fetchRestaurantById(id, callback) {\n // fetch all restaurants with proper error handling.\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n const restaurant = restaurants.find(r => r.id == id);\n if (restaurant) { // Got the restaurant\n callback(null, restaurant);\n } else { // Restaurant does not exist in the database\n callback('Restaurant does not exist', null);\n }\n }\n });\n }", "static fetchRestaurantById(id, callback) {\n // fetch all restaurants with proper error handling.\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n const restaurant = restaurants.find(r => r.id == id);\n if (restaurant) { // Got the restaurant\n callback(null, restaurant);\n } else { // Restaurant does not exist in the database\n callback('Restaurant does not exist', null);\n }\n }\n });\n }", "static fetchRestaurantById(id, callback) {\n // fetch all restaurants with proper error handling.\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n const restaurant = restaurants.find(r => r.id == id);\n if (restaurant) { // Got the restaurant\n callback(null, restaurant);\n } else { // Restaurant does not exist in the database\n callback('Restaurant does not exist', null);\n }\n }\n });\n }", "static fetchRestaurantById(id, callback) {\r\n // fetch all restaurants with proper error handling.\r\n DBHelper.fetchRestaurants((error, restaurant) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n if (restaurant) { // Got the restaurant\r\n callback(null, restaurant);\r\n } else { // Restaurant does not exist in the database\r\n callback('Restaurant does not exist', null);\r\n }\r\n }\r\n },id);\r\n }", "static fetchRestaurantById(id, callback) {\n\n // fetch all restaurants with proper error handling.\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n const restaurant = restaurants.find(r => r.id == id);\n if (restaurant) { // Got the restaurant\n callback(null, restaurant);\n } else { // Restaurant does not exist in the database\n callback('Restaurant does not exist', null);\n }\n }\n });\n }", "static fetchRestaurantById(id, callback) {\n\n // fetch all restaurants with proper error handling.\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n const restaurant = restaurants.find(r => r.id == id);\n if (restaurant) { // Got the restaurant\n callback(null, restaurant);\n } else { // Restaurant does not exist in the database\n callback('Restaurant does not exist', null);\n }\n }\n });\n }", "static fetchRestaurantById(id, callback) {\n\t\t// fetch all restaurants with proper error handling.\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\tconst restaurant = restaurants.find(r => r.id == id);\n\t\t\t\tif (restaurant) { // Got the restaurant\n\t\t\t\t\tcallback(null, restaurant);\n\t\t\t\t} else { // Restaurant does not exist in the database\n\t\t\t\t\tcallback('Restaurant does not exist', null);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}", "static fetchRestaurantById(id, callback) {\n\t\t// fetch all restaurants with proper error handling.\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\tconst restaurant = restaurants.find(r => r.id == id);\n\t\t\t\tif (restaurant) { // Got the restaurant\n\t\t\t\t\tcallback(null, restaurant);\n\t\t\t\t} else { // Restaurant does not exist in the database\n\t\t\t\t\tcallback('Restaurant does not exist', null);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}", "static fetchRestaurantById(id, callback) {\r\n // fetch all restaurants with proper error handling.\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let restaurant = restaurants.find(r => r.id == id);\r\n\r\n if (restaurant) { // Got the restaurant\r\n DBHelper.fetchRestaurantReviewsById(id, restaurant, callback);\r\n } else { // Restaurant does not exist in the database\r\n callback('Restaurant does not exist', null);\r\n }\r\n }\r\n });\r\n }", "static fetchRestaurantById(id, callback) {\r\n\t\t// fetch all restaurants with proper error handling.\r\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\r\n\t\t\tif (error) {\r\n\t\t\t\tcallback(error, null);\r\n\t\t\t} else {\r\n\t\t\t\tconst restaurant = restaurants.find(r => r.id == id);\r\n\t\t\t\tif (restaurant) {\r\n\t\t\t\t\t// Got the restaurant\r\n\t\t\t\t\tcallback(null, restaurant);\r\n\t\t\t\t} else {\r\n\t\t\t\t\t// Restaurant does not exist in the database\r\n\t\t\t\t\tcallback('Restaurant does not exist', null);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n\t}", "static fetchRestaurantById(id, callback) {\r\n\t\t// fetch all restaurants with proper error handling.\r\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\r\n\t\t\tif (error) {\r\n\t\t\t\tcallback(error, null);\r\n\t\t\t} else {\r\n\t\t\t\tconst restaurant = restaurants.find((r) => r.id == id);\r\n\t\t\t\tif (restaurant) {\r\n\t\t\t\t\t// Got the restaurant\r\n\t\t\t\t\tcallback(null, restaurant);\r\n\t\t\t\t} else {\r\n\t\t\t\t\t// Restaurant does not exist in the database\r\n\t\t\t\t\tcallback('Restaurant does not exist', null);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n\t}", "static fetchRestaurantById(id, callback) {\r\n // fetch all restaurants with proper error handling.\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n const restaurant = restaurants.find(r => r.id == id);\r\n if (restaurant) { // Got the restaurant\r\n DBHelper.fetchReviews(id, (error, reviews) => {\r\n restaurant.reviews = reviews;\r\n callback(null, restaurant);\r\n });\r\n } else { // Restaurant does not exist in the database\r\n callback('Restaurant does not exist', null);\r\n }\r\n }\r\n });\r\n }", "static fetchRestaurantById(id, callback) {\r\n // fetch all restaurants with proper error handling.\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n const restaurant = restaurants.find(r => r.id == id);\r\n if (restaurant) { // Got the restaurant.\r\n callback(null, restaurant);\r\n } else { // Restaurant does not exist in the database.\r\n callback('Restaurant does not exist', null);\r\n }\r\n }\r\n });\r\n }", "findById(id) {\n let sqlRequest = \"SELECT id, name, description FROM restaurants WHERE id=$id\";\n let sqlParams = {\n $id: id\n };\n return this.common.findOne(sqlRequest, sqlParams).then(row =>\n new Restaurant(row.id, row.name, row.description));\n }", "static fetchRestaurantById(id, callback) {\r\n // fetch all restaurants with proper error handling.\r\n const idbRestaurant = idbApp.fetchRestaurantById(id);\r\n idbRestaurant.then(function(idbRestaurantObject) {\r\n if (idbRestaurantObject) {\r\n callback(null, idbRestaurantObject);\r\n return;\r\n }\r\n else {\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n const restaurant = restaurants.find(r => r.id == id);\r\n if (restaurant) {\r\n idbApp.addRestaurantById(restaurant); // add restaurant to DB\r\n callback(null, restaurant);\r\n } else {\r\n callback('Restaurant not found', null);\r\n }\r\n }\r\n });\r\n }\r\n });\r\n }", "findRestaurant({id}) {\r\n\t\tconst cachedResults = cache.getRestaurant(id);\r\n\r\n\t\tif (cachedResults) {\r\n\t\t\tconsole.log(\"Restaurant resolved from cache.\");\r\n\t\t\treturn Promise.resolve(cachedResults);\r\n\t\t}\r\n\r\n\t\treturn dao.findRestaurantByID(id)\r\n\t\t\t.then(bson => {\r\n\t\t\t\tif (bson) {\r\n\t\t\t\t\tconst restaurant = instanceFromBSON(bson);\r\n\t\t\t\t\tcache.cacheRestaurant(restaurant);\r\n\t\t\t\t\treturn restaurant.toJSON();\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t}", "static fetchRestaurants(id, callback) {\n\t\tfetch(DBHelper.REMOTE_SERVER_URL('restaurants', id))\n\t\t\t.then(response => response.status === 200 ? response.json() : null)\n\t\t\t.then(restaurants => restaurants ? DBHelper.saveRestaurantsToIndexedDB(restaurants) : DBHelper.loadRestaurantsFromIndexedDB(id))\n\t\t\t.catch(() => {\n\t\t\t\treturn DBHelper.loadRestaurantsFromIndexedDB(id);\n\t\t\t}).then((restaurants) => callback(null, restaurants));\n\t}", "async fetchRestaurantById(id, callback) {\r\n let restaurant;\r\n const objStoreName = `restaurant`;\r\n try {\r\n const idbPromise = await this.IDB.createObjectStore(objStoreName);\r\n\r\n restaurant = await this.IDB.get(id, objStoreName).then(res => res);\r\n if (restaurant) {\r\n console.log('fetch restaurant from idb');\r\n if (callback) {\r\n callback(null, restaurant);\r\n }\r\n return restaurant;\r\n }\r\n\r\n if (!restaurant) {\r\n const url = this.DATABASE_URL.restaurants + id;\r\n restaurant = await this.apiFetcher(url);\r\n this.IDB.set(id, restaurant, objStoreName);\r\n if (callback) {\r\n callback(null, restaurant);\r\n }\r\n return restaurant;\r\n }\r\n } catch (error) {\r\n console.log('Request failed: ', error);\r\n return {};\r\n }\r\n }", "static fetchRestaurantById(id, callback) {\n // check if restaurant exist inside our indexedDB\n db.fetchById(id)\n .then(restaurant => {\n if (restaurant) {\n callback(null, restaurant);\n } else {\n // fetch restaurant from the database\n fetch(`${DBHelper.DATABASE_URL}/${id}`)\n .then(res => res.json())\n .then(restaurant => {\n callback(null, restaurant);\n db.storebyId(restaurant);\n })\n .catch(error => console.log(error));\n }\n })\n .catch(error => console.log(error));\n }", "getRestaurants(id = undefined) {\n return this.db.then(db => {\n const store = db.transaction('restaurants').objectStore('restaurants');\n if (id) return store.get(Number(id));\n return store.getAll();\n });\n }", "static fecthRestaurantReviewsById(id) {\n return fetch(\n `${DBHelper.DATABASE_URL_REVIEWS}/?restaurant_id=${id}`, {\n method: 'GET'\n }\n ).then(response => response.json());\n }", "function findByRestaurant(id) {\n return db('cuisine_type')\n .where('restaurant_id', id)\n .first()\n}", "fetchRestaurantById(id, callback) {\r\n\t\twindow.idb.openDb().then(() => {\r\n\t\t\twindow.idb.getById(id).then((restaurant) => {\r\n\t\t\t\tcallback(null, restaurant);\r\n\t\t\t});\r\n\t\t}).catch((error) => {\r\n\t\t\tcallback(error, null);\r\n\t\t});\r\n\t}", "static fetchRestaurantById(id, callback) {\n let cached = false;\n\n this.restaurantsDb.selectRestaurantById(id)\n .then(restaurant => {\n if (restaurant && !cached) {\n cached = true\n return callback(null, restaurant)\n } else {\n fetch(`${this.DATABASE_URL}restaurants/${id}`)\n .then(response => {\n if (response.status === 200) {\n return response.json();\n } else { // Oops!. Got an error from server.\n const error = 'Restaurant does not exist';\n callback(error, null);\n }\n })\n .then(response => {\n const restaurant = response;\n callback(null, restaurant);\n });\n }\n });\n }", "static fetchRestaurantById(id, callback) {\r\n // fetch all restaurants with proper error handling.\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n const restaurant = restaurants.find(r => r.id == id);\r\n if (restaurant) { // Got the restaurant\r\n callback(null, restaurant);\r\n } else { // Restaurant does not exist in the database\r\n callback('Restaurant does not exist', null);\r\n }\r\n }\r\n });\r\n}", "getRestaurantById(req,res) {\n\t\treturn Restaurant.findById(req.params.id)\n\t\t.then((restaurant)=>{\n\t\t\tif(!restaurant){\n\t\t\t\treturn res.status(404).send({message:'Restaurant not Found'})\n\t\t\t}\n\t\t\tres.status(200).send(restaurant)\n\t\t}).catch((error)=>{res.status(400).send(error)})\n\t}", "function findRestaurantByID(id){\n\treturn new Promise(function(resolve , reject ){\n\t\tRestaurant.findById(id).then(function(restaurant){\n\t\t\tif(!restaurant){\n\t\t\t\treturn reject(new Error('No restaurant found for id'));\n\t\t\t}\n\t\t\tresolve(restaurant);\n\t\t}).catch(function(err){\n\t\t\treject(err);\n\t\t});\n\t});\n}", "static fetchRestaurantById(id, callback) {\n // fetch all restaurants with proper error handling.\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n const restaurant = restaurants.find(r => r.id == id);\n if (restaurant) { // Got the restaurant\n\n console.log(restaurant);\n fetch(\"http://localhost:1337/reviews/?restaurant_id=\" + restaurant.id)\n .then(function (response) {\n return response.json();\n })\n .then(function (reviews) {\n console.log(reviews);\n restaurant[\"reviews\"] = reviews || [];\n callback(null, restaurant);\n })\n .catch(function (error) {\n console.log(error);\n });\n\n\n // callback(null, restaurant);\n } else { // Restaurant does not exist in the database\n callback('Restaurant does not exist', null);\n }\n }\n });\n }", "static fetchReviewsForRestaurantId(id) {\r\n return new Promise((resolve, reject) => {\r\n DBHelper.openDatabase()\r\n .then(db => {\r\n let tx = db.transaction('reviews');\r\n let store = tx.objectStore('reviews').index('restaurant');\r\n return store.getAll(parseInt(id))\r\n .then(resolve)\r\n .catch((e) => {\r\n console.error('Could not get reviews for Restaurant', e);\r\n resolve([]);\r\n });\r\n });\r\n });\r\n }", "fetchRestaurantFromURL (restaurant) {\n if (this.restaurant) { // restaurant already fetched!\n // return this.restaurant\n return new Promise((resolve) => resolve(this.restaurant))\n }\n const id = this.getParameterByName('id')\n if (!id) { // no id found in URL\n return new Promise((resolve, reject) => reject(new Error('No restaurant id in URL')))\n } else {\n return DBHelper.fetchRestaurantById(id)\n .then(restaurant => {\n this.restaurant = restaurant\n this.fillRestaurantHTML(restaurant)\n return restaurant\n })\n }\n }", "function getRestaurantsById(id) {\n const options = {\n uri: \"https://api.yelp.com/v3/businesses/\" + id,\n headers: {\n \"Authorization\": \"Bearer \" + API_KEY\n },\n json: true\n };\n\n return request(options).then(function (searchResults) {\n return searchResults.name;\n });\n}", "static getRestaurantById(idbPromise, id, callback) {\n return idbPromise.then(db => {\n if (!db) return;\n // get restaurant stored into IDB by id\n return db.transaction('restaurant')\n .objectStore('restaurant')\n .get(Number(id))\n .then(restaurant => callback(restaurant));\n });\n }", "async show(req, res) {\n const { id } = req.params;\n\n const restaurant = await Restaurant.findByPk(id);\n\n return res.json(restaurant);\n }", "static fetchRestaurantById(id, callback) {\r\n let callbackCalled = false;\r\n\r\n DBHelper.IDB_PROMISE\r\n .then(db => {\r\n // always fetch the new restaurant info. However, we will display cache items (if any).\r\n // If there's no restaurants in cached indexedDB, the fetch will return the requested\r\n // restaurant and cache it.\r\n fetch(DBHelper.RESTAURANT_API_URL + id)\r\n .then(restaurantsResponse => {\r\n if (restaurantsResponse.status === 200) {\r\n restaurantsResponse.json()\r\n .then(restaurant => {\r\n fetch(`${DBHelper.REVIEW_API_URL}?restaurant_id=${restaurant.id}`)\r\n .then(reviewsResponse => {\r\n if (reviewsResponse.status === 200) {\r\n return reviewsResponse.json();\r\n }\r\n else {\r\n return [];\r\n }\r\n })\r\n .then(reviews => {\r\n // Only retrieve db store if the browser supports indexed db\r\n let tx, store = undefined;\r\n if (db) {\r\n tx = db.transaction(DBHelper.RESTAURANTS_STORE_NAME, 'readwrite');\r\n store = tx.objectStore(DBHelper.RESTAURANTS_STORE_NAME)\r\n }\r\n\r\n restaurant.photograph = (restaurant.photograph ? restaurant.photograph : restaurant.id) + '.webp';\r\n restaurant.reviews = reviews;\r\n if (typeof restaurant.is_favorite === 'string') {\r\n restaurant.is_favorite = restaurant.is_favorite === 'true';\r\n }\r\n\r\n if (store) {\r\n store.put(restaurant);\r\n }\r\n\r\n callback(null, restaurant);\r\n callbackCalled = true;\r\n if (tx) {\r\n return tx.complete;\r\n }\r\n });\r\n })\r\n } else {\r\n callback(`Request failed. Returned status of ${restaurantsResponse.status}`, null);\r\n }\r\n });\r\n\r\n // if db doesn't exist then there's no point to access db\r\n if (!db) return;\r\n\r\n db.transaction(DBHelper.RESTAURANTS_STORE_NAME, 'readonly')\r\n .objectStore(DBHelper.RESTAURANTS_STORE_NAME)\r\n .get(+id).then(restaurant => {\r\n if (!callbackCalled && restaurant) {\r\n callback(null, restaurant);\r\n callbackCalled = true;\r\n }\r\n });\r\n });\r\n }", "static fetchRestaurantReviewsById(id, restaurant, callback) {\r\n let xhr = new XMLHttpRequest();\r\n const params = '?restaurant_id=' + id;\r\n\r\n xhr.open('GET', DBHelper.REVIEWS_URL + params, true);\r\n xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');\r\n xhr.onload = () => {\r\n if (xhr.status === 200) {\r\n restaurant.reviews = JSON.parse(xhr.responseText);\r\n\r\n callback(null, restaurant);\r\n } else { // Oops!. Got an error from server.\r\n console.error(`Request failed. Returned status of ${xhr.status}`);\r\n callback('Restaurant reviews does not exist', null);\r\n }\r\n };\r\n xhr.send();\r\n }", "static fetchReviewsByRestaurantId(id, callback) {\n\t\tfetch(DBHelper.DATABASE_URL + '/reviews/?restaurant_id=' + id).then((response) => {\n\t\t\treturn response.json();\n\t\t}).then(reviews => {\n\t\t\tif(reviews) {\n\t\t\t\tDBHelper.addToIndexedDB(dbName, dbVersion, 'reviews', reviews);\n\t\t\t\tcallback(null, reviews);\n\t\t\t} else {\n\t\t\t\tDBHelper.getFromIndexedDB(dbName, dbVersion, 'reviews', callback);\n\t\t\t}\n\t\t}).catch(error => { // Got an error from server.\n\t\t\tDBHelper.getFromIndexedDB(dbName, dbVersion, 'reviews', callback);\n\t\t});\n\t}", "getReviewsForRestaurant(id) {\n return this.db.then(db => {\n const storeIndex = db.transaction('reviews').objectStore('reviews').index('restaurant_id');\n return storeIndex.getAll(Number(id));\n });\n }", "static fetchReviewsByRestaurantId(id, callback) {\r\n localDb.then( db => {\r\n const storeName = 'reviews'\r\n let url=DBHelper.DATABASE_URL+`reviews/?restaurant_id=${id}`;\r\n fetch(url)\r\n .then(response => response.json())\r\n .then(response => {\r\n db.transaction(storeName,'readwrite')\r\n .objectStore(storeName)\r\n .put(response,Number(id))\r\n return response;\r\n })\r\n .then(response => callback(null,response))\r\n .catch(error =>{\r\n console.warn(error)\r\n \r\n const tx =db.transaction(storeName,'readwrite');\r\n const store = tx.objectStore(storeName);\r\n store.get(Number(id)).then(response =>{\r\n if(response) return callback(null,response);\r\n })\r\n .catch(callback)\r\n })\r\n })\r\n\r\n }", "getById(knex, id) {\n return knex\n .from('restaurants')\n .select('*')\n .where({ id })\n .first();\n }", "static getReviewsForRestaurant(id) {\n const init = DBHelper.fetchInit('GET');\n const url = `${DBHelper.API_URL}/reviews/?restaurant_id=${id}`;\n return DBHelper.makeCall(url, init);\n }", "static fetchReviewsByRestaurantId (id) {\r\n return fetch(`${DBHelper.DATABASE_URL}/reviews?restaurant_id=${id}`).then(res => {\r\n return res.json().then(json => {\r\n return idb.cacheCollection('reviews', json.reviews).then(() => json.reviews);\r\n });\r\n });\r\n }", "function findById(id){\n return db('restaurants')\n .where({ id })\n .first();\n}", "async show (req, res) {\n const restaurant = await Restaurants.findOne({ id: req.params.id });\n if (!restaurant) {\n return res.status(404).json({\n message: 'Restaurant not found'\n });\n }\n\n res.json({\n restaurant\n });\n }", "function fetchRestaurantFromURL(callback) {\n if (self.restaurant) { // restaurant already fetched!\n callback(null, self.restaurant)\n return;\n }\n const id = getParameterByName('id');\n if (!id) { // no id found in URL\n var error = 'No restaurant id in URL';\n callback(error, null);\n } else {\n DBHelper.fetchRestaurantById(id, (error, restaurant) => {\n self.restaurant = restaurant;\n if (!restaurant) {\n console.error(error);\n return;\n }\n fillRestaurantHTML();\n callback(null, restaurant)\n });\n }\n}", "fetch(id) {\n return this._callApi('get', id);\n }", "static fetchReviewById(id, callback) {\n\t\t// fetch all reviews with proper error handling.\n\t\tDBHelper.fetchReviews((error, reviews) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\tconst review = reviews.find(r => r.id == id);\n\t\t\t\tif (review) { // Got the restaurant\n\t\t\t\t\tcallback(null, review);\n\t\t\t\t} else { // Review does not exist in the database\n\t\t\t\t\tcallback('Review does not exist', null);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}", "async fetchRestaurantReviewsById(id, callback) {\r\n const url = this.DATABASE_URL.restaurantReviews + id;\r\n const res = await this.apiFetcher(url);\r\n if (callback) {\r\n callback(null, res);\r\n }\r\n }", "function show(req, res) {\n\tconsole.log(req.params.id);\n\n\tRestaurant.findById(req.params.id)\n\t\t.then((restaurant, err) => {\n\t\t\tif(err) { res.json (err); }\n\t\t\tconsole.log('hitting the restaurant.show controller on the back end');\n\t\t\tres.json(restaurant);\n\t\t});\n}", "static fetchRestaurantReviewsById(id, callback) {\r\n if(!navigator.onLine) {\r\n idbApp.fetchAllReviewsByRestaurantId(id).then((reviews) => {\r\n return callback(null, reviews)\r\n })\r\n } else {\r\n fetch(DBHelper.BASE_URL + `/reviews/?restaurant_id=${id}`)\r\n .then(response => {\r\n if(response) {\r\n // response.json().then((body) => {console.log(body)}).catch(err => console.log(err))\r\n // // console.log(response.json())\r\n // // idbApp.addReviewByRestaurant(response);\r\n return response.json()\r\n .then(body => {\r\n idbApp.addReviewByRestaurant(id, body);\r\n return body;\r\n })\r\n }\r\n \r\n })\r\n .then(data => callback(null, data))\r\n .catch(err => callback(err, null));\r\n }\r\n }", "getRestaurant(req, res) {\n return models.Restaurant\n .findByPk(req.params.id, {\n include: [{\n model: models.Product\n }, {\n model: models.Info,\n where: {\n language: req.session.language.util\n }\n }]\n })\n .then(restaurant => res.status(200).send(restaurant))\n .catch(error => res.status(400).send(error))\n }", "static loadRestaurantsFromIndexedDB(id) {\n\t\treturn dbPromise.then(function (db) {\n\t\t\tconst tx = db.transaction('restaurants');\n\t\t\tconst restaurantsStore = tx.objectStore('restaurants');\n\t\t\tconst idIndex = restaurantsStore.index('by-id');\n\t\t\treturn id ? restaurantsStore.get(Number(id)) : idIndex.getAll();\n\t\t}).then(function (restaurants) {\n\t\t\treturn restaurants;\n\t\t});\n\t}", "static fetchRestaurants() {\r\n return fetch(DBHelper.DATABASE_URL)\r\n .then( response => {\r\n if (response.ok){\r\n return response.json();\r\n }\r\n }).catch(function(err){\r\n console.log('Fetch error', err);\r\n });\r\n }", "static fetchReviewsById(restaurant_id, cb) {\n DBHelper.fetchReviews(restaurant_id, (error, reviews) => {\n if (error) {\n cb(error, null);\n } else {\n const review = reviews.filter(r => r.restaurant_id == restaurant_id);\n if (review) {\n cb(null, review);\n } else {\n cb('Review does not exist', null);\n }\n }\n });\n }", "function findOne(id, callback) {\n console.log(\"find \" + id);\n RestaurantModel.find({place_id: id}, callback);\n // RestaurantModel.find({place_id: 'ChIJFUBxSY6AhYARwOaLV7TsLjw'}, callback);\n}", "get(id)\n {\n return this._fetch(this._url + '/' + id);\n }", "function queryDb(restaurant_id) {\n}", "getDetail(id) {\n return this.fetch(`${this.api}/${this.resource}/${id}`);\n }", "fetchById(id) {\n // There should be only one match. Return first match or null if undefined.\n return this.data.filter(fruit => fruit.id === id)[0] || null;\n }", "function Restaurant(id){\n\tthis.type = 'restaurant';\n\tthis.id = id;\n}", "fetchRestaurants() {\n return this._updateFromService()\n .then(() => this.db)\n .then(db => {\n const store = this._getStore(db, 'restaurants', false);\n const request = store.openCursor();\n return this._cursorToArray(request);\n });\n }", "function findRestaurant({id,ownerId}={}){\n\tif(typeof id ==='string')\tid = parseInt(id)\n\tif(typeof ownerId ==='string')\townerId = parseInt(ownerId)\n\treturn prisma.restaurant.findMany({ where: {id,ownerId} })\n}", "async function getFoodWithId( req, res, next ) {\n try {\n const resObj = await dataMngr.read( req.params.id );\n res.json( resObj );\n } catch( error ){\n next( error );\n }\n}", "async function getMenuById(id){\n let restaurant = await db('restaurants')\n .where({ id })\n .first()\n let menu = await getRmenu(id)\n return{...restaurant, menu}\n}", "async function getRecipe(id) {\n // let recipe = await fetch(id);\n let recipe = await fetch(`https://bunplanner.herokuapp.com/recipes/${id}`);\n let data = await recipe.json();\n setRecipeToShop(data);\n }", "fetchOneById(fruitId) {\n\t\t\treturn Fruit.collection().query(qb => {\n\t\t\t\tqb.where('id', fruitId);\n\t\t\t}).fetchOne({\n\t\t\t\twithRelated: [\n\t\t\t\t\t'ratings'\n\t\t\t\t]\n\t\t\t});\n\t\t}", "async getRide({ id }) {\n return new Promise(function (resolve, reject) {\n //use paramitarized query to prevent Sql injection\n const query = \"SELECT * FROM Rides WHERE rideID = ?\";\n db.all(query, [id], function (err, rows) {\n if (err) {\n reject(\"Read error: \" + err.message);\n }\n resolve(rows[0]);\n });\n });\n }", "static fetchRestaurants(restaurantIDB, dbCallback, networkCallback) {\r\n DBHelper._retrieveData(\r\n DBHelper._dataRetrievalUseCase.GET_ALL,\r\n networkCallback, \r\n dbCallback, \r\n DBHelper.RESTAURANTS_DATABASE_URL, \r\n restaurantIDB, \r\n 'id');\r\n }", "fetchReviewsByRestId(restaurantId) {\n let DBurl = this.dataBaseUrls().restaurantReviews(restaurantId);\n return fetch(DBurl).then(response => response.json()).then(reviews => {\n idbKeyval.set(REVIEWS_STORE,Number(restaurantId),reviews);\n return Promise.resolve(reviews);\n }).catch(() => {\n return idbKeyval.getItems(REVIEWS_STORE,Number(restaurantId),'restaurants').then(reviews => {\n //console.error(error);\n return Promise.resolve(reviews);\n });\n });\n }", "readById(id, callback) {\n allergiesModel.allergies.find({ where: { id: id } }).then((allergy) => {\n callback(allergy);\n });\n }", "fetchRestaurantByNeighborhood(neighborhood) {\n return this._fetchRestaurantsByIndex('neighborhood', neighborhood);\n }", "function show(id) {\n\n return resource.fetch(id)\n .then(function(data){ return data.data; });\n }", "static fetchById(id) {\n const result = DummyDataHelpers.findById(dummyEntries, id); \n if (!result) {\n return this.badRequest(`no entry for id ${id}`);\n }\n return this.success(`An entry with ${id} has been fetched successfully`, result);\n }", "function getById(rentalId) {\n const rental = findItemById(rentals, rentalId);\n if (!rental) {\n throw new ClientError({\n statusCode: 404,\n code: \"CLI_123\",\n label: \"Unknown rental\",\n });\n }\n return rental;\n}", "findById(id) {\n return db.oneOrNone(`\n SELECT * FROM recipes\n WHERE id = $1\n `, id);\n }", "function getSingleDancer(id) {\n return fetch(danceURL + `/${id}`)\n .then(res => res.json())\n}", "static fetchReviewsByRestaurantId(id, callback) {\r\n /**\r\n * (1) Check local IndexedDB database first and return reviews from there\r\n\t\t* if available. \r\n\t\t* (2) Then, try to fetch reviews from network, \r\n\t\t* (3) clear the IndexedDB database,\r\n\t\t* (4) return the freshly fetched reviews to the callback,\r\n\t\t* (5) and put them into the local IndexedDB again.\r\n\t\t* The clearing of the local database is necessary because reviews may have been \r\n\t\t* deleted, or edited/updated. We can not only add new reviews, because\r\n\t\t* we'd ignore any edited reviews. And we can not just update existing reviews\r\n\t\t* and add new ones to the local database, because we'd ignore if a review was deleted.\r\n */\r\n indexDBPromise.then((db) => {\r\n\t\t\tlet reviewsObjectStore = db.transaction('restaurant-reviews', 'readwrite').objectStore('restaurant-reviews');\r\n let reviewsByDateIndex = reviewsObjectStore.index('by-date');\r\n reviewsByDateIndex.getAll().then((reviews) => {\r\n\t\t\t\tconst reviewsByRestaurantId = reviews.filter(review => review.restaurant_id == id);\r\n\t\t\t\t\r\n\t\t\t\t// (1)\r\n\t\t\t\tcallback(reviewsByRestaurantId);\r\n\t\t\t\t\r\n\t\t\t\t// (2)\r\n\t\t\t\tfetch(`http://localhost:1337/reviews/?restaurant_id=${id}`).then((response) => {\r\n\t\t\t\t\tif (response.ok) {\r\n\t\t\t\t\t\t// (3) We only clear the database, if we successfully fetched updated data:\r\n\t\t\t\t\t\treviewsObjectStore = db.transaction('restaurant-reviews', 'readwrite').objectStore('restaurant-reviews');\r\n\t\t\t\t\t\treviewsByRestaurantId.forEach((review) => {\r\n\t\t\t\t\t\t\treviewsObjectStore.delete(review.id);\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t// (4)\r\n\t\t\t\t\t\tresponse.json().then((reviewsFromNetwork) => {\t\t\t\r\n\t\t\t\t\t\t\tcallback(reviewsFromNetwork);\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t// (5)\r\n\t\t\t\t\t\t\treviewsObjectStore = db.transaction('restaurant-reviews', 'readwrite').objectStore('restaurant-reviews');\r\n\t\t\t\t\t\t\treviewsFromNetwork.forEach((review) => {\r\n\t\t\t\t\t\t\t\treviewsObjectStore.add(review);\r\n\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\tconsole.log(`Network fetch for reviews failed. Returned status of ${response.statusText}`);\r\n\t\t\t\t\t}\r\n\t\t\t\t}).catch((error) => {\r\n\t\t\t\t\tconsole.log(`Network fetch for reviews failed. Are you offline? Error: ${error}`);\r\n\t\t\t\t});\r\n\t\t\t\t\r\n\t\t\t});\r\n });\t\t\r\n\t}" ]
[ "0.84540904", "0.84215057", "0.83600545", "0.8234782", "0.82138604", "0.8033051", "0.7830975", "0.78258544", "0.77985275", "0.777047", "0.77702683", "0.77023655", "0.77004296", "0.76958853", "0.75834715", "0.75834715", "0.75834715", "0.75834715", "0.75834715", "0.7575404", "0.7574838", "0.7574838", "0.7573398", "0.7573398", "0.7571345", "0.7546082", "0.75423086", "0.7506881", "0.7501853", "0.7488247", "0.74644077", "0.7428026", "0.7377765", "0.73247176", "0.7271024", "0.7266084", "0.7257712", "0.72544616", "0.7242051", "0.7169268", "0.715087", "0.7126021", "0.7089201", "0.7065621", "0.7044249", "0.7009651", "0.70082885", "0.70051044", "0.69845504", "0.69740903", "0.6964049", "0.6941052", "0.6937553", "0.6929636", "0.692011", "0.68923306", "0.68859667", "0.68780154", "0.68538153", "0.685361", "0.67632043", "0.6743758", "0.6710387", "0.6608025", "0.66057307", "0.65863025", "0.65845096", "0.65351707", "0.6522843", "0.6507604", "0.64856255", "0.64448255", "0.6420924", "0.64199454", "0.6396114", "0.639286", "0.63633174", "0.6328867", "0.6322284", "0.63071215", "0.6306793", "0.6296644", "0.6282763", "0.62484205", "0.6232242", "0.6187665", "0.6159127", "0.61406124", "0.6117711", "0.61170286", "0.61006564", "0.6082596" ]
0.75293285
34
Fetch restaurants by a cuisine type with proper error handling.
static fetchRestaurantByCuisine(cuisine, callback) { // Fetch all restaurants with proper error handling DBHelper.fetchRestaurants((error, restaurants) => { if (error) { callback(error, null); } else { // Filter restaurants to have only given cuisine type const results = restaurants.filter(r => r.cuisine_type == cuisine); callback(null, results); } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "fetchRestaurantByCuisine(cuisine) {\n // Fetch all restaurants with proper error handling\n return this.fetchRestaurants().then(restaurants => restaurants.filter(restaurant => restaurant.cuisine_type === cuisine));\n }", "static fetchRestaurantByCuisine (cuisine) {\r\n return DBHelper.fetchRestaurants()\r\n .then(restaurants => {\r\n // Filter restaurants to have only given cuisine type\r\n return restaurants.filter(r => r.cuisine_type == cuisine)\r\n })\r\n }", "static fetchRestaurantByCuisine(cuisine, cb) {\n // console.log('>>>>>>> DBHelper - fetchRestaurantByCuisine(cuisine, cb), cuisine =', cuisine);\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n cb(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n cb(null, results);\n }\n });\n }", "fetchRestaurantByCuisine(cuisine, callback) {\r\n // Fetch all restaurants with proper error handling\r\n this.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given cuisine type\r\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\r\n if (callback) {\r\n callback(null, results);\r\n }\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n this.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\r\n // Fetch all restaurants with proper error handling.\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given cuisine type.\r\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(neighborhood, cuisine) {\r\n return DBHelper.fetchJSON(`${DBHelper.DATABASE_URL}/restaurants`)\r\n .then(res => {\r\n let restaurants = res;\r\n if(cuisine != 'all') {\r\n restaurants = restaurants.filter(result => result.cuisine_type == cuisine);\r\n }\r\n\r\n if(neighborhood != 'all') {\r\n restaurants = restaurants.filter(result => result.neighborhood == neighborhood);\r\n }\r\n\r\n return restaurants;\r\n })\r\n .catch(DBHelper.logError);\r\n }", "static fetchRestaurantByCuisine(cuisine) {\n return new Promise((resolve, reject) => {\n // Fetch all restaurants with proper error handling\n DBHelper.getRestaurants().then(restaurants => {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n resolve(results);\n }).catch(error => {\n reject(error);\n });\n });\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\r\n\t\t// Fetch all restaurants with proper error handling\r\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\r\n\t\t\tif (error) {\r\n\t\t\t\tcallback(error, null);\r\n\t\t\t} else {\r\n\t\t\t\t// Filter restaurants to have only given cuisine type\r\n\t\t\t\tconst results = restaurants.filter(r => r.cuisine_type == cuisine);\r\n\t\t\t\tcallback(null, results);\r\n\t\t\t}\r\n\t\t});\r\n\t}", "static fetchRestaurantByCuisine(cuisine, callback) {\r\n\t\t// Fetch all restaurants with proper error handling\r\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\r\n\t\t\tif (error) {\r\n\t\t\t\tcallback(error, null);\r\n\t\t\t} else {\r\n\t\t\t\t// Filter restaurants to have only given cuisine type\r\n\t\t\t\tconst results = restaurants.filter((r) => r.cuisine_type == cuisine);\r\n\t\t\t\tcallback(null, results);\r\n\t\t\t}\r\n\t\t});\r\n\t}", "static fetchRestaurantByCuisine(cuisine, callback) {\n\t\t// Fetch all restaurants with proper error handling\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\t// Filter restaurants to have only given cuisine type\n\t\t\t\tconst results = restaurants.filter(r => r.cuisine_type == cuisine);\n\t\t\t\tcallback(null, results);\n\t\t\t}\n\t\t});\n\t}", "static fetchRestaurantByCuisine(cuisine, callback) {\n\t\t// Fetch all restaurants with proper error handling\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\t// Filter restaurants to have only given cuisine type\n\t\t\t\tconst results = restaurants.filter(r => r.cuisine_type == cuisine);\n\t\t\t\tcallback(null, results);\n\t\t\t}\n\t\t});\n\t}", "static fetchRestaurantByCuisine(cuisine, callback) {\n\t\t// Fetch all restaurants with proper error handling\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\t// Filter restaurants to have only given cuisine type\n\t\t\t\tconst results = restaurants.filter(r => r.cuisine_type == cuisine);\n\t\t\t\tcallback(null, results);\n\t\t\t}\n\t\t});\n\t}", "static fetchRestaurantByCuisine(cuisine, callback) {\r\n // Fetch all restaurants with proper error handling\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given cuisine type\r\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\r\n // Fetch all restaurants with proper error handling\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given cuisine type\r\n const results = restaurants.filter(r => r.cuisine_type === cuisine);\r\n callback(null, results);\r\n }\r\n });\r\n }", "fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood) {\n // Fetch all restaurants\n return this.fetchRestaurants().then(restaurants => {\n let results = restaurants;\n if (cuisine !== 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type === cuisine);\n }\n if (neighborhood !== 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood === neighborhood);\n }\n return results;\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood) {\r\n // Fetch all restaurants\r\n return DBHelper.fetchRestaurants()\r\n .then(res => {\r\n \r\n let results = res;\r\n\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n return results;\r\n });\r\n }", "fetchRestaurantByCuisine(cuisine) {\n return this._fetchRestaurantsByIndex('cuisine', cuisine);\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n\r\n DBHelper.getRestaurants().then(results => {\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null,results);\r\n }).catch((e) => {\r\n callback(e,null)\r\n });\r\n }", "async fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, restaurants) {\r\n // Fetch all restaurants\r\n if (!restaurants || !restaurants.length) {\r\n restaurants = await this.fetchRestaurants();\r\n }\r\n let results = restaurants;\r\n if (cuisine != 'all') {\r\n // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') {\r\n // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n\r\n return results;\r\n }", "static fetchRestaurantByCuisineAndNeighborhood (cuisine, neighborhood, callback) {\r\n return DBHelper.fetchRestaurants()\r\n .then(restaurants => {\r\n if (cuisine != 'all') { // filter by cuisine\r\n restaurants = restaurants.filter(r => r.cuisine_type == cuisine)\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n restaurants = restaurants.filter(r => r.neighborhood == neighborhood)\r\n }\r\n return restaurants\r\n })\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n this.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood) {\n if (cuisine === 'all' && neighborhood === 'all') {\n return this.fetchRestaurants();\n }\n if (neighborhood === 'all') {\n return this.fetchRestaurantByCuisine(cuisine);\n }\n if (cuisine === 'all') {\n return this.fetchRestaurantByNeighborhood(neighborhood);\n }\n return this._fetchRestaurantsByIndex('cuisine_neighborhood', [cuisine, neighborhood]);\n }", "function getRestaurantsByType (type) {\n var request = {\n location: selectedCoords,\n radius: $radius.val(),\n query: type + \" restaurant\"\n };\n $('.bg_overlay_alt').addClass('is_show');\n $('body').addClass('no_scroll');\n placeService.textSearch(request, function (results, status, pagination) {\n if (status === google.maps.places.PlacesServiceStatus.OK) {\n callbackTextSearch(results, pagination, type);\n }\n });\n}", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood) {\n return new Promise((resolve, reject) => {\n // Fetch all restaurants\n DBHelper.getRestaurants().then(restaurants => {\n let results = restaurants;\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n resolve(results);\n }).catch(error => {\n reject(error);\n });\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants;\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants;\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants.\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // Filter by cuisine.\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // Filter by neighborhood.\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') {\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') {\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants;\n\n if (cuisine != 'all') {\n // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n\n if (neighborhood != 'all') {\n // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\t// Filter restaurants to have only given cuisine type\n\t\t\t\tconst results = restaurants.filter(r => r.cuisine_type == neighborhood);\n\t\t\t\tcallback(null, results);\n\t\t\t}\n\t\t});\n\t}", "static fetchRestaurantByCuisineAndNeighborhood(\n cuisine,\n neighborhood,\n callback\n ) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants;\n if (cuisine != \"all\") {\n // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != \"all\") {\n // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\tlet results = restaurants;\n\t\t\t\tif (cuisine !== 'all') { // filter by cuisine\n\t\t\t\t\tresults = results.filter(r => r.cuisine_type == cuisine);\n\t\t\t\t}\n\t\t\t\tif (neighborhood !== 'all') { // filter by neighborhood\n\t\t\t\t\tresults = results.filter(r => r.neighborhood == neighborhood);\n\t\t\t\t}\n\t\t\t\tcallback(null, results);\n\t\t\t}\n\t\t});\n\t}", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n\t\t// Fetch all restaurants\r\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\r\n\t\t\tif (error) {\r\n\t\t\t\tcallback(error, null);\r\n\t\t\t} else {\r\n\t\t\t\tlet results = restaurants;\r\n\t\t\t\tif (cuisine != 'all') {\r\n\t\t\t\t\t// filter by cuisine\r\n\t\t\t\t\tresults = results.filter(r => r.cuisine_type == cuisine);\r\n\t\t\t\t}\r\n\t\t\t\tif (neighborhood != 'all') {\r\n\t\t\t\t\t// filter by neighborhood\r\n\t\t\t\t\tresults = results.filter(r => r.neighborhood == neighborhood);\r\n\t\t\t\t}\r\n\t\t\t\tif (document.getElementById('favorite-checkbox').checked) {\r\n\t\t\t\t\t// filter by favorite\r\n\t\t\t\t\tresults = results.filter(r => r.is_favorite == 'true');\r\n\t\t\t\t}\r\n\t\t\t\tcallback(null, results);\r\n\t\t\t}\r\n\t\t});\r\n\t}", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n\t\t// Fetch all restaurants\r\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\r\n\t\t\tif (error) {\r\n\t\t\t\tcallback(error, null);\r\n\t\t\t} else {\r\n\t\t\t\tlet results = restaurants;\r\n\t\t\t\tif (cuisine != 'all') {\r\n\t\t\t\t\t// filter by cuisine\r\n\t\t\t\t\tresults = results.filter((r) => r.cuisine_type == cuisine);\r\n\t\t\t\t}\r\n\t\t\t\tif (neighborhood != 'all') {\r\n\t\t\t\t\t// filter by neighborhood\r\n\t\t\t\t\tresults = results.filter((r) => r.neighborhood == neighborhood);\r\n\t\t\t\t}\r\n\t\t\t\tcallback(null, results);\r\n\t\t\t}\r\n\t\t});\r\n\t}", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\tlet results = restaurants;\n\t\t\t\tif (cuisine != 'all') { // filter by cuisine\n\t\t\t\t\tresults = results.filter(r => r.cuisine_type == cuisine);\n\t\t\t\t}\n\t\t\t\tif (neighborhood != 'all') { // filter by neighborhood\n\t\t\t\t\tresults = results.filter(r => r.neighborhood == neighborhood);\n\t\t\t\t}\n\t\t\t\tcallback(null, results);\n\t\t\t}\n\t\t});\n\t}", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\tlet results = restaurants;\n\t\t\t\tif (cuisine != 'all') { // filter by cuisine\n\t\t\t\t\tresults = results.filter(r => r.cuisine_type == cuisine);\n\t\t\t\t}\n\t\t\t\tif (neighborhood != 'all') { // filter by neighborhood\n\t\t\t\t\tresults = results.filter(r => r.neighborhood == neighborhood);\n\t\t\t\t}\n\t\t\t\tcallback(null, results);\n\t\t\t}\n\t\t});\n\t}", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants(null, (error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\tlet results = restaurants;\n\t\t\t\tif (cuisine !== 'All Cuisines') { // filter by cuisine\n\t\t\t\t\tresults = results.filter(r => r.cuisine_type === cuisine);\n\t\t\t\t}\n\t\t\t\tif (neighborhood !== 'All Neighborhoods') { // filter by neighborhood\n\t\t\t\t\tresults = results.filter(r => r.neighborhood === neighborhood);\n\t\t\t\t}\n\t\t\t\tcallback(null, results);\n\t\t\t}\n\t\t});\n\t}", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants;\r\n if (cuisine !== 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type === cuisine);\r\n }\r\n if (neighborhood !== 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood === neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchCuisines(callback) {\r\n // Fetch all restaurants\r\n DBHelper.getRestaurants().then(result => {\r\n const cuisines = result.map((v, i) => result[i].cuisine_type)\r\n callback(null,cuisines.filter((v, i) => cuisines.indexOf(v) == i));\r\n })\r\n }", "static fetchCuisines() {\r\n return fetch(DBHelper.DATABASE_URL)\r\n .then( response => {\r\n if (response.ok){\r\n return response.json()\r\n .then(res => {\r\n // Get all cuisines from all restaurants\r\n const cuisines = res.map((v, i) => res[i].cuisine_type)\r\n // Remove duplicates from cuisines\r\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)\r\n return uniqueCuisines;\r\n });\r\n }\r\n }).catch(function(err){\r\n console.log('Fetch error', err);\r\n });\r\n }", "fetchCuisines() {\n // Fetch all restaurants\n return this.fetchRestaurants().then(restaurants => {\n // Get all cuisines from all restaurants\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type);\n // Remove duplicates from cuisines\n return cuisines.filter((v, i) => cuisines.indexOf(v) === i);\n });\n }", "static fetchCuisines(cb) {\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n cb(error, null);\n } else {\n // Get all cuisines from all restaurants\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)\n // Remove duplicates from cuisines\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)\n cb(null, uniqueCuisines);\n }\n });\n }", "static fetchCuisines (callback) {\r\n return DBHelper.fetchRestaurants()\r\n .then(restaurants => {\r\n // Get all cuisines from all restaurants\r\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)\r\n // Remove duplicates from cuisines\r\n return cuisines.filter((v, i) => cuisines.indexOf(v) == i)\r\n })\r\n }", "static fetchCuisines(restaurants, callback) {\r\n return callback(...DBHelper._getCategories(restaurants, 'cuisine_type'));\r\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\r\n DBHelper.openDatabase().then(db => {\r\n let tx = db.transaction('restaurants');\r\n let store = tx.objectStore('restaurants').index('cuisine');\r\n return store.get(cuisine);\r\n }).then(result => {\r\n callback(null,result);\r\n }).catch((e) => {\r\n callback(e,null)\r\n });\r\n }", "static fetchCuisines(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all cuisines from all restaurants\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type);\n // Remove duplicates from cuisines\n const uniqueCuisines = cuisines.filter(\n (v, i) => cuisines.indexOf(v) == i\n );\n callback(null, uniqueCuisines);\n }\n });\n }", "static fetchCuisines(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all cuisines from all restaurants\r\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)\r\n // Remove duplicates from cuisines\r\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)\r\n callback(null, uniqueCuisines);\r\n }\r\n });\r\n }", "static fetchCuisines(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all cuisines from all restaurants\r\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)\r\n // Remove duplicates from cuisines\r\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)\r\n callback(null, uniqueCuisines);\r\n }\r\n });\r\n }", "static fetchCuisines(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all cuisines from all restaurants\r\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)\r\n // Remove duplicates from cuisines\r\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)\r\n callback(null, uniqueCuisines);\r\n }\r\n });\r\n }", "static fetchCuisines(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all cuisines from all restaurants\r\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)\r\n // Remove duplicates from cuisines\r\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)\r\n callback(null, uniqueCuisines);\r\n }\r\n });\r\n }", "static fetchCuisines(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all cuisines from all restaurants\r\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)\r\n // Remove duplicates from cuisines\r\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)\r\n callback(null, uniqueCuisines);\r\n }\r\n });\r\n }" ]
[ "0.79653025", "0.794189", "0.7750687", "0.7699828", "0.769169", "0.769169", "0.769169", "0.769169", "0.769169", "0.769169", "0.769169", "0.769169", "0.769169", "0.76915866", "0.7669903", "0.76631", "0.76631", "0.76492435", "0.764008", "0.7607431", "0.76051086", "0.7603229", "0.7603229", "0.7603229", "0.7547769", "0.7541879", "0.74938875", "0.74476534", "0.7266923", "0.72139287", "0.71741134", "0.71480685", "0.71283513", "0.70951796", "0.70786935", "0.7044678", "0.7044678", "0.7044273", "0.7044273", "0.7044273", "0.7044273", "0.7044273", "0.7044273", "0.7044273", "0.7044273", "0.7044273", "0.7044273", "0.7044273", "0.7044273", "0.7044273", "0.7033894", "0.70294636", "0.70294636", "0.70294636", "0.70294636", "0.70294636", "0.70294636", "0.70294636", "0.7027232", "0.7027232", "0.7018002", "0.7008799", "0.6999729", "0.6997922", "0.6991391", "0.6905801", "0.69053656", "0.6896816", "0.6896724", "0.6896724", "0.68796295", "0.6876832", "0.68765885", "0.68704754", "0.6831096", "0.68130594", "0.6755231", "0.6753412", "0.6725426", "0.6704638", "0.66692007", "0.66560954", "0.66560954", "0.66560954", "0.66560954", "0.66560954" ]
0.76632255
26
Fetch restaurants by a neighborhood with proper error handling.
static fetchRestaurantByNeighborhood(neighborhood, callback) { // Fetch all restaurants DBHelper.fetchRestaurants((error, restaurants) => { if (error) { callback(error, null); } else { // Filter restaurants to have only given neighborhood const results = restaurants.filter(r => r.neighborhood == neighborhood); callback(null, results); } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "static fetchRestaurantByNeighborhood(cb) {\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n cb(error, null);\n } else {\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n cb(null, results);\n }\n });\n }", "fetchRestaurantByNeighborhood(neighborhood) {\n return this._fetchRestaurantsByIndex('neighborhood', neighborhood);\n }", "static fetchRestaurantByNeighborhood (neighborhood) {\r\n return DBHelper.fetchRestaurants()\r\n .then(restaurants => {\r\n // Filter restaurants to have only given neighborhood\r\n return restaurants.filter(r => r.neighborhood == neighborhood)\r\n })\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants.\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood.\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n this.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n\t\t// Fetch all restaurants\r\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\r\n\t\t\tif (error) {\r\n\t\t\t\tcallback(error, null);\r\n\t\t\t} else {\r\n\t\t\t\t// Filter restaurants to have only given neighborhood\r\n\t\t\t\tconst results = restaurants.filter((r) => r.neighborhood == neighborhood);\r\n\t\t\t\tcallback(null, results);\r\n\t\t\t}\r\n\t\t});\r\n\t}", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n\t\t// Fetch all restaurants\r\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\r\n\t\t\tif (error) {\r\n\t\t\t\tcallback(error, null);\r\n\t\t\t} else {\r\n\t\t\t\t// Filter restaurants to have only given neighborhood\r\n\t\t\t\tconst results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n\t\t\t\tcallback(null, results);\r\n\t\t\t}\r\n\t\t});\r\n\t}", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\t// Filter restaurants to have only given neighborhood\n\t\t\t\tconst results = restaurants.filter(r => r.neighborhood == neighborhood);\n\t\t\t\tcallback(null, results);\n\t\t\t}\n\t\t});\n\t}", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\t// Filter restaurants to have only given neighborhood\n\t\t\t\tconst results = restaurants.filter(r => r.neighborhood == neighborhood);\n\t\t\t\tcallback(null, results);\n\t\t\t}\n\t\t});\n\t}", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood === neighborhood);\r\n callback(null, results);\r\n }\r\n });\r\n }", "fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n this.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n if (callback) {\r\n callback(null, results);\r\n }\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood) {\n return new Promise((resolve, reject) => {\n // Fetch all restaurants\n DBHelper.getRestaurants().then(restaurants => {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n resolve(results);\n }).catch(error => {\n reject(error);\n });\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\t// Filter restaurants to have only given cuisine type\n\t\t\t\tconst results = restaurants.filter(r => r.cuisine_type == neighborhood);\n\t\t\t\tcallback(null, results);\n\t\t\t}\n\t\t});\n\t}", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.openDatabase().then(db => {\r\n let tx = db.transaction('restaurants');\r\n let store = tx.objectStore('restaurants').index('neighborhood');\r\n return store.get(neighborhood);\r\n }).then(result => {\r\n callback(null,result);\r\n }).catch((e) => {\r\n callback(e,null)\r\n });\r\n }", "fetchRestaurantByNeighborhood(neighborhood) {\n // Fetch all restaurants\n return this.fetchRestaurants().then(restaurants => restaurants.filter(restaurant => restaurant.neighborhood === neighborhood));\n }", "static fetchNeighborhoods (callback) {\r\n return DBHelper.fetchRestaurants()\r\n .then(restaurants => {\r\n // Filter restaurants to have only given neighborhood\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n return neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n })\r\n }", "static fetchNeighborhoods(cb) {\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n cb(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n cb(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map(\n (v, i) => restaurants[i].neighborhood\n );\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter(\n (v, i) => neighborhoods.indexOf(v) == i\n );\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(neighborhood, cuisine) {\r\n return DBHelper.fetchJSON(`${DBHelper.DATABASE_URL}/restaurants`)\r\n .then(res => {\r\n let restaurants = res;\r\n if(cuisine != 'all') {\r\n restaurants = restaurants.filter(result => result.cuisine_type == cuisine);\r\n }\r\n\r\n if(neighborhood != 'all') {\r\n restaurants = restaurants.filter(result => result.neighborhood == neighborhood);\r\n }\r\n\r\n return restaurants;\r\n })\r\n .catch(DBHelper.logError);\r\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood); // Remove duplicates from neighborhoods\n\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i);\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants.\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants.\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods.\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood) {\r\n // Fetch all restaurants\r\n return DBHelper.fetchRestaurants()\r\n .then(res => {\r\n \r\n let results = res;\r\n\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n return results;\r\n });\r\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n this.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "fetchNeighborhoods() {\n // Fetch all restaurants\n return this.fetchRestaurants().then(restaurants => {\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood);\n return neighborhoods.filter((v, i) => neighborhoods.indexOf(v) === i);\n });\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood);\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) === i);\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\t// Get all neighborhoods from all restaurants\n\t\t\t\tconst neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood);\n\t\t\t\t// Remove duplicates from neighborhoods\n\t\t\t\tconst uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) === i);\n\t\t\t\tcallback(null, uniqueNeighborhoods);\n\t\t\t}\n\t\t});\n\t}", "static fetchNeighborhoods(callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\t// Get all neighborhoods from all restaurants\n\t\t\t\tconst neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood);\n\t\t\t\t// Remove duplicates from neighborhoods\n\t\t\t\tconst uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i);\n\t\t\t\tcallback(null, uniqueNeighborhoods);\n\t\t\t}\n\t\t});\n\t}", "static fetchNeighborhoods(callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\t// Get all neighborhoods from all restaurants\n\t\t\t\tconst neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood);\n\t\t\t\t// Remove duplicates from neighborhoods\n\t\t\t\tconst uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i);\n\t\t\t\tcallback(null, uniqueNeighborhoods);\n\t\t\t}\n\t\t});\n\t}", "static fetchNeighborhoods(callback) {\r\n\t\t// Fetch all restaurants\r\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\r\n\t\t\tif (error) {\r\n\t\t\t\tcallback(error, null);\r\n\t\t\t} else {\r\n\t\t\t\t// Get all neighborhoods from all restaurants\r\n\t\t\t\tconst neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood);\r\n\t\t\t\t// Remove duplicates from neighborhoods\r\n\t\t\t\tconst uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i);\r\n\t\t\t\tcallback(null, uniqueNeighborhoods);\r\n\t\t\t}\r\n\t\t});\r\n\t}", "static fetchNeighborhoods(callback) {\r\n\t\t// Fetch all restaurants\r\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\r\n\t\t\tif (error) {\r\n\t\t\t\tcallback(error, null);\r\n\t\t\t} else {\r\n\t\t\t\t// Get all neighborhoods from all restaurants\r\n\t\t\t\tconst neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood);\r\n\t\t\t\t// Remove duplicates from neighborhoods\r\n\t\t\t\tconst uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i);\r\n\t\t\t\tcallback(null, uniqueNeighborhoods);\r\n\t\t\t}\r\n\t\t});\r\n\t}", "static fetchNeighborhoods(callback) {\r\n DBHelper.getRestaurants().then(result => {\r\n const neighborhoods = result.map((v, i) => result[i].neighborhood)\r\n callback(null,neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i));\r\n })\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood) {\n if (cuisine === 'all' && neighborhood === 'all') {\n return this.fetchRestaurants();\n }\n if (neighborhood === 'all') {\n return this.fetchRestaurantByCuisine(cuisine);\n }\n if (cuisine === 'all') {\n return this.fetchRestaurantByNeighborhood(neighborhood);\n }\n return this._fetchRestaurantsByIndex('cuisine_neighborhood', [cuisine, neighborhood]);\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n\r\n DBHelper.getRestaurants().then(results => {\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null,results);\r\n }).catch((e) => {\r\n callback(e,null)\r\n });\r\n }", "fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood) {\n // Fetch all restaurants\n return this.fetchRestaurants().then(restaurants => {\n let results = restaurants;\n if (cuisine !== 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type === cuisine);\n }\n if (neighborhood !== 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood === neighborhood);\n }\n return results;\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants;\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants;\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }" ]
[ "0.8068655", "0.80564713", "0.79725736", "0.7930988", "0.7930988", "0.7930988", "0.7930988", "0.7930988", "0.7930988", "0.7930988", "0.7930988", "0.7930988", "0.7910176", "0.7910176", "0.788401", "0.78660226", "0.7813408", "0.7812883", "0.7812393", "0.78097826", "0.78097826", "0.7809307", "0.7807425", "0.78029907", "0.76805776", "0.7630331", "0.75961596", "0.7445399", "0.74073875", "0.7248585", "0.72007984", "0.7198897", "0.71789116", "0.71789116", "0.71789116", "0.71789116", "0.71789116", "0.71789116", "0.71789116", "0.7172958", "0.7172958", "0.7172958", "0.7172958", "0.7172958", "0.7172958", "0.7172958", "0.7172958", "0.7172958", "0.7172958", "0.7172958", "0.7172958", "0.7172958", "0.7172958", "0.7172958", "0.716882", "0.7155989", "0.7155989", "0.7150679", "0.7112528", "0.7095199", "0.7072295", "0.70696217", "0.70616204", "0.70616204", "0.7050151", "0.7050151", "0.7044235", "0.70376056", "0.6973946", "0.6907704", "0.6844561", "0.6798263", "0.6798263", "0.6798263", "0.6798263", "0.6798263", "0.6798263", "0.6798263", "0.6798263", "0.6798263", "0.6798263", "0.6798263", "0.6798263", "0.6798263", "0.67960405", "0.67960405" ]
0.7901411
24
Fetch restaurants by a cuisine and a neighborhood with proper error handling.
static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) { // Fetch all restaurants DBHelper.fetchRestaurants((error, restaurants) => { if (error) { callback(error, null); } else { let results = restaurants if (cuisine != 'all') { // filter by cuisine results = results.filter(r => r.cuisine_type == cuisine); } if (neighborhood != 'all') { // filter by neighborhood results = results.filter(r => r.neighborhood == neighborhood); } callback(null, results); } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood) {\r\n // Fetch all restaurants\r\n return DBHelper.fetchRestaurants()\r\n .then(res => {\r\n \r\n let results = res;\r\n\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n return results;\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(neighborhood, cuisine) {\r\n return DBHelper.fetchJSON(`${DBHelper.DATABASE_URL}/restaurants`)\r\n .then(res => {\r\n let restaurants = res;\r\n if(cuisine != 'all') {\r\n restaurants = restaurants.filter(result => result.cuisine_type == cuisine);\r\n }\r\n\r\n if(neighborhood != 'all') {\r\n restaurants = restaurants.filter(result => result.neighborhood == neighborhood);\r\n }\r\n\r\n return restaurants;\r\n })\r\n .catch(DBHelper.logError);\r\n }", "fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood) {\n if (cuisine === 'all' && neighborhood === 'all') {\n return this.fetchRestaurants();\n }\n if (neighborhood === 'all') {\n return this.fetchRestaurantByCuisine(cuisine);\n }\n if (cuisine === 'all') {\n return this.fetchRestaurantByNeighborhood(neighborhood);\n }\n return this._fetchRestaurantsByIndex('cuisine_neighborhood', [cuisine, neighborhood]);\n }", "fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood) {\n // Fetch all restaurants\n return this.fetchRestaurants().then(restaurants => {\n let results = restaurants;\n if (cuisine !== 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type === cuisine);\n }\n if (neighborhood !== 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood === neighborhood);\n }\n return results;\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n\r\n DBHelper.getRestaurants().then(results => {\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null,results);\r\n }).catch((e) => {\r\n callback(e,null)\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants;\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants;\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants;\n\n if (cuisine != 'all') {\n // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n\n if (neighborhood != 'all') {\n // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants.\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // Filter by cuisine.\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // Filter by neighborhood.\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n // Fetch all restaurants\n this.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants\n if (cuisine != 'all') {\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') {\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood) {\n return new Promise((resolve, reject) => {\n // Fetch all restaurants\n DBHelper.getRestaurants().then(restaurants => {\n let results = restaurants;\n if (cuisine != 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n resolve(results);\n }).catch(error => {\n reject(error);\n });\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood (cuisine, neighborhood, callback) {\r\n return DBHelper.fetchRestaurants()\r\n .then(restaurants => {\r\n if (cuisine != 'all') { // filter by cuisine\r\n restaurants = restaurants.filter(r => r.cuisine_type == cuisine)\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n restaurants = restaurants.filter(r => r.neighborhood == neighborhood)\r\n }\r\n return restaurants\r\n })\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(\n cuisine,\n neighborhood,\n callback\n ) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n let results = restaurants;\n if (cuisine != \"all\") {\n // filter by cuisine\n results = results.filter(r => r.cuisine_type == cuisine);\n }\n if (neighborhood != \"all\") {\n // filter by neighborhood\n results = results.filter(r => r.neighborhood == neighborhood);\n }\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\tlet results = restaurants;\n\t\t\t\tif (cuisine !== 'all') { // filter by cuisine\n\t\t\t\t\tresults = results.filter(r => r.cuisine_type == cuisine);\n\t\t\t\t}\n\t\t\t\tif (neighborhood !== 'all') { // filter by neighborhood\n\t\t\t\t\tresults = results.filter(r => r.neighborhood == neighborhood);\n\t\t\t\t}\n\t\t\t\tcallback(null, results);\n\t\t\t}\n\t\t});\n\t}", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\tlet results = restaurants;\n\t\t\t\tif (cuisine != 'all') { // filter by cuisine\n\t\t\t\t\tresults = results.filter(r => r.cuisine_type == cuisine);\n\t\t\t\t}\n\t\t\t\tif (neighborhood != 'all') { // filter by neighborhood\n\t\t\t\t\tresults = results.filter(r => r.neighborhood == neighborhood);\n\t\t\t\t}\n\t\t\t\tcallback(null, results);\n\t\t\t}\n\t\t});\n\t}", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\tlet results = restaurants;\n\t\t\t\tif (cuisine != 'all') { // filter by cuisine\n\t\t\t\t\tresults = results.filter(r => r.cuisine_type == cuisine);\n\t\t\t\t}\n\t\t\t\tif (neighborhood != 'all') { // filter by neighborhood\n\t\t\t\t\tresults = results.filter(r => r.neighborhood == neighborhood);\n\t\t\t\t}\n\t\t\t\tcallback(null, results);\n\t\t\t}\n\t\t});\n\t}", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n\t\t// Fetch all restaurants\r\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\r\n\t\t\tif (error) {\r\n\t\t\t\tcallback(error, null);\r\n\t\t\t} else {\r\n\t\t\t\tlet results = restaurants;\r\n\t\t\t\tif (cuisine != 'all') {\r\n\t\t\t\t\t// filter by cuisine\r\n\t\t\t\t\tresults = results.filter((r) => r.cuisine_type == cuisine);\r\n\t\t\t\t}\r\n\t\t\t\tif (neighborhood != 'all') {\r\n\t\t\t\t\t// filter by neighborhood\r\n\t\t\t\t\tresults = results.filter((r) => r.neighborhood == neighborhood);\r\n\t\t\t\t}\r\n\t\t\t\tcallback(null, results);\r\n\t\t\t}\r\n\t\t});\r\n\t}", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n\t\t// Fetch all restaurants\r\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\r\n\t\t\tif (error) {\r\n\t\t\t\tcallback(error, null);\r\n\t\t\t} else {\r\n\t\t\t\tlet results = restaurants;\r\n\t\t\t\tif (cuisine != 'all') {\r\n\t\t\t\t\t// filter by cuisine\r\n\t\t\t\t\tresults = results.filter(r => r.cuisine_type == cuisine);\r\n\t\t\t\t}\r\n\t\t\t\tif (neighborhood != 'all') {\r\n\t\t\t\t\t// filter by neighborhood\r\n\t\t\t\t\tresults = results.filter(r => r.neighborhood == neighborhood);\r\n\t\t\t\t}\r\n\t\t\t\tif (document.getElementById('favorite-checkbox').checked) {\r\n\t\t\t\t\t// filter by favorite\r\n\t\t\t\t\tresults = results.filter(r => r.is_favorite == 'true');\r\n\t\t\t\t}\r\n\t\t\t\tcallback(null, results);\r\n\t\t\t}\r\n\t\t});\r\n\t}", "static fetchRestaurantByNeighborhood(cb) {\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n cb(error, null);\n } else {\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n cb(null, results);\n }\n });\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants(null, (error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\tlet results = restaurants;\n\t\t\t\tif (cuisine !== 'All Cuisines') { // filter by cuisine\n\t\t\t\t\tresults = results.filter(r => r.cuisine_type === cuisine);\n\t\t\t\t}\n\t\t\t\tif (neighborhood !== 'All Neighborhoods') { // filter by neighborhood\n\t\t\t\t\tresults = results.filter(r => r.neighborhood === neighborhood);\n\t\t\t\t}\n\t\t\t\tcallback(null, results);\n\t\t\t}\n\t\t});\n\t}", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants\r\n if (cuisine != 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n let results = restaurants;\r\n if (cuisine !== 'all') { // filter by cuisine\r\n results = results.filter(r => r.cuisine_type === cuisine);\r\n }\r\n if (neighborhood !== 'all') { // filter by neighborhood\r\n results = results.filter(r => r.neighborhood === neighborhood);\r\n }\r\n callback(null, results);\r\n }\r\n });\r\n }", "async fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, restaurants) {\r\n // Fetch all restaurants\r\n if (!restaurants || !restaurants.length) {\r\n restaurants = await this.fetchRestaurants();\r\n }\r\n let results = restaurants;\r\n if (cuisine != 'all') {\r\n // filter by cuisine\r\n results = results.filter(r => r.cuisine_type == cuisine);\r\n }\r\n if (neighborhood != 'all') {\r\n // filter by neighborhood\r\n results = results.filter(r => r.neighborhood == neighborhood);\r\n }\r\n\r\n return results;\r\n }", "fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {\r\n\t\twindow.idb.openDb().then(() => {\r\n\t\t\tif (neighborhood == 'all' && cuisine == 'all') {\r\n\t\t\t\twindow.idb.getAll().then((restaurants) => {\r\n\t\t\t\t\tcallback(null, restaurants);\r\n\t\t\t\t});\r\n\t\t\t} else {\r\n\t\t\t\tlet index = [];\r\n\t\t\t\tlet value = [];\r\n\r\n\t\t\t\tif (neighborhood != 'all') {\r\n\t\t\t\t\tindex.push('neighborhood');\r\n\t\t\t\t\tvalue.push(neighborhood);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (cuisine != 'all') {\r\n\t\t\t\t\tindex.push('cuisine_type');\r\n\t\t\t\t\tvalue.push(cuisine);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (value.length == 1) {\r\n\t\t\t\t\tvalue = value.join('');\r\n\t\t\t\t}\r\n\r\n\t\t\t\twindow.idb.getByIndex(index.join('_'), value).then((restaurant) => {\r\n\t\t\t\t\tcallback(null, restaurant);\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t}).catch((error) => {\r\n\t\t\tcallback(error, null);\r\n\t\t});\r\n\t}", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\t// Filter restaurants to have only given cuisine type\n\t\t\t\tconst results = restaurants.filter(r => r.cuisine_type == neighborhood);\n\t\t\t\tcallback(null, results);\n\t\t\t}\n\t\t});\n\t}", "fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n this.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n if (callback) {\r\n callback(null, results);\r\n }\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n this.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood (neighborhood) {\r\n return DBHelper.fetchRestaurants()\r\n .then(restaurants => {\r\n // Filter restaurants to have only given neighborhood\r\n return restaurants.filter(r => r.neighborhood == neighborhood)\r\n })\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants.\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood.\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n callback(null, results);\r\n }\r\n });\r\n }", "fetchRestaurantByNeighborhood(neighborhood) {\n return this._fetchRestaurantsByIndex('neighborhood', neighborhood);\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n\t\t// Fetch all restaurants\r\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\r\n\t\t\tif (error) {\r\n\t\t\t\tcallback(error, null);\r\n\t\t\t} else {\r\n\t\t\t\t// Filter restaurants to have only given neighborhood\r\n\t\t\t\tconst results = restaurants.filter((r) => r.neighborhood == neighborhood);\r\n\t\t\t\tcallback(null, results);\r\n\t\t\t}\r\n\t\t});\r\n\t}", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n\t\t// Fetch all restaurants\r\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\r\n\t\t\tif (error) {\r\n\t\t\t\tcallback(error, null);\r\n\t\t\t} else {\r\n\t\t\t\t// Filter restaurants to have only given neighborhood\r\n\t\t\t\tconst results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n\t\t\t\tcallback(null, results);\r\n\t\t\t}\r\n\t\t});\r\n\t}", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood) {\n return new Promise((resolve, reject) => {\n // Fetch all restaurants\n DBHelper.getRestaurants().then(restaurants => {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n resolve(results);\n }).catch(error => {\n reject(error);\n });\n });\n }", "fetchRestaurantByNeighborhood(neighborhood) {\n // Fetch all restaurants\n return this.fetchRestaurants().then(restaurants => restaurants.filter(restaurant => restaurant.neighborhood === neighborhood));\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\t// Filter restaurants to have only given neighborhood\n\t\t\t\tconst results = restaurants.filter(r => r.neighborhood == neighborhood);\n\t\t\t\tcallback(null, results);\n\t\t\t}\n\t\t});\n\t}", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\t// Filter restaurants to have only given neighborhood\n\t\t\t\tconst results = restaurants.filter(r => r.neighborhood == neighborhood);\n\t\t\t\tcallback(null, results);\n\t\t\t}\n\t\t});\n\t}", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood === neighborhood);\r\n callback(null, results);\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.openDatabase().then(db => {\r\n let tx = db.transaction('restaurants');\r\n let store = tx.objectStore('restaurants').index('neighborhood');\r\n return store.get(neighborhood);\r\n }).then(result => {\r\n callback(null,result);\r\n }).catch((e) => {\r\n callback(e,null)\r\n });\r\n }", "static fetchNeighborhoods(cb) {\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n cb(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n cb(null, uniqueNeighborhoods);\n }\n });\n }", "static getRestaurants(idbPromise, cuisine, neighborhood, callback) {\n return idbPromise.then(db => {\n if (!db) return;\n\n let promise;\n const store = db.transaction('restaurant')\n .objectStore('restaurant');\n if (cuisine != 'all' && neighborhood != 'all') {\n promise = store.index('neighborhood, cuisine-type')\n .getAll([neighborhood, cuisine]);\n } else if (cuisine != 'all') {\n promise = store.index('cuisine-type')\n .getAll(cuisine);\n } else if (neighborhood != 'all') {\n promise = store.index('neighborhood')\n .getAll(neighborhood);\n } else {\n promise = store.getAll();\n }\n return promise.then(restaurants => callback(restaurants));\n });\n }", "static fetchRestaurantByCuisine(cuisine, cb) {\n // console.log('>>>>>>> DBHelper - fetchRestaurantByCuisine(cuisine, cb), cuisine =', cuisine);\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n cb(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n cb(null, results);\n }\n });\n }", "fetchRestaurantByCuisine(cuisine) {\n // Fetch all restaurants with proper error handling\n return this.fetchRestaurants().then(restaurants => restaurants.filter(restaurant => restaurant.cuisine_type === cuisine));\n }", "static fetchNeighborhoods (callback) {\r\n return DBHelper.fetchRestaurants()\r\n .then(restaurants => {\r\n // Filter restaurants to have only given neighborhood\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n return neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n })\r\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map(\n (v, i) => restaurants[i].neighborhood\n );\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter(\n (v, i) => neighborhoods.indexOf(v) == i\n );\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood); // Remove duplicates from neighborhoods\n\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i);\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchRestaurantByCuisine (cuisine) {\r\n return DBHelper.fetchRestaurants()\r\n .then(restaurants => {\r\n // Filter restaurants to have only given cuisine type\r\n return restaurants.filter(r => r.cuisine_type == cuisine)\r\n })\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }" ]
[ "0.84062105", "0.84022444", "0.831087", "0.8243038", "0.81832695", "0.81235147", "0.81235147", "0.81235147", "0.81235147", "0.81235147", "0.81235147", "0.81235147", "0.8116345", "0.8116345", "0.8112629", "0.8112629", "0.8104913", "0.8099702", "0.80821717", "0.80770075", "0.8075517", "0.8068742", "0.8039604", "0.80362004", "0.8025843", "0.8025843", "0.8007495", "0.79999644", "0.7999601", "0.799827", "0.79981697", "0.79959726", "0.78504086", "0.77948713", "0.7781506", "0.7600652", "0.7573779", "0.75512934", "0.7531873", "0.7531873", "0.7531873", "0.7531873", "0.7531873", "0.7531873", "0.7531873", "0.7531873", "0.7531873", "0.7522745", "0.7522745", "0.75202423", "0.75202423", "0.75202423", "0.75202423", "0.75202423", "0.75202423", "0.75202423", "0.75202423", "0.75202423", "0.75202423", "0.75202423", "0.75202423", "0.75202423", "0.75202423", "0.75202423", "0.747859", "0.742488", "0.7417522", "0.7414977", "0.74132204", "0.74084836", "0.7407839", "0.74045527", "0.74045527", "0.7401582", "0.7349504", "0.7318302", "0.73029035", "0.7245399", "0.72447354", "0.7195026", "0.7081717", "0.70575285", "0.70316404", "0.7030645", "0.7030645", "0.7030645", "0.7030645", "0.7030645" ]
0.8121277
21
Fetch all neighborhoods with proper error handling.
static fetchNeighborhoods(callback) { // Fetch all restaurants DBHelper.fetchRestaurants((error, restaurants) => { if (error) { callback(error, null); } else { // Get all neighborhoods from all restaurants const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood) // Remove duplicates from neighborhoods const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i) callback(null, uniqueNeighborhoods); } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function fetchNeighborhoods() {\n DBHelper.fetchNeighborhoods((error, neighborhoods) => { // eslint-disable-line no-undef\n if (error) { // Got an error\n console.error(error);\n } else {\n main.neighborhoods = neighborhoods;\n IndexDBHelper.storeNeighborhoods(neighborhoods); // eslint-disable-line no-undef\n resetNeighborhoods();\n fillNeighborhoodsHTML();\n }\n });\n}", "fetchNeighborhoods() {\n return this._getIndexRange('neighborhood');\n }", "static fetchNeighborhoods(callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\t// Get all neighborhoods from all restaurants\n\t\t\t\tconst neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood);\n\t\t\t\t// Remove duplicates from neighborhoods\n\t\t\t\tconst uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) === i);\n\t\t\t\tcallback(null, uniqueNeighborhoods);\n\t\t\t}\n\t\t});\n\t}", "static fetchNeighborhoods(callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\t// Get all neighborhoods from all restaurants\n\t\t\t\tconst neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood);\n\t\t\t\t// Remove duplicates from neighborhoods\n\t\t\t\tconst uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i);\n\t\t\t\tcallback(null, uniqueNeighborhoods);\n\t\t\t}\n\t\t});\n\t}", "static fetchNeighborhoods(callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\t// Get all neighborhoods from all restaurants\n\t\t\t\tconst neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood);\n\t\t\t\t// Remove duplicates from neighborhoods\n\t\t\t\tconst uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i);\n\t\t\t\tcallback(null, uniqueNeighborhoods);\n\t\t\t}\n\t\t});\n\t}", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map(\n (v, i) => restaurants[i].neighborhood\n );\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter(\n (v, i) => neighborhoods.indexOf(v) == i\n );\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods() {\r\n return fetch(DBHelper.DATABASE_URL)\r\n .then( response => {\r\n if (response.ok){\r\n return response.json()\r\n .then(res => {\r\n const neighborhoods = res.map((v, i) => res[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n return uniqueNeighborhoods;\r\n });\r\n }\r\n }).catch(function(err){\r\n console.log('Fetch error', err);\r\n });\r\n }", "static fetchNeighborhoods(cb) {\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n cb(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n cb(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood); // Remove duplicates from neighborhoods\n\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i);\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood);\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) === i);\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants.\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants.\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods.\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\r\n\t\t// Fetch all restaurants\r\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\r\n\t\t\tif (error) {\r\n\t\t\t\tcallback(error, null);\r\n\t\t\t} else {\r\n\t\t\t\t// Get all neighborhoods from all restaurants\r\n\t\t\t\tconst neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood);\r\n\t\t\t\t// Remove duplicates from neighborhoods\r\n\t\t\t\tconst uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i);\r\n\t\t\t\tcallback(null, uniqueNeighborhoods);\r\n\t\t\t}\r\n\t\t});\r\n\t}", "static fetchNeighborhoods(callback) {\r\n\t\t// Fetch all restaurants\r\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\r\n\t\t\tif (error) {\r\n\t\t\t\tcallback(error, null);\r\n\t\t\t} else {\r\n\t\t\t\t// Get all neighborhoods from all restaurants\r\n\t\t\t\tconst neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood);\r\n\t\t\t\t// Remove duplicates from neighborhoods\r\n\t\t\t\tconst uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i);\r\n\t\t\t\tcallback(null, uniqueNeighborhoods);\r\n\t\t\t}\r\n\t\t});\r\n\t}", "static fetchNeighborhoods(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n callback(null, uniqueNeighborhoods);\r\n }\r\n });\r\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods(callback) {\n // Fetch all restaurants\n this.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\n callback(null, uniqueNeighborhoods);\n }\n });\n }", "static fetchNeighborhoods () {\r\n return fetch(`${DBHelper.DATABASE_URL}/neighborhoods`).then(res => {\r\n return res.json().then(json => {\r\n return idb.cacheCollection('neighborhoods', json.neighborhoods).then(() => json.neighborhoods);\r\n });\r\n });\r\n }", "fetchNeighborhoods(callback) {\r\n\t\twindow.idb.openDb().then(() => {\r\n\t\t\twindow.idb.getAll().then((restaurants) => {\r\n\t\t\t\t// Get all neighborhoods from all restaurants\r\n\t\t\t\tconst neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood);\r\n\t\t\t\t// Remove duplicates from neighborhoods\r\n\t\t\t\tconst uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i);\r\n\t\t\t\tcallback(null, uniqueNeighborhoods);\r\n\t\t\t});\r\n\t\t}).catch((error) => {\r\n\t\t\tcallback(error, null);\r\n\t\t});\r\n\t}", "static fetchNeighborhoods (callback) {\r\n return DBHelper.fetchRestaurants()\r\n .then(restaurants => {\r\n // Filter restaurants to have only given neighborhood\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n return neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n })\r\n }", "static fetchNeighborhoods() {\n return new Promise((resolve, reject) => {\n // Fetch all restaurants\n DBHelper.getRestaurants().then(restaurants => {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood);\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i);\n resolve(uniqueNeighborhoods);\n }).catch(error => {\n reject(error);\n });\n });\n }", "fetchNeighborhoods() {\n // Fetch all restaurants\n return this.fetchRestaurants().then(restaurants => {\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood);\n return neighborhoods.filter((v, i) => neighborhoods.indexOf(v) === i);\n });\n }", "static fetchNeighborhoods(callback) {\r\n DBHelper.getRestaurants().then(result => {\r\n const neighborhoods = result.map((v, i) => result[i].neighborhood)\r\n callback(null,neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i));\r\n })\r\n }", "static fetchNeighborhoods() {\n return DBHelper.fetchRestaurantsPromise()\n .then(restaurants => {\n // Get all neighborhoods from all restaurants\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood);\n // Remove duplicates from neighborhoods\n const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i);\n return uniqueNeighborhoods;\n }).catch(console.log);\n }", "static getNeighborhoods(idbPromise, callback) {\n return idbPromise.then(db => {\n if (!db) return;\n\n // get neighborhoods stored into IDB\n return db.transaction('neighborhood')\n .objectStore('neighborhood')\n .getAll()\n .then(neighborhoods => callback(neighborhoods));\n });\n }", "static fetchNeighborhoods(restaurants, callback) {\r\n return callback(...DBHelper._getCategories(restaurants, 'neighborhood'));\r\n }", "function getAllNodesNeighborhood(){\n\t\tglobalData.nodes.map(function(node){\n\t\t\tnode.neighbors = getNeighborhoodLabels(node.index)\n\t\t\tneighborhoodLengths.push(node.neighbors.length)\n\t\t\td3.select('#' + node.label)\n\t\t\t\t.attr('neighborhood', node.neighbors.toString())\n\t\t})\n\t}", "findNeighbours() {\n const n = this.neighbours;\n const { row, col } = this.pos;\n n.topleft = boxes[row - 1]?.[col - 1]; // get top left corner\n n.top = boxes[row - 1]?.[col]; // get the top box\n n.topright = boxes[row - 1]?.[col + 1]; // get top right corner\n n.right = boxes[row]?.[col + 1]; // get the right box\n n.bottomright = boxes[row + 1]?.[col + 1]; // get bottom right corner\n n.bottom = boxes[row + 1]?.[col]; // get the bottom box\n n.bottomleft = boxes[row + 1]?.[col - 1]; // get bottom left corner\n n.left = boxes[row]?.[col - 1]; // get the left box\n // add all neighbours that exist to allNeighbours array\n this.allNeighbours = Object.values(n).filter((n) => n);\n }", "getNeighbours(data, height, width) {\n let updatedData = data;\n for (let i = 0; i < height; i++) {\n for (let j = 0; j < width; j++) {\n if (!data[i][j].isMine) {\n let mine = 0;\n const area = this.traverseBoard(data[i][j].x, data[i][j].y, data);\n area.map((value) => {\n if (value.isMine) {\n mine++;\n }\n });\n if (mine === 0) {\n updatedData[i][j].isEmpty = true;\n }\n updatedData[i][j].neighbour = mine;\n }\n }\n }\n\n return updatedData;\n }", "function tryToFindAll() {\n // Tries GET\n try {\n\n // SUPPORTED TYPES for Place API 'Nearby': https://developers.google.com/places/web-service/supported_types\n\n return getData('https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-8.060726,-34.891307&rankby=distance&type=parking&keyword=estacionamento&key=YOUR_KEY_HERE', organizeFoundPlaces);\n\n } catch (error) {\n console.error(error);\n }\n}", "findAllNeighbors() {\r\n for (let i = 0; i < this.items.length; i++) {\r\n const row = this.items[i];\r\n for (let j = 0; j < row.length; j++) {\r\n const item = this.items[i][j];\r\n item.neighbors = [];\r\n item.findNeighbors(this);\r\n item.checkShouldChangeColor();\r\n // console.log(item.neighbors);\r\n // console.log('----------------------------');\r\n }\r\n }\r\n }", "static fetchRestaurantByNeighborhood(cb) {\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n cb(error, null);\n } else {\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n cb(null, results);\n }\n });\n }", "getNeighbors(node) {\n const neighbors = [];\n Object.values(node.walls).forEach((side) => {\n if (side instanceof Cell) {\n neighbors.push(side);\n }\n })\n return neighbors; \n }", "function findAllNeighbors() {\n var neighbors = [];\n var tiles = qsa(\"#puzzlearea div\");\n for (var i = 0; i < tiles.length; i++) {\n var currentTile = tiles.item(i);\n var left = getLeftPosition(currentTile);\n var top = getTopPosition(currentTile);\n // If the current tile is movable, that means it is a neighbor of the empty tile\n if (isMovable(left, top)) {\n neighbors.push(currentTile);\n }\n }\n return neighbors;\n }", "getNeighbors(grid, d, isWall) {\n // Could be a property of the class?\n let moves = [[-d,0],[0,d],[d,0],[0,-d]];\n let neighbors = [];\n for (let move of moves) {\n\n const [row,col] = move;\n let nr = row + this.y;\n let nc = col + this.x;\n\n //if it is or is not a wall, then we add this to our valid neighbors array;\n if(isValidLocation(grid,nr,nc) && \n (isWall === grid[nr][nc].isWall)) {\n\n neighbors.push(grid[nr][nc]);\n }\n }\n \n return neighbors\n }", "getNeighbors() {\n const neighbors = new Array();\n for (const direction of TILE_DIRECTIONS) {\n const neighbor = this.getNeighbor(direction);\n if (neighbor) {\n neighbors.push(neighbor);\n }\n }\n return neighbors;\n }", "async getNeighbors(codes) {\n // wait for the promise all to return value\n const neighbors = await Promise.all( //wait for all promises to resolve to return a single promise\n codes.map(async code => { // needs to be async as we make a call to get the country for each code\n let country = this.countries.find(\n country => country.alpha3Code === code\n );\n // if we already have stored the country, no need to make a call to be API\n if (country?.name) {\n return `<li class=\"list-group-item\"><a href=\"#${country.alpha3Code}\">${country.name}</a></li>`;\n }\n const response = await fetch(\n `https://restcountries.eu/rest/v2/alpha/${code}`\n );\n country = await response.json();\n console.log(code, country);\n return `<li class=\"list-group-item\"><a href=\"#${country.alpha3Code}\">${country.name}</a></li>`;\n })\n );\n return neighbors;\n }", "getNeighbors(){\n\n var offSetDir = [\n [[-1,-1], [-1, 0], [0,1], [1, 0], [1,-1], [0, -1]],\n [[-1, 0], [-1, 1], [0,1], [1,1], [1, 0], [0, -1]]\n ]\n var parity = this.index.row % 2;\n var neighbors = []\n for(var i = 0; i<6; i++){\n var assocNeighbor = {row: this.index.row + offSetDir[parity][i][0], col: this.index.col + offSetDir[parity][i][1]}\n if(assocNeighbor.row>=0 && assocNeighbor.row < this.board.numRows){\n if(assocNeighbor.col>=0 && assocNeighbor.col< this.board.numColumns){\n if(this.board.getHex(assocNeighbor.row, assocNeighbor.col)!=undefined && this.board.getHex(assocNeighbor.row, assocNeighbor.col).identifier.name== this.identifier.name){\n neighbors.push(this.board.getHex(assocNeighbor.row, assocNeighbor.col));\n\n }\n }\n }\n }\n return neighbors;\n }", "function getNeighborSet(cell_idx) {\n\n // reset return array\n var nset = [];\n\n if (!result.cells.hasOwnProperty(cell_idx) || result.cells[cell_idx] == undefined)\n {\n LOG.debug(\"No cell with that ID: \" + cell_idx);\n return nset;\n }\n\n //LOG.debug('getNeighborSet cell_idx: ' + cell_idx + ' cell size: ' + result.cells.length);\n\n // check if index range is sensible\n if (cell_idx >= 0 && cell_idx < result.cells.length && result.cells[cell_idx].site != undefined) {\n\n var cell_id = result.cells[cell_idx].site.id;\n var halfedges = result.cells[cell_idx].halfedges;\n\n //LOG.debug(result.cells);\n\n //LOG.debug('halfedge count: ' + halfedges.length);\n\n // go through each halfedge & check for edge's sites on two ends\n for (var i=0; i < halfedges.length; i++) {\n\n var edge = halfedges[i].edge;\n /*\n LOG.debug('edge ' + i + ' site_id: ' + halfedges[i].site.id + ' va (' + edge.va.x + ', ' + edge.va.y + ') vb (' + edge.vb.x + ', ' + edge.vb.y + ')');\n LOG.debug('lSite: ' + edge.lSite + ' id: ' + (edge.lSite !== null ? edge.lSite.id : 'null'));\n LOG.debug('rSite: ' + edge.rSite + ' id: ' + (edge.rSite !== null ? edge.rSite.id : 'null'));\n */\n // take the bisector's site from the other side of current given index\n //var id = (edge.bisectingID[0] == index ? edge.bisectingID[1] : edge.bisectingID[0]);\n\n var site = (edge.lSite.id === cell_id ? edge.rSite : edge.lSite);\n //LOG.debug('lSite.id: ' + edge.lSite.id + ' cell_id: ' + cell_id + ' site: ' + site);\n\n if (site !== null)\n nset.push(site.id);\n }\n }\n\n return nset;\n }", "function get_neighbours(x,y,visited){\n var neighbours=[];\n var index=((y-1)*no_columns)+(x-1);\n visited[x+','+y]=true;\n //top neighbour\n if(y-1>0 && !grids[index-no_columns].classList.contains('obstacle') && visited[x+','+(y-1)]===undefined){\n neighbours.push([x,(y-1)]);\n visited[x+','+(y-1)]=true;\n };\n //right neighbour\n if(x+1<=no_columns && !grids[index+1].classList.contains('obstacle') && visited[(x+1)+','+y]===undefined){\n neighbours.push([(x+1),y]);\n visited[(x+1)+','+y]=true;\n };\n //bottom neighbour\n if(y+1<=no_rows && !grids[index+no_columns].classList.contains('obstacle') && visited[x+','+(y+1)]===undefined){\n neighbours.push([x,(y+1)]);\n visited[x+','+(y+1)]=true;\n };\n //left neighbour\n if(x-1>0 && !grids[index-1].classList.contains('obstacle') && visited[(x-1)+','+y]===undefined){\n neighbours.push([(x-1),y]);\n visited[(x-1)+','+y]=true;\n };\n return neighbours;\n }", "getNeighbors(i, j, rows, cols) {\n let neighbors = [];\n if (i > 1) { \n neighbors.push([i - 1, j]); \n }\n if (i < rows - 1) { \n neighbors.push([i + 1, j]); \n }\n if (j > 1){ \n neighbors.push([i, j - 1]); \n }\n if (j < cols - 1) { \n neighbors.push([i, j + 1]); \n }\n return neighbors;\n }", "getNeighbors() {\n // tslint:disable-next-line:no-unsafe-any\n return tiled_1.BaseTile.prototype.getNeighbors.call(this);\n }", "neighborhood() {\n return store.neighborhoods.find(\n function(neighborhood) {\n return neighborhood.id === this.neighborhoodId\n }.bind(this)\n )\n }", "findNeighbors(i, j) {\n this.Neighbors.enumerate().forEach(neighbor => {\n let yOffset;\n let xOffset;\n let piece = this.pieces[i][j];\n let point = new Point(piece.point.x + this.Neighbors[neighbor].x, piece.point.y + this.Neighbors[neighbor].y);\n let check = this.hashmap.getPointFromMap(point, this.pieces);\n if (check !== null) {\n this.pieces[i][j].neighbors.push(\n () => this.hashmap.getPointFromMap(point, this.pieces)\n //check\n );\n }\n });\n }", "function getNeighbors() {\n\tvar neighbors = [];\n\tfor (var i = 0; i < squares.length; i++) {\n\t\tif (squares[i].canMove()) neighbors.push(squares[i]);\n\t}\n\treturn neighbors;\n}", "function fetchPositions() {\n console.log('Querying Critical Maps Api');\n\n get(config.criticalmaps.baseUrl, processResult);\n}", "static fetchRestaurantByNeighborhood(neighborhood) {\n return new Promise((resolve, reject) => {\n // Fetch all restaurants\n DBHelper.getRestaurants().then(restaurants => {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n resolve(results);\n }).catch(error => {\n reject(error);\n });\n });\n }", "neighbours(){\n var neighbours = []\n neighbours.push(this.neighbour(0,1))\n //neighbours.push(this.neighbour(1,1))\n neighbours.push(this.neighbour(1,0))\n //neighbours.push(this.neighbour(1,-1))\n neighbours.push(this.neighbour(0,-1))\n //neighbours.push(this.neighbour(-1,-1))\n neighbours.push(this.neighbour(-1,0))\n //neighbours.push(this.neighbour(-1,1))\n return neighbours\n }", "function getAllBoardstates()\n {\n ajaxHelper(boardsUri,'GET').done(function(data)\n {\n self.boards(data);\n });\n }", "showNeighbours(){\n\n var currentLevel = levels[gameState.level]; // chosen difficulty level\n \n // iterate over all immediate neighbours\n for(var j = this.y - 1; j <= this.y + 1; j++){ // iterate over all cols\n for(var i = this.x - 1; i <= this.x + 1; i++){ // iterate over all rows\n \n if( i == this.x && j == this.y ) // cell whose neighbours to be checked\n continue;\n \n if( i < 0 || j < 0 || i >= currentLevel.numCols || j >= currentLevel.numRows ) // boundary condition\n continue;\n \n var idx = ((j * currentLevel.numCols) + i); // current neighbour cell idx \n if( grid[idx].currentState == 'hidden' ){\n\n grid[idx].currentState = 'visible'; // update current state\n if(grid[idx].numMines == 0)\n grid[idx].showNeighbours(); // recursive call\n\n }\n }\n }\n }", "function getNeighbors(tile){\r\n var indexofTile=tile.index(); //get the index of the cell on the grid\r\n var neighbors=[]; \r\n checknextNeigbor(tile); //call the function to check if there is next neighbor and push it in the array \r\n checkpreviousNeigbor(tile); //call the function to check if there is previous neighbor and push it in the array \r\n //check if cell has up neighbor\r\n if(tile.parent().prev().children().eq(indexofTile).length) { \r\n var upTile=tile.parent().prev().children().eq(indexofTile);\r\n neighbors.push(upTile);\r\n checknextNeigbor(upTile);\r\n checkpreviousNeigbor(upTile);\r\n }\r\n //check if cell has down neighbor\r\n if(tile.parent().next().children().eq(indexofTile).length){\r\n var downTile=tile.parent().next().children().eq(indexofTile);\r\n neighbors.push(downTile);\r\n checknextNeigbor(downTile);\r\n checkpreviousNeigbor(downTile);\r\n \r\n }\r\n function checknextNeigbor(cell){ //the function to check if there is next neighbor and push it in the array \r\n if(cell.next().length){ //check if cell has next neighbor\r\n neighbors.push(cell.next()); \r\n }}\r\n function checkpreviousNeigbor(cell){ //the function to check if there is previous neighbor and push it in the array \r\n if(cell.prev().length){ //check if cell has next neighbor\r\n neighbors.push(cell.prev()); \r\n }}\r\n return neighbors; //return neighbors of certain cell\r\n}", "getNeighbors(currentCell) {\n var neighbors = [];\n\n // add logic to get neighbors and add them to the array\n for (var xOffset = -1; xOffset <= 1; xOffset++) {\n for (var yOffset = -1; yOffset <= 1; yOffset++) {\n var neighborColumn = currentCell.column + xOffset;\n var neighborRow = currentCell.row + yOffset;\n\n // do something with neighborColumn and neighborRow\n /* Step 9\n - updated it with isValidPosition\n - Checks to prevent the cell that is the currentCell to be added to the array\n */\n if(this.isValidPosition(neighborColumn, neighborRow)){\n var neighborCell = this.cells[neighborColumn][neighborRow];\n \n if(neighborCell != currentCell){\n neighbors.push(neighborCell);\n }\n }\n }\n}\n\n return neighbors;\n}", "function neighbours(x, y, width, height) {\n var neighbourList = [];\n var right = cell(x + 1, y, width, height);\n var bottom = cell(x, y + 1, width, height);\n if (right !== null) neighbourList.push(right);\n if (bottom !== null) neighbourList.push(bottom);\n return neighbourList;\n}", "async function getNasaPictures() {\n try {\n const response = await fetch(apiUrl)\n resultsArray = await response.json()\n console.log(resultsArray)\n updateDOM()\n } catch (error) {\n // Catch Error Here\n }\n}", "function FindIslands(event){\n clearGridSaveWall()\n resetVisit()\n var islandNum = 0\n\n for(var i = 0; i < GRID_ROW_SIZE; i++){\n for(var j = 0; j < GRID_COL_SIZE; j++){\n \n // already visited, continue\n if(Grid[i][j].VisitedAt != -1){\n continue\n }\n // not part of an island, continue;\n if(Grid[i][j].State != \"Wall\"){\n continue\n }\n // unvisited island found, explore and count\n else{\n islandNum ++\n IslandExplorer(i,j)\n }\n\n }\n }\n \n console.log(islandNum);\n}", "fetchRestaurantByNeighborhood(neighborhood) {\n // Fetch all restaurants\n return this.fetchRestaurants().then(restaurants => restaurants.filter(restaurant => restaurant.neighborhood === neighborhood));\n }", "neighbours(i) {\r\n // This doesn't even do anything in particular. I don't know why this works.\r\n let cell = [this.boids[i].cell[0] - 1, this.boids[i].cell[1] - 1];\r\n \r\n let n = [];\r\n \r\n // Using r, c here as i is already being used.\r\n // If r and c are changed to different numbers, there are different behaviours. I don't know how this works...\r\n for (let r = 0; r < 3; r++) {\r\n for (let c = 0; c < 3; c++) {\r\n let append = this.grid.cells[int((this.grid.rows + cell[0] + r) % this.grid.rows)][int((this.grid.cols + cell[1] + c) % this.grid.cols)]\r\n \r\n n = n.concat(append);\r\n }\r\n }\r\n \r\n return n;\r\n }", "get unflaggedNeighbours() {\n return this.allNeighbours.filter((n) => !n.isDug && !n.hasFlag);\n }", "static getNeighbours(isTop, isBottom, isLeft, isRight) {\n let neighbours = [[-1, -1], [-1, 0],[-1, 1],[0, -1],[0, 1],[1, -1], [1, 0],[1, 1]];\n // [ -1,-1 -1, 0 -1, 1 ]\n // neighbours [ 0, -1 0, 1 ]\n // [ 1, -1 1, 0 1, 1 ]\n\n\n //IF is top row, removes neightbours above\n if(isTop) {\n neighbours = neighbours.filter(function (e) {\n return e[0] !== -1\n })\n }\n\n if(isBottom){\n neighbours = neighbours.filter(function (e) {\n return e[0] !== 1\n })\n }\n\n if(isLeft){\n neighbours = neighbours.filter(function (e) {\n return e[1] !== -1\n })\n }\n\n if(isRight){\n neighbours = neighbours.filter(function (e) {\n return e[1] !== 1\n })\n }\n return neighbours;\n }", "function getWheelMapNodes(bounds) {\n\tconst params = {\n\t\tapi_key: apiKey,\n\t\tbbox: bounds,\n\t\tper_page: 1000,\n\t}\n\tconst options = {\n\t\tmode: 'no-cors'\n\t}\n\tconst queryString = formatQuery(params)\n\tconst url = `${searchURL}?${queryString}`\n\tfetch(url, options)\n\t\t.then(response => {\n\t\t\tconsole.log(response);\n\t\t})\n\t\t.catch(err => {\n\t\t\tconsole.log(err)\n\t\t});\n}", "function fetchDescriptions(neighborhoodData) {\n // using async.parallel to retrieve data from all neighborhoods at once\n async.concat(neighborhoodData, getNeighborhoodDescription, function(err, results) {\n // here are the neighborhoods with descrptions. Let's print them out\n results.forEach(function(result) {\n db.area.create({\n name: result.name,\n description: result.description\n });\n console.log(result.name);\n console.log(result.description);\n console.log('----------------');\n });\n });\n}", "getNeighbors() {\n let neighbors = [];\n switch(growthPattern){\n case GROWPATTERN.diamond: \n for (let i = -1; i < 2; i++) {\n for (let j = -1; j < 2; j++) {\n let nearX = i+this.xIndex;\n let nearY = j+this.yIndex;\n if (nearX > -1 && nearX < cols && \n nearY > -1 && nearY < rows && abs(i)!=abs(j)) {\n neighbors.push(this.board.grid[nearX][nearY]);\n }\n }\n }\n break;\n default:\n print(\"Error in neighbors\");\n }\n return neighbors;\n }", "function getAllImages() {\n printLog('Requiring all images the user solved from the server.');\n IMAGES = [];\n // IMAGES_ON_CLIENT = 0;\n send(json_get_all_images_message());\n}", "function getNeighbors( i, j )\n{\n var neighbors = [];\n //top, bottom, left, right\n var limit = 4;\n //top, bottom, left, right, top-left, top-right, bottom-left, bottom-right\n if( diagnolSelected )\n limit=8;\n \n for( var k = 0; k < limit; k++ )\n {\n var newRow = i + dirX[k];\n var newCol = j + dirY[k];\n //If neighbour exists, add it into the neighbours list\n if( newRow >= 0 && newRow < totalRows && newCol >= 0 && newCol < totalCols)\n neighbors.push( [newRow, newCol] );\n }\n \n return neighbors;\n}", "fetchRestaurantByNeighborhood(neighborhood) {\n return this._fetchRestaurantsByIndex('neighborhood', neighborhood);\n }", "fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n this.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given neighborhood\r\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\r\n if (callback) {\r\n callback(null, results);\r\n }\r\n }\r\n });\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\r\n // Fetch all restaurants\r\n DBHelper.openDatabase().then(db => {\r\n let tx = db.transaction('restaurants');\r\n let store = tx.objectStore('restaurants').index('neighborhood');\r\n return store.get(neighborhood);\r\n }).then(result => {\r\n callback(null,result);\r\n }).catch((e) => {\r\n callback(e,null)\r\n });\r\n }", "generateNeighbours(grid) {\r\n //Right neighbour\r\n if (this.x < cols - 1) {\r\n this.neighbours.push(grid[this.x + 1][this.y]);\r\n }\r\n //Left neighbour\r\n if (this.x > 0) {\r\n this.neighbours.push(grid[this.x - 1][this.y]);\r\n }\r\n //Bottom neighbour\r\n if (this.y < rows - 1) {\r\n this.neighbours.push(grid[this.x][this.y + 1]);\r\n }\r\n //Top neighbour\r\n if (this.y > 0) {\r\n this.neighbours.push(grid[this.x][this.y - 1]);\r\n }\r\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n this.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByNeighborhood(neighborhood, callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given neighborhood\n const results = restaurants.filter(r => r.neighborhood == neighborhood);\n callback(null, results);\n }\n });\n }", "getUnvisitedNeighbors(neighbor = null) {\n const directions = neighbor === null ? this.graph[this.currentRoom] : this.graph[neighbor]\n\n const unvisited = []\n for (let i in directions) {\n if (directions[i] === null && !this.visited.has(directions[i])) {\n unvisited.push(i)\n }\n }\n return unvisited\n }" ]
[ "0.7945284", "0.7055915", "0.69890165", "0.69833696", "0.69833696", "0.6965614", "0.6949113", "0.6919723", "0.69066477", "0.69066477", "0.69066477", "0.69066477", "0.69066477", "0.69066477", "0.69066477", "0.6904565", "0.68913037", "0.6867803", "0.6862686", "0.6862686", "0.68614167", "0.6859225", "0.6859225", "0.6793957", "0.6745219", "0.6674985", "0.66478777", "0.6624392", "0.65469086", "0.64410573", "0.622998", "0.61120427", "0.60567003", "0.6034851", "0.58053976", "0.578758", "0.57617193", "0.55978775", "0.55703557", "0.5567925", "0.5526554", "0.5484207", "0.54742116", "0.5442731", "0.54373443", "0.5430532", "0.5405466", "0.5376291", "0.53528655", "0.5349622", "0.53212047", "0.5307419", "0.52968395", "0.52870256", "0.5284194", "0.5258125", "0.52486575", "0.52475715", "0.52433294", "0.5238815", "0.5228102", "0.5222058", "0.522181", "0.51978034", "0.5179492", "0.5159625", "0.51473534", "0.5146907", "0.5146394", "0.51374555", "0.5129026", "0.51235694", "0.512091", "0.51130825", "0.50992036", "0.50977314", "0.5096234", "0.5096234", "0.5096234", "0.5096234", "0.5096234", "0.5096234", "0.5096234", "0.5096234", "0.5096234", "0.5096092" ]
0.68441343
37
Fetch all cuisines with proper error handling.
static fetchCuisines(callback) { // Fetch all restaurants DBHelper.fetchRestaurants((error, restaurants) => { if (error) { callback(error, null); } else { // Get all cuisines from all restaurants const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type) // Remove duplicates from cuisines const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i) callback(null, uniqueCuisines); } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function fetchCuisines() {\n DBHelper.fetchCuisines((error, cuisines) => { // eslint-disable-line no-undef\n if (error) { // Got an error!\n console.error(error);\n } else {\n main.cuisines = cuisines;\n IndexDBHelper.storeCuisines(cuisines); // eslint-disable-line no-undef\n resetCuisines();\n fillCuisinesHTML();\n }\n });\n}", "static fetchCuisines () {\r\n return fetch(`${DBHelper.DATABASE_URL}/cuisines`).then(res => {\r\n return res.json().then(json => {\r\n return idb.cacheCollection('cuisines', json.cuisines).then(() => json.cuisines);\r\n });\r\n });\r\n }", "static fetchCuisines(callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\t// Get all cuisines from all restaurants\n\t\t\t\tconst cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type);\n\t\t\t\t// Remove duplicates from cuisines\n\t\t\t\tconst uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i);\n\t\t\t\tcallback(null, uniqueCuisines);\n\t\t\t}\n\t\t});\n\t}", "static fetchCuisines(callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\t// Get all cuisines from all restaurants\n\t\t\t\tconst cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type);\n\t\t\t\t// Remove duplicates from cuisines\n\t\t\t\tconst uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i);\n\t\t\t\tcallback(null, uniqueCuisines);\n\t\t\t}\n\t\t});\n\t}", "static fetchCuisines(callback) {\n\t\t// Fetch all restaurants\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\t// Get all cuisines from all restaurants\n\t\t\t\tconst cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type);\n\t\t\t\t// Remove duplicates from cuisines\n\t\t\t\tconst uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) === i);\n\t\t\t\tcallback(null, uniqueCuisines);\n\t\t\t}\n\t\t});\n\t}", "static fetchCuisines(cb) {\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n cb(error, null);\n } else {\n // Get all cuisines from all restaurants\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)\n // Remove duplicates from cuisines\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)\n cb(null, uniqueCuisines);\n }\n });\n }", "static fetchCuisines (callback) {\r\n return DBHelper.fetchRestaurants()\r\n .then(restaurants => {\r\n // Get all cuisines from all restaurants\r\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)\r\n // Remove duplicates from cuisines\r\n return cuisines.filter((v, i) => cuisines.indexOf(v) == i)\r\n })\r\n }", "static fetchCuisines(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all cuisines from all restaurants\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type);\n // Remove duplicates from cuisines\n const uniqueCuisines = cuisines.filter(\n (v, i) => cuisines.indexOf(v) == i\n );\n callback(null, uniqueCuisines);\n }\n });\n }", "static fetchCuisines(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all cuisines from all restaurants\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)\n // Remove duplicates from cuisines\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)\n callback(null, uniqueCuisines);\n }\n });\n }", "static fetchCuisines(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all cuisines from all restaurants\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)\n // Remove duplicates from cuisines\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)\n callback(null, uniqueCuisines);\n }\n });\n }", "static fetchCuisines(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all cuisines from all restaurants\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)\n // Remove duplicates from cuisines\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)\n callback(null, uniqueCuisines);\n }\n });\n }", "static fetchCuisines(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all cuisines from all restaurants\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)\n // Remove duplicates from cuisines\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)\n callback(null, uniqueCuisines);\n }\n });\n }", "static fetchCuisines(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all cuisines from all restaurants\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)\n // Remove duplicates from cuisines\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)\n callback(null, uniqueCuisines);\n }\n });\n }", "static fetchCuisines(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all cuisines from all restaurants\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)\n // Remove duplicates from cuisines\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)\n callback(null, uniqueCuisines);\n }\n });\n }", "static fetchCuisines(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all cuisines from all restaurants\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)\n // Remove duplicates from cuisines\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)\n callback(null, uniqueCuisines);\n }\n });\n }", "static fetchCuisines(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all cuisines from all restaurants\r\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type);\r\n // Remove duplicates from cuisines\r\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) === i);\r\n callback(null, uniqueCuisines);\r\n }\r\n });\r\n }", "static fetchCuisines(callback) {\r\n\t\t// Fetch all restaurants\r\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\r\n\t\t\tif (error) {\r\n\t\t\t\tcallback(error, null);\r\n\t\t\t} else {\r\n\t\t\t\t// Get all cuisines from all restaurants\r\n\t\t\t\tconst cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type);\r\n\t\t\t\t// Remove duplicates from cuisines\r\n\t\t\t\tconst uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i);\r\n\t\t\t\tcallback(null, uniqueCuisines);\r\n\t\t\t}\r\n\t\t});\r\n\t}", "static fetchCuisines(callback) {\r\n\t\t// Fetch all restaurants\r\n\t\tDBHelper.fetchRestaurants((error, restaurants) => {\r\n\t\t\tif (error) {\r\n\t\t\t\tcallback(error, null);\r\n\t\t\t} else {\r\n\t\t\t\t// Get all cuisines from all restaurants\r\n\t\t\t\tconst cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type);\r\n\t\t\t\t// Remove duplicates from cuisines\r\n\t\t\t\tconst uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i);\r\n\t\t\t\tcallback(null, uniqueCuisines);\r\n\t\t\t}\r\n\t\t});\r\n\t}", "static fetchCuisines(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all cuisines from all restaurants\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)\n // Remove duplicates from cuisines\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)\n callback(null, uniqueCuisines);\n }\n });\n }", "static fetchCuisines(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all cuisines from all restaurants\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)\n // Remove duplicates from cuisines\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)\n callback(null, uniqueCuisines);\n }\n });\n }", "static fetchCuisines(callback) {\n // Fetch all restaurants\n this.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all cuisines from all restaurants\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)\n // Remove duplicates from cuisines\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)\n callback(null, uniqueCuisines);\n }\n });\n }", "static fetchCuisines(callback) {\n // Fetch all restaurants\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Get all cuisines from all restaurants\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type); // Remove duplicates from cuisines\n\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i);\n callback(null, uniqueCuisines);\n }\n });\n }", "static fetchCuisines(callback) {\r\n // Fetch all restaurants.\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all cuisines from all restaurants.\r\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)\r\n // Remove duplicates from cuisines.\r\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)\r\n callback(null, uniqueCuisines);\r\n }\r\n });\r\n }", "static fetchCuisines(callback) {\r\n // Fetch all restaurants\r\n DBHelper.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Get all cuisines from all restaurants\r\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)\r\n // Remove duplicates from cuisines\r\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)\r\n callback(null, uniqueCuisines);\r\n }\r\n });\r\n }", "static fetchCuisines() {\r\n return fetch(DBHelper.DATABASE_URL)\r\n .then( response => {\r\n if (response.ok){\r\n return response.json()\r\n .then(res => {\r\n // Get all cuisines from all restaurants\r\n const cuisines = res.map((v, i) => res[i].cuisine_type)\r\n // Remove duplicates from cuisines\r\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)\r\n return uniqueCuisines;\r\n });\r\n }\r\n }).catch(function(err){\r\n console.log('Fetch error', err);\r\n });\r\n }", "static fetchCuisines(callback) {\r\n // Fetch all restaurants\r\n DBHelper.getRestaurants().then(result => {\r\n const cuisines = result.map((v, i) => result[i].cuisine_type)\r\n callback(null,cuisines.filter((v, i) => cuisines.indexOf(v) == i));\r\n })\r\n }", "fetchCuisines(callback) {\r\n\t\twindow.idb.openDb().then(() => {\r\n\t\t\twindow.idb.getAll().then((restaurants) => {\r\n\t\t\t\t// Get all cuisines from all restaurants\r\n\t\t\t\tconst cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type);\r\n\t\t\t\t// Remove duplicates from cuisines\r\n\t\t\t\tconst uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i);\r\n\t\t\t\tcallback(null, uniqueCuisines);\r\n\t\t\t});\r\n\t\t}).catch((error) => {\r\n\t\t\tcallback(error, null);\r\n\t\t});\r\n\t}", "static fetchCuisines() {\n return new Promise((resolve, reject) => {\n // Fetch all restaurants\n DBHelper.getRestaurants().then(restaurants => {\n // Get all cuisines from all restaurants\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type);\n // Remove duplicates from cuisines\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i);\n resolve(uniqueCuisines);\n }).catch(error => {\n reject(error);\n });\n });\n }", "fetchCuisines() {\n // Fetch all restaurants\n return this.fetchRestaurants().then(restaurants => {\n // Get all cuisines from all restaurants\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type);\n // Remove duplicates from cuisines\n return cuisines.filter((v, i) => cuisines.indexOf(v) === i);\n });\n }", "static fetchCuisines() {\n return DBHelper.fetchRestaurantsPromise()\n .then(restaurants => {\n // Get all cuisines from all restaurants\n const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type);\n // Remove duplicates from cuisines\n const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i);\n return uniqueCuisines;\n }).catch(console.log);\n }", "fetchCuisines() {\n return this._getIndexRange('cuisine');\n }", "static fetchCuisines(restaurants, callback) {\r\n return callback(...DBHelper._getCategories(restaurants, 'cuisine_type'));\r\n }", "static getCuisines(idbPromise, callback) {\n return idbPromise.then(db => {\n if (!db) return;\n\n return db.transaction('cuisine')\n .objectStore('cuisine')\n .getAll()\n .then(cuisines => callback(cuisines));\n });\n }", "fetchRestaurantByCuisine(cuisine) {\n // Fetch all restaurants with proper error handling\n return this.fetchRestaurants().then(restaurants => restaurants.filter(restaurant => restaurant.cuisine_type === cuisine));\n }", "async function getCatagories(){\n //Gets an array of Catagories and returns it if error occurs it returns and empty array\n try {\n const response = await fetch(`/api/places/catagories`);\n if (response.ok)\n return response.json();\n return [];\n }\n catch (err) {\n console.log(err);\n return [];\n }\n}", "async function fetch_all_clients() {\n const log = debug.extend('fetch_all_clients')\n log('Fetching all clients')\n const clients = (await (await collection.find({})).toArray()).map(fix_id)\n log('Fetched\\n%O', clients)\n return clients\n }", "async function fetchAllCenturies() \n {\n if (localStorage.getItem('centuries')) \n {\n return JSON.parse(localStorage.getItem('centuries'));\n }\n\n try \n {\n const response = await fetch(`${ API.BASE_URL }/${ API.RESOURCES.CENTURY }?${ API.KEY }&size=100&sort=temporalorder`);\n\n // Now, you need to store them. Where can we do that? Right before we return them after successful fetch. \n // Add a line to set the centuries item in localstorage after you get the records, but before returning them.\n let { info, records } = await response.json();\n localStorage.setItem('centuries', JSON.stringify(records));\n \n return records;\n } \n catch (error) \n {\n console.error(error);\n }\n }", "async fetchAll() {\n try {\n // Make the request\n const response = await axios.get(\n `${this.DB_READ_URL}/${this.DB_DEFAULTS_CONFIG.plugin_id}/${this.DB_DEFAULTS_CONFIG.collection_name}/${this.DB_DEFAULTS_CONFIG.organization_id}`,\n );\n\n if (response.data.data == null) {\n return { data: [] };\n }\n\n // Return the response\n return response.data;\n } catch (error) {\n if (\n error.response.data.status === 404\n && error.response.data.message === 'collection not found'\n ) {\n return { data: [] };\n }\n\n throw new CustomError(`Unable to Connect to Zuri Core DB [READ ALL]: ${error}`, '500');\n }\n }", "static fetchAll(cb) {\n getProductsFromFile(cb);\n }", "function fetchCountries(){\n console.log('IMonData: [Countries] Fetching data..');\n var store = new Store();\n var futures = [];\n var baseUrl = 'https://thenetmonitor.org/v2/countries';\n\n var fut = HTTP.get.future()(baseUrl, { timeout: Settings.timeout*3 });\n futures.push(fut);\n var results = fut.wait();\n store.sync(results.data);\n _.each(results.data.data, function(d){\n store.sync(d.relationships.data_points);\n });\n\n console.log('IMonData: [Countries] Data fetched.');\n Future.wait(futures);\n\n var insert = function(){\n console.log('IMonData: [Countries] Inserting...');\n _.each(store.findAll('countries'), insertCountryData);\n console.log('IMonData: [Countries] Inserted.');\n };\n\n Future.task(insert);\n\n}", "static fetchAll(cb) {\n getProductsFromFile(cb);\n }", "function getCuentas(callback) {\n\tvar criterio = {$or: [\n \t {$and: [\n\t \t{'datosMonitoreo' : {$exists : true}},\n \t\t{'datosMonitoreo' : {$ne : ''}},\n \t\t{'datosMonitoreo.id' : {$ne : ''}}\n \t ]},\n \t {$and: [\n \t\t{'datosPage' : {$exists : true}},\n\t\t{'datosPage': {$ne : ''}},\n\t\t{'datosPage.id' : {$ne : ''}}\n \t ]}\n \t]};\n\tvar elsort = { nombreSistema : 1 };\n \tclassdb.buscarToStream('accounts', criterio, elsort, 'solicitudes/getoc/getCuentas', function(cuentas){\n\t if (cuentas === 'error') {\n\t\treturn callback(cuentas);\n\t }\n\t else {\n\t\trefinaCuentas(cuentas, 0, [], function(refinadas){\n\t\t return callback(refinadas);\n\t\t});\n\t }\n\t});\n }", "static fetchAll(cb) {\n getProductsFile(cb);\n }", "function iterate() {\n cursor.read(1000, (err, rows) => {\n if (err) return cb(err);\n\n if (!rows.length) {\n done();\n return cb();\n }\n\n for (let row of rows) {\n if (turf.lineDistance(row.geom) < 0.001) continue;\n\n row.name = row.name.filter(name => {\n if (!name.display) return false;\n return true;\n });\n\n if (!row.name.length) continue;\n\n let feat = {\n type: 'Feature',\n properties: {\n 'carmen:text': row.name,\n 'carmen:rangetype': 'tiger',\n 'carmen:parityl': [[]],\n 'carmen:parityr': [[]],\n 'carmen:lfromhn': [[]],\n 'carmen:rfromhn': [[]],\n 'carmen:ltohn': [[]],\n 'carmen:rtohn': [[]]\n },\n geometry: {\n type: 'GeometryCollection',\n geometries: [\n row.geom\n ]\n }\n };\n\n if (self.opts.country) feat.properties['carmen:geocoder_stack'] = self.opts.country;\n\n feat = self.post.feat(feat);\n if (feat) self.output.write(JSON.stringify(feat) + '\\n');\n }\n\n return iterate();\n });\n }", "function getAllChemicalCategory() {\r\n return get('/chemicalcategory/getall').then(function (res) {\r\n return res.data;\r\n }).catch(function (err) {\r\n return err.response.data;\r\n });\r\n}", "function iterate() {\n cursor.read(1000, (err, rows) => {\n if (err) return cb(err);\n\n if (!rows.length) {\n done();\n return cb();\n }\n\n rows.forEach((row) => {\n if (!row.name.some(name => { return name.display.trim().length })) return;\n\n let feat = {\n type: 'Feature',\n properties: {\n 'carmen:text': row.name,\n 'carmen:addressnumber': []\n },\n geometry: {\n type: 'GeometryCollection',\n geometries: [{\n type: 'MultiPoint',\n coordinates: []\n }]\n }\n };\n\n const units = new Units();\n\n row.geom.coordinates.forEach((coord) => {\n let num = units.decode(coord.pop());\n\n if (!num || !num.output) return;\n\n feat.properties['carmen:addressnumber'].push(num.num);\n feat.geometry.geometries[0].coordinates.push(coord);\n });\n\n if (feat.geometry.geometries[0].coordinates.length) {\n feat.properties['carmen:addressnumber'] = [ feat.properties['carmen:addressnumber'] ];\n\n if (self.opts.country) feat.properties['carmen:geocoder_stack'] = self.opts.country;\n feat = self.post.feat(feat);\n\n if (feat) self.output.write(JSON.stringify(feat) + '\\n');\n }\n });\n\n return iterate();\n });\n }", "static fetchRestaurants(cb) {\n fetchRestaurantsCounts++;\n console.log('fetchRestaurants() called', fetchRestaurantsCounts, 'times!!!');\n DBHelper.getCachedRestaurants().then(data => {\n if (data.length > 0) {\n return cb(null, data);\n }\n fetch(RESTAURANTS_URL, {credentials:'same-origin'}).then(response => {\n return response.json()\n }).then(data => {\n dbPromise.then(db => {\n if (!db) return;\n console.log('data fetched:', data);\n const index = db.transaction('restaurants', 'readwrite').objectStore('restaurants');\n data.forEach(restaurant => index.put(restaurant));\n });\n return cb(null, data);\n }).catch(error => cb(error, null));\n });\n }", "async function getClinicFromApi() {\n\n const clinics = [];\n const urls = config.clinicUrls.split(',');\n\n for(const url of urls){\n const cl = await axios.get(url);\n for(const c of cl.data){\n clinics.push(c);\n }\n }\n return clinics;\n}", "async function getCourses() {\n return await microcredapi.get(`/unit/${window.localStorage.getItem('userId')}`).then(response => {\n setCourses(response.data.units);\n })\n }", "async function continetAnalize(countries) {\n\n let continentData = [];\n for (const [key, value] of Object.entries(countries)) {\n let continent = {};\n continent.name = key;\n continent.cases = 0;\n continent.death = 0;\n continent.recovered = 0;\n continent.critical = 0;\n continent.countries = [];\n\n for (ele of value) {\n if (ele[1] != \"XK\") {\n let src = `https://corona-api.com/countries/${ele[1]}`;\n const getdata = await fetch(src);\n let allData = await getdata.json();\n\n let cases = allData.data.latest_data.confirmed;\n let death = allData.data.latest_data.deaths;\n let recovered = allData.data.latest_data.recovered;\n let critical = allData.data.latest_data.critical;\n\n let country = {};\n country.name = `${ele[0]}`;\n country.cases = cases;\n country.death = death;\n country.recovered = recovered;\n country.critical = critical;\n\n continent.countries.push(country);\n\n continent.cases += cases;\n continent.death += death;\n continent.recovered += recovered;\n continent.critical += critical;\n\n }\n }\n continentData.push(continent);\n }\n console.log(`finished!`);\n return continentData;\n}", "async fetch () {\n\t\tif (this.notFound.length === 0) {\n\t\t\treturn;\t// got 'em all from the cache ... yeehaw\n\t\t}\n\t\telse if (this.notFound.length === 1) {\n\t\t\t// single ID fetch is more efficient\n\t\t\treturn await this.fetchOne();\n\t\t}\n\t\telse {\n\t\t\treturn await this.fetchMany();\n\t\t}\n\t}", "function loadCourses() {\n var limit = 100;\n var skip = 0;\n var popOut = false;\n\n request(\"https://cobalt.qas.im/api/1.0/courses\" + cobalt + \"&limit=10\", function(err, resp, body) {\n if (err) {\n return console.log(\"Failed to connect, falling back to previous data.\");\n }\n\n if (resp.statusCode != 200) {\n return console.log(\"Did not get proper error code, falling back to previous data.\");\n }\n });\n\n // Need to implement a check if a connection can be successfully established, we drop the coursesData relation\n // Otherwise stop, dont process anything and just use pre-existing data.\n CourseData.remove({}, function(err) {\n if (err) {\n console.log(\"Failed to remove courses.\");\n return true;\n } else {\n console.log(\"Successfully removed courses.\");\n }\n });\n\n\n while (popOut == false || skip < 7000) {\n\n var searchUri = \"https://cobalt.qas.im/api/1.0/courses?key=\" + cobalt + \"&limit=\" + limit + \"&skip=\" + skip;\n console.log(searchUri);\n\n popOut = request(searchUri, function(err, resp, body) {\n if (err) {\n console.log(\"Error connecting to Cobalt, falling back to pre-existing data.\");\n return true;\n }\n\n if (resp.statusCode != 200) {\n console.log(\"Cobalt API returned a different status code than expected: \" + resp.statusCode);\n return true;\n }\n\n if (body == null) {\n console.log(\"Empty body\");\n } else {\n var courseInfo = JSON.parse(body);\n console.log(\"Attempting to insert...\");\n\n CourseData.insertMany(courseInfo, function(err, docs) {\n if (err) {\n console.log(\"Failed to add set into database.\");\n } else {\n console.log(docs.length + \" courses were successfully inserted into the database.\");\n }\n });\n }\n });\n skip += 100;\n }\n}", "async function all() {\n const user = 123\n const userRequest = await fetch(`https://catappapi.herokuapp.com/users/${user}`)\n const userData = await userRequest.json()\n\n return await Promise.all(\n // as async returns a promise we can add it to our new array of promises here\n userData.cats.map(async function(catId) {\n const response = await fetch(`https://catappapi.herokuapp.com/cats/${catId}`)\n const data = await response.json()\n return data.imageUrl\n })\n )\n}", "static fetchRestaurantByCuisine(cuisine) {\n return new Promise((resolve, reject) => {\n // Fetch all restaurants with proper error handling\n DBHelper.getRestaurants().then(restaurants => {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n resolve(results);\n }).catch(error => {\n reject(error);\n });\n });\n }", "async function fetchCities() {\n // TODO: MODULE_CITIES\n // 1. Fetch cities using the Backend API and return the data\n try{\n const res = await fetch(config.backendEndpoint + '/cities')\n .then(response => response.json())\n .then(data => {\n return data\n })\n .catch((error) => {\n return error\n });\n return res;\n }catch(e){\n return null\n }\n}", "fetchRestaurantByCuisine(cuisine, callback) {\r\n // Fetch all restaurants with proper error handling\r\n this.fetchRestaurants((error, restaurants) => {\r\n if (error) {\r\n callback(error, null);\r\n } else {\r\n // Filter restaurants to have only given cuisine type\r\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\r\n if (callback) {\r\n callback(null, results);\r\n }\r\n }\r\n });\r\n }", "async fetchUsers() {\n try {\n const res = await fetch(`${this.url}/list`);\n const json = await res.json();\n\n // Having retrieved our data, let's establish a new connection to our\n // API to obtain data for each individual user\n this.getEachUserData(json);\n \n // A token represents a signal that there are still more results left\n // that have yet been retrieved. Keep retrieving result \"token\" is null.\n let token = (\"token\" in json) ? json.token : \"\";\n do { \n try {\n const res = await fetch(`${this.url}/list?token=${token}`);\n const json = await res.json();\n this.getEachUserData(json);\n token = (\"token\" in json) ? json.token : \"\";\n }\n catch(e) {\n console.log(`${e} - Unable to obtain data from server`);\n }\n } while (token)\n\n // Having retrieved every user's information, loading is done and\n // proceed to retrieving youngest users\n this.setState({ loading: false })\n this.retrieveYoungestUsers();\n }\n catch(e) {\n console.log(`${e} - Unable to obtain data from server`);\n }\n }", "function prefetchISupeCourses(callback) {\n\n var queryFunctions = []; // Populate with functions with signature (callback)\n\n const iSupeCourses = canvasCache.getISupeCourses();\n for (let iSupeCourse of iSupeCourses) {\n const courseId = iSupeCourse.id;\n\n // We're interested in the course enrollments\n queryFunctions.push(\n function(cb) { return canvasCache.loadCourseEnrollments(courseId, cb); }\n );\n\n // We're interested in the course assignments\n queryFunctions.push(\n function (cb) { return canvasCache.loadCourseAssignments(courseId, cb); }\n );\n }\n\n // /**\n // * Faculty member can have up to 3 iSupervision courses, named like:\n // * \n // * \"CST1841S-\" + <mailbox part of user login>\n // * \"CST1842S-\" + <mailbox part of user login>\n // * \"CST1843S-\" + <mailbox part of user login>\n // * \n // * e.g. \"CST1841S-rplaugher\"\n // **/\n \n // const facultyLogins = Array.from(\n // new Set(\n // canvasCache.getFaculty().map(\n // e => e.user.login_id.split('@')[0] )));\n\n // // Get list of prefixes for iSupervision course names from the terms configuration\n // const terms = appConfig.getTerms();\n // const iSupePrefixes = Array.from(new Set(terms.map( e => e.isupe_prefix )));\n // // console.log(\"isupe_prefixes\", iSupePrefixes);\n\n // // Build list of all possible iSupervision course names\n // let iSupeCourseNames = [];\n // for (let iSupePrefix of iSupePrefixes) {\n // iSupeCourseNames = iSupeCourseNames.concat(facultyLogins.map( e => iSupePrefix + e));\n // }\n // // let iSupeCourseNames = [].concat(\n // // facultyLogins.map( e => \"CST1841S-\" + e),\n // // facultyLogins.map( e => \"CST1842S-\" + e),\n // // facultyLogins.map( e => \"CST1843S-\" + e)\n // // );\n\n // // for (let courseName of iSupeCourseNames) {\n // // console.log(courseName);\n // // }\n\n // // See how many of these iSupervision course names we can find\n // const courses = canvasCache.getCourses();\n // for (let iSupeCourseName of iSupeCourseNames) {\n\n // const iSupeCourse = courses.find( e => e.name === iSupeCourseName);\n // if (iSupeCourse) {\n // const courseId = iSupeCourse.id;\n\n // // We're interested in the course enrollments\n // queryFunctions.push(\n // function(cb) { return canvasCache.loadCourseEnrollments(courseId, cb); }\n // );\n\n // // We're interested in the course assignments\n // queryFunctions.push(\n // function (cb) { return canvasCache.loadCourseAssignments(courseId, cb); }\n // );\n\n // } // end if iSupervision course found for faculty member\n // } // end loop through faculty logins\n\n console.log(`Priming cache with iSupervision courses, ${queryFunctions.length} queries.`);\n // async.parallel(queryFunctions, (err, results) => {\n async.series(queryFunctions, (err, results) => {\n return callback(err, results);\n });\n}", "async function fetchClients(){\n try{\n const res = await fetch(`${baseUrl}/api`);\n const clients = await res.json();\n return clients;\n } catch(err){\n console.error(err)\n }\n \n}", "function getCouncils(callback) {\n chrome.storage.local.get([\"file-data\"], function (data) {\n // Extract a list of councils from the data.\n let districtInfo = data[\"file-data\"].districtInfo.contents['district-councils'];\n let councils = [];\n for (let council in districtInfo) {\n councils.push(council);\n }\n // Callback with the array of councils.\n callback(councils);\n });\n}", "function Fetch_All_from_Data_Set()\r\n{\r\n\tfor (var p=0;p<profileIds.length;p++){ \r\n \t\t\t\tfor (var i=0;i<studyIds.length;i++){ \r\n\t\t\t\tvar strServer = \"http://www.cbioportal.org/webservice.do?\";\t\r\n\t\t\t\tvar study = studyIds[i];\r\n\t\t\t\tvar profile = profileIds[p];\r\n\t\t\t\tvar request = \"cmd=getClinicalData&case_set_id=\"+study+\"_all\"\r\n\t\t\t\t \r\n\t\t\t\tvar str2 = strServer+request;\r\n\t\t\t\t(function(request,i,p) { \t\r\n\t\t\t\t\td3.csv(str2, function(error, json) {\r\n\t\t\t\t\t\ttemp_counter++\r\n\t\t\t\t\t\tprocessDone=true\r\n\t\t\t\t\t\tif (error) {\r\n\t\t\t\t\t\t\tconsole.warn(\"warn: \"+error);\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t}\t\r\n\t\t\t\t\t})\r\n\t\t\t\t\t.get()\r\n\t\t\t\t\t.on('load', function(d) {\t\t\t\t\t\r\n\t\t\t\t\t\tfor(var i=0;i<d.length;i++)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tfor( key in d[i])\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tvar days_to_death=key.split(\"\t\").indexOf(\"DAYS_TO_DEATH\")\r\n\t\t\t\t\t\t\t\tvar gender=key.split(\"\t\").indexOf(\"GENDER\")\r\n\t\t\t\t\t\t\t\tvar sex=key.split(\"\t\").indexOf(\"SEX\")\r\n\t\t\t\t\t\t\t\tvar final_obj={cancer_type : \"\",MALE : \"\",Female : \"\"}\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tif(gender>=0)\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tvar column_value=d[i][key].split(\"\t\")[\"\"||gender];\r\n\t\t\t\t\t\t\t\t\tcur_row_value=d[i][key].split(\"\t\")[key.split(\"\t\").indexOf(\"CANCER_TYPE\")];\r\n\t\t\t\t\t\t\t\t\tif(column_value==\"M\" || column_value==\"MALE\")\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tvar cur_row_value=d[i][key].split(\"\t\")[key.split(\"\t\").indexOf(\"CANCER_TYPE\")];\r\n\t\t\t\t\t\t\t\t\t\tif(Obj_Fetch[cur_row_value]== undefined)\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tObj_Fetch[cur_row_value]=[];\r\n\t\t\t\t\t\t\t\t\t\t\tObj_Fetch[cur_row_value][\"FEMALE\"]=0;\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\tObj_Fetch[cur_row_value][\"MALE\"]=0;\t\r\n\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tObj_Fetch[cur_row_value][\"MALE\"]=parseInt(Obj_Fetch[cur_row_value][\"MALE\"])+1;\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\telse if(column_value==\"F\" || column_value==\"FEMALE\")\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tvar cur_row_value=d[i][key].split(\"\t\")[key.split(\"\t\").indexOf(\"CANCER_TYPE\")];\r\n\t\t\t\t\t\t\t\t\t\tif(Obj_Fetch[cur_row_value]== undefined)\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tObj_Fetch[cur_row_value]=[];\r\n\t\t\t\t\t\t\t\t\t\t\tObj_Fetch[cur_row_value][\"FEMALE\"]=0;\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\tObj_Fetch[cur_row_value][\"MALE\"]=0;\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\tObj_Fetch[cur_row_value][\"FEMALE\"]=parseInt(Obj_Fetch[cur_row_value][\"FEMALE\"])+1;\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}\r\n\t\t\t\t\t\t\t\telse if(sex>=0)\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tvar cur_row_value=d[i][key].split(\"\t\")[key.split(\"\t\").indexOf(\"CANCER_TYPE\")];\r\n\t\t\t\t\t\t\t\t\tvar column_value=d[i][key].split(\"\t\")[sex];\r\n\t\t\t\t\t\t\t\t\tif(column_value==\"M\" || column_value==\"MALE\")\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tif(Obj_Fetch[cur_row_value]== undefined)\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tObj_Fetch[cur_row_value]=[];\r\n\t\t\t\t\t\t\t\t\t\t\tObj_Fetch[cur_row_value][\"MALE\"]=0;\r\n\t\t\t\t\t\t\t\t\t\t\tObj_Fetch[cur_row_value][\"FEMALE\"]=0;\r\n\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tObj_Fetch[cur_row_value][\"MALE\"]=parseInt(Obj_Fetch[cur_row_value][\"MALE\"])+1;\r\n\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\telse if(column_value==\"F\" || column_value==\"FEMALE\")\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tvar cur_row_value=d[i][key].split(\"\t\")[key.split(\"\t\").indexOf(\"CANCER_TYPE\")];\r\n\t\t\t\t\t\t\t\t\t\tif(Obj_Fetch[cur_row_value]== undefined)\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tObj_Fetch[cur_row_value]=[];\r\n\t\t\t\t\t\t\t\t\t\t\tObj_Fetch[cur_row_value][\"FEMALE\"]=0;\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\tObj_Fetch[cur_row_value][\"MALE\"]=0;\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tObj_Fetch[cur_row_value][\"FEMALE\"]=parseInt(Obj_Fetch[cur_row_value][\"FEMALE\"])+1;\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\t\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\ttemp_counter++\r\n\t\t\t\t\t\tif(temp_counter==(studyIds.length*2)){\r\n\t\t\t\t\t\tprocessDone=true\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tvar i=0;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t); \r\n\t\t\t\t\t})(request,i,p);\r\n\t\t\t} \r\n\t\t\tif(p==profileIds.length-1){\r\n\t\t\r\n\t\t\t}\r\n\t\t}\r\n\t\r\n\t\r\n\t}", "function getCoffees() { // axios uses promises !!!\n axios\n .get(url)\n .then(res => {\n // console.log(res);\n displayCoffees(res.data.records);\n })\n .catch(err => {\n console.error(err);\n });\n}", "static storeCuisines(idbPromise, cuisines) {\n idbPromise.then(db => {\n if (!db) return;\n \n let store = db.transaction('cuisine', 'readwrite')\n .objectStore('cuisine');\n cuisines.forEach((cuisine, index) => {\n store.put({\n id: index,\n name: cuisine\n });\n });\n });\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n this.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "function getCuisines(locObj){\n var deferred = $q.defer();\n\n $http({\n url: API_ENDPOINT + APIPATH.geoCode,\n method: 'GET',\n params: {\n lat: locObj.latitude,\n lon: locObj.longitude\n }\n })\n .then(function (data) {\n deferred.resolve(data);\n },function(data){\n deferred.resolve(data);\n $mdToast.show(\n $mdToast.simple()\n .textContent('Sorry! Unable to get the cuisins near your place')\n .position('top')\n .hideDelay(5000)\n );\n })\n\n return deferred.promise;\n }", "function getAllResClinco(req, res) {\n return __awaiter(this, void 0, void 0, function* () {\n yield ResClinico_1.default.find((err, doc) => {\n if (!err) {\n res.send(doc);\n }\n else {\n res.send('Error');\n }\n });\n });\n}", "function getAccs() {\n // console.log(\"getting accs\");\n\n sendHttpGetReq(\"/get_accs\")\n .then(res => {\n accs = res;\n\n if (accs.length > 0) {\n accs.forEach(acc => {\n let box = document.createElement(\"div\");\n box.className = \"result\";\n let acc_header = getAccHeader(acc, box);\n\n box.appendChild(acc_header);\n box.appendChild(document.createElement(\"br\"));\n\n acc.box = box;\n });\n console.log(`done processing, ${accs.length} accs found`);\n\n loadingAccs.style.display = \"none\";\n retrieveBtn.style.display = \"\";\n\n // ACC_LIMIT = accs.length;\n ACC_LIMIT = Math.min(accs.length, 200);\n // ACC_LIMIT = Math.min(accs.length, 50);\n } else {\n loadingAccs.style.display = \"none\";\n document.getElementById(\"no-accs\").style.display = \"\";\n }\n });\n }", "fetchCountryData() {\n this.countriesLoaded = false;\n this.errorCountries = false;\n\n fetch(`${this.api}/countries`)\n .then((res) => res.json())\n .then((data) => (this.items = data))\n .finally(() => (this.countriesLoaded = true))\n .catch((error) => {\n this.countriesLoaded = false;\n this.errorCountries = true;\n console.log(error);\n });\n }", "async _collect() {\n\t\tif (!this.state.should_collect) {\n\t\t\treturn;\n\t\t}\n\n\t\tfor (let char of window.get_characters()) {\n\t\t\tif (char.name === character.name || !char.online) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst server = window.server.region + window.server.id;\n\t\t\tif (char.server !== server) {\n\t\t\t\t// Not on this sever!\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tLogging.info(`Collecting from ${char.name}`);\n\t\t\tconst regulator = new Util.Regulator(Util.SECOND_MS);\n\t\t\twhile (Entity.get_entities({name: char.name}).length === 0) {\n\t\t\t\tawait regulator.regulate();\n\n\t\t\t\tif (this.is_interrupted()) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst c = Brain.get_character(char.name);\n\t\t\t\tif (!c.online || c.server !== server) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tawait movement.pathfind_move({x: c.x, y: c.y, map: c.map}, {range: 250}, {avoid: true});\n\t\t\t}\n\t\t}\n\n\t\t// Warp back to town\n\t\tawait character.town();\n\n\t\tthis.state.should_collect = false;\n\t\tthis.state.should_bank = true;\n\t}", "function get_all_cargo(req){\n var q = datastore.createQuery(CARGO).limit(3);\n var results = {}; //returned to user\n if(Object.keys(req.query).includes(\"cursor\")){ //If there is a cursor\n q.startVal = (req.query.cursor).replace(/ /g, \"+\"); //Set start of retrieval at cursor in URI format\n }\n console.log(\"QUERY\");\n console.log(q);\n return datastore.runQuery(q).then( entities => {\n results.items = entities[0];\n console.log(\"CURSOR\");\n console.log(entities[1]);\n if(entities[1].moreResults !== Datastore.NO_MORE_RESULTS){\n results.next = \"https://\" + req.get(\"host\") + \"/cargo?cursor=\" + entities[1].endCursor;\n } else {\n results.next = \"END OF RESULTS\";\n }\n\n return results;\n }).catch( err => {\n return false;\n });\n}", "async getCustomersList(_data) {\r\n\t\tlet return_result = {};\r\n\t\t_data.columns = {\r\n\t\t\tcustomer_id: \"customers.id\",\r\n\t\t\tfirst_name: knex.raw(\"CAST(AES_DECRYPT(customers.first_name,'\" + encription_key + \"') AS CHAR(255))\"),\r\n\t\t\tlast_name: knex.raw(\"CAST(AES_DECRYPT(customers.last_name,'\" + encription_key + \"') AS CHAR(255))\"),\r\n\t\t\temail: knex.raw(\"CAST(AES_DECRYPT(customers.email,'\" + encription_key + \"') AS CHAR(255))\"),\r\n\t\t\toam_commission: \"customers.oam_commission\",\r\n\t\t\towner_commission: \"customers.owner_commission\",\r\n\t\t\tgain_commission: \"customers.gain_commission\",\r\n\t\t\tdob: \"customers.dob\",\r\n\t\t\tgender: \"customers.gender\",\r\n\t\t\tcreated_at: knex.raw(\"DATE_FORMAT(customers.created_at,'%b %d,%Y, %h:%i:%S %p')\"),\r\n\t\t\tphone: knex.raw(\"CAST(AES_DECRYPT(customers.phone,'\" + encription_key + \"') AS CHAR(255))\"),\r\n\t\t\tcustomer_unique_id: knex.raw(\"CAST(AES_DECRYPT(customers.customer_unique_id,'\" + encription_key + \"') AS CHAR(255))\")\r\n\t\t};\r\n\r\n\t\tlet obj = customerModel.getCustomersList(_data);\r\n\t\treturn obj.then(async (result) => {\r\n\t\t\tif (result.length > 0) {\r\n\t\t\t\treturn_result.customer_list = result;\r\n\t\t\t\tdelete _data.limit;\r\n\t\t\t\tdelete _data.offset;\r\n\t\t\t\tdelete _data.columns;\r\n\t\t\t\tlet countData = await customerModel.getCustomersList(_data);\r\n\t\t\t\treturn_result.total_records = countData[0].total_records\r\n\r\n\t\t\t\treturn response.response_success(true, status_codes.customer_found, messages.customer_found, (return_result));\r\n\t\t\t} else {\r\n\t\t\t\tthrow new Error(\"customers_not_found\")\r\n\t\t\t}\r\n\t\t}).catch((err) => common_functions.catch_error(err));\r\n\t}", "function fetchRows () {\n\t\tjQuery.getJSON(url, function (response) {\n\t\t\tvar people = [],\n\t\t\t\textra;\n\t\t\tfor (var i in response.feed.entry) {\n\t\t\t\tif (response.feed.entry[i].content && response.feed.entry[i].content.$t !== '') {\n\t\t\t\t\textra = '{\"' + cleanUp(response.feed.entry[i].content.$t) + '\"}';\n\t\t\t\t\textra = jQuery.parseJSON(extra);\n\t\t\t\t\tif (response.feed.entry[i].title && extra.floor) {\n\t\t\t\t\t\tpeople.push(constructSeat(i, response, extra));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t$scope.turned = false;\n\t\t\t$scope.loaded = true;\n\t\t\t$scope.seats = people;\n\n\t\t\t$scope.setColz();\n\n\n\t\t\t$scope.$apply();\n\t\t});\t\n\t}", "fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood) {\n // Fetch all restaurants\n return this.fetchRestaurants().then(restaurants => {\n let results = restaurants;\n if (cuisine !== 'all') { // filter by cuisine\n results = results.filter(r => r.cuisine_type === cuisine);\n }\n if (neighborhood !== 'all') { // filter by neighborhood\n results = results.filter(r => r.neighborhood === neighborhood);\n }\n return results;\n });\n }", "function getAllCases() {\n return new Promise((resolve, reject) => {\n Case.query().then(cases => {\n resolve(cases);\n });\n });\n}", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisine(cuisine, callback) {\n // Fetch all restaurants with proper error handling\n DBHelper.fetchRestaurants((error, restaurants) => {\n if (error) {\n callback(error, null);\n } else {\n // Filter restaurants to have only given cuisine type\n const results = restaurants.filter(r => r.cuisine_type == cuisine);\n callback(null, results);\n }\n });\n }", "static fetchRestaurantByCuisine (cuisine) {\r\n return DBHelper.fetchRestaurants()\r\n .then(restaurants => {\r\n // Filter restaurants to have only given cuisine type\r\n return restaurants.filter(r => r.cuisine_type == cuisine)\r\n })\r\n }", "static async showAllFlights() {\n let flightQuery = 'SELECT * FROM flights';\n try {\n const client = await pool.connect();\n const result = await client.query(flightQuery);\n client.release();\n return result;\n } catch (error) {\n console.log(error);\n }\n }", "async function getCountries() {\r\n try {\r\n // Call the API to fetch data\r\n const res = await fetch('https://www.themealdb.com/api/json/v1/1/categories.php');\r\n const data = await res.json();\r\n \r\n //const result = axios.get('https://www.themealdb.com/api/json/v1/1/categories.php');\r\n // Await the result from the server and store\r\n // the result in a variable named customers\r\n // const { data: countries } = await result;\r\n // Iterate over the returned result\r\n data.categories.map(country => {\r\n \r\n div.innerHTML +=\r\n `<div class=\"card\" style=\"width: 10rem;\">\r\n <img src=\"${country.strCategoryThumb}\" class=\"card-img-top\" style=\"width:100%; height: 8rem;\"; alt=\"...\">\r\n <div class=\"card-body\" style=\"height:75px; padding:2px; \">\r\n <h5 style=\"font-size:12px; text-align:center;\">${country.strCategory}</h5>\r\n <p class=\"card-text\" style=\"font-size:9px;\">${country.strCategoryDescription.length\r\n < 50 ? `${country.strCategoryDescription}` :\r\n `${country.strCategoryDescription.substring(0, 100)}...`}</p>\r\n </div>\r\n </div>`;\r\n });\r\n }\r\n catch (err) {\r\n \r\n console.log(\"getCustomers: ERROR\", err);\r\n }\r\n}" ]
[ "0.7879858", "0.7223122", "0.7173168", "0.7173168", "0.71661013", "0.7154812", "0.71521324", "0.7096084", "0.706611", "0.706611", "0.706611", "0.706611", "0.706611", "0.706611", "0.706611", "0.7060444", "0.7043844", "0.7043844", "0.7041222", "0.7041222", "0.70409405", "0.7040292", "0.7029823", "0.70233256", "0.7016432", "0.6893062", "0.6862876", "0.6788889", "0.6765795", "0.6654145", "0.6592812", "0.62882644", "0.58732265", "0.5851057", "0.5804989", "0.57814914", "0.5760544", "0.5714971", "0.5700213", "0.5698653", "0.567982", "0.56258255", "0.5581139", "0.5564415", "0.5524761", "0.55226964", "0.5463218", "0.5449117", "0.5421575", "0.54178023", "0.5397652", "0.53813344", "0.5370998", "0.53306663", "0.5324392", "0.53176826", "0.53076136", "0.5303951", "0.5283427", "0.5256009", "0.5239812", "0.52373946", "0.52332157", "0.522633", "0.5224097", "0.5221391", "0.52154166", "0.5195006", "0.518706", "0.5185776", "0.5180285", "0.51799476", "0.51758254", "0.516739", "0.51669955", "0.51669955", "0.51669955", "0.51669955", "0.51669955", "0.51669955", "0.51669955", "0.51669955", "0.51669955", "0.5162396", "0.5157047", "0.5153303" ]
0.7034309
32
Map marker for a restaurant.
static mapMarkerForRestaurant(restaurant, map) { const marker = new google.maps.Marker({ position: restaurant.latlng, title: restaurant.name, url: DBHelper.urlForRestaurant(restaurant), map: map, animation: google.maps.Animation.DROP } ); return marker; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "static mapMarkerForRestaurant(restaurant, map) {\r\n // https://leafletjs.com/reference-1.3.0.html#marker\r\n const marker = new L.marker([restaurant.latlng.lat, restaurant.latlng.lng], {\r\n title: restaurant.name,\r\n alt: restaurant.name,\r\n url: DBHelper.urlForRestaurant(restaurant)\r\n })\r\n marker.addTo(map);\r\n return marker;\r\n }", "static mapMarkerForRestaurant(restaurant, map) {\n // https://leafletjs.com/reference-1.3.0.html#marker\n const marker = new L.marker([\n restaurant.latlng.lat, restaurant.latlng.lng\n ], {\n title: restaurant.name,\n alt: restaurant.name,\n url: DBHelper.urlForRestaurant(restaurant)\n })\n marker.addTo(newMap);\n return marker;\n }", "static mapMarkerForRestaurant(restaurant, map) {\r\n // https://leafletjs.com/reference-1.3.0.html#marker\r\n const marker = new L.marker([restaurant.latlng.lat, restaurant.latlng.lng],\r\n {title: restaurant.name,\r\n alt: restaurant.name,\r\n url: DBHelper.urlForRestaurant(restaurant)\r\n })\r\n marker.addTo(newMap);\r\n return marker;\r\n }", "static mapMarkerForRestaurant(restaurant, map) {\r\n const marker = new google.maps.Marker({\r\n position: restaurant.latlng,\r\n title: restaurant.name,\r\n url: DBHelper.getRestaurantURL(restaurant),\r\n map: map,\r\n animation: google.maps.Animation.DROP}\r\n );\r\n return marker;\r\n }", "static mapMarkerForRestaurant(restaurant, map) {\n const marker = new google.maps.Marker({\n position: restaurant.latlng,\n title: restaurant.name,\n url: this.urlForRestaurant(restaurant),\n map: map,\n animation: google.maps.Animation.DROP}\n );\n return marker;\n }", "static mapMarkerForRestaurant(restaurant, map) {\r\n // https://leafletjs.com/reference-1.3.0.html#marker \r\n const marker = new L.marker([restaurant.latlng.lat, restaurant.latlng.lng],\r\n {title: restaurant.name,\r\n alt: restaurant.name,\r\n url: DBHelper.urlForRestaurant(restaurant)\r\n })\r\n marker.addTo(newMap);\r\n return marker;\r\n }", "static mapMarkerForRestaurant(restaurant, map) {\r\n // https://leafletjs.com/reference-1.3.0.html#marker \r\n const marker = new L.marker([restaurant.latlng.lat, restaurant.latlng.lng],\r\n {title: restaurant.name,\r\n alt: restaurant.name,\r\n url: DBHelper.urlForRestaurant(restaurant)\r\n })\r\n marker.addTo(newMap);\r\n return marker;\r\n }", "static mapMarkerForRestaurant(restaurant, map) {\n // https://leafletjs.com/reference-1.3.0.html#marker\n const marker = new L.marker(\n [restaurant.latlng.lat, restaurant.latlng.lng],\n {\n title: restaurant.name,\n alt: restaurant.name,\n url: DBHelper.urlForRestaurant(restaurant)\n }\n );\n marker.addTo(newMap);\n return marker;\n }", "static mapMarkerForRestaurant(restaurant, map) {\r\n // https://leafletjs.com/reference-1.3.0.html#marker\r\n const marker = new L.marker([restaurant.latlng.lat, restaurant.latlng.lng],\r\n {title: restaurant.name,\r\n alt: restaurant.name,\r\n url: DBHelper.urlForRestaurant(restaurant)\r\n })\r\n marker.addTo(newMap);\r\n return marker;\r\n }", "static mapMarkerForRestaurant(restaurant, map) {\n const marker = new google.maps.Marker({\n position: restaurant.latlng,\n title: restaurant.name,\n url: DBHelper.urlForRestaurant(restaurant),\n map: map,\n animation: google.maps.Animation.DROP}\n );\n return marker;\n }", "static mapMarkerForRestaurant(restaurant, map) {\r\n const marker = new google.maps.Marker({\r\n position: restaurant.latlng,\r\n title: restaurant.name,\r\n url: DBHelper.urlForRestaurant(restaurant),\r\n map: map,\r\n animation: google.maps.Animation.DROP\r\n });\r\n return marker;\r\n }", "static mapMarkerForRestaurant(restaurant, map) {\n // https://leafletjs.com/reference-1.3.0.html#marker \n const marker = new L.marker([restaurant.latlng.lat, restaurant.latlng.lng],\n {title: restaurant.name,\n alt: restaurant.name,\n url: DBHelper.urlForRestaurant(restaurant)\n })\n marker.addTo(self.newMap);\n return marker;\n }", "static mapMarkerForRestaurant(restaurant, map) {\n // https://leafletjs.com/reference-1.3.0.html#marker \n const marker = new L.marker([restaurant.latlng.lat, restaurant.latlng.lng],\n {title: restaurant.name,\n alt: restaurant.name,\n url: DBHelper.urlForRestaurant(restaurant)\n })\n marker.addTo(self.newMap);\n return marker;\n }", "static mapMarkerForRestaurant(restaurant, map) {\r\n // https://leafletjs.com/reference-1.3.0.html#marker \r\n const marker = new L.marker([restaurant.latlng.lat, restaurant.latlng.lng],\r\n { title: restaurant.name,\r\n alt: restaurant.name,\r\n url: DBHelper.urlForRestaurant(restaurant)\r\n })\r\n marker.addTo(newMap);\r\n return marker;\r\n }", "static mapMarkerForRestaurant(restaurant, map) {\n // https://leafletjs.com/reference-1.3.0.html#marker\n const marker = new L.marker([restaurant.latlng.lat, restaurant.latlng.lng], {\n title: restaurant.name,\n alt: restaurant.name,\n url: DBHelper.urlForRestaurant(restaurant)\n });\n marker.addTo(newMap);\n return marker;\n }", "static mapMarkerForRestaurant(restaurant, map) {\r\n const marker = new google.maps.Marker({\r\n position: restaurant.latlng,\r\n title: restaurant.name,\r\n url: DBHelper.urlForRestaurant(restaurant),\r\n map: map,\r\n animation: google.maps.Animation.DROP}\r\n );\r\n return marker;\r\n }", "static mapMarkerForRestaurant(restaurant, map) {\r\n const marker = new google.maps.Marker({\r\n position: restaurant.latlng,\r\n title: restaurant.name,\r\n url: DBHelper.urlForRestaurant(restaurant),\r\n map: map,\r\n animation: google.maps.Animation.DROP}\r\n );\r\n return marker;\r\n }", "static mapMarkerForRestaurant(restaurant, map) {\r\n const marker = new google.maps.Marker({\r\n position: restaurant.latlng,\r\n title: restaurant.name,\r\n url: DBHelper.urlForRestaurant(restaurant),\r\n map: map,\r\n animation: google.maps.Animation.DROP}\r\n );\r\n return marker;\r\n }", "static mapMarkerForRestaurant(restaurant, map) {\r\n const marker = new google.maps.Marker({\r\n position: restaurant.latlng,\r\n title: restaurant.name,\r\n url: DBHelper.urlForRestaurant(restaurant),\r\n map: map,\r\n animation: google.maps.Animation.DROP}\r\n );\r\n return marker;\r\n }", "static mapMarkerForRestaurant(restaurant, map) {\r\n const marker = new google.maps.Marker({\r\n position: restaurant.latlng,\r\n title: restaurant.name,\r\n url: DBHelper.urlForRestaurant(restaurant),\r\n map: map,\r\n animation: google.maps.Animation.DROP}\r\n );\r\n return marker;\r\n }", "static mapMarkerForRestaurant(restaurant, map) {\r\n const marker = new google.maps.Marker({\r\n position: restaurant.latlng,\r\n title: restaurant.name,\r\n url: DBHelper.urlForRestaurant(restaurant),\r\n map: map,\r\n animation: google.maps.Animation.DROP}\r\n );\r\n return marker;\r\n }", "static mapMarkerForRestaurant(restaurant, map) {\r\n const marker = new google.maps.Marker({\r\n position: restaurant.latlng,\r\n title: restaurant.name,\r\n url: DBHelper.urlForRestaurant(restaurant),\r\n map: map,\r\n animation: google.maps.Animation.DROP}\r\n );\r\n return marker;\r\n }", "static mapMarkerForRestaurant(restaurant, map) {\r\n\t\t// https://leafletjs.com/reference-1.3.0.html#marker\r\n\t\tconst marker = new L.marker([ restaurant.latlng.lat, restaurant.latlng.lng ], {\r\n\t\t\ttitle: restaurant.name,\r\n\t\t\talt: restaurant.name,\r\n\t\t\turl: DBHelper.urlForRestaurant(restaurant)\r\n\t\t});\r\n\t\tmarker.addTo(newMap);\r\n\t\treturn marker;\r\n\t}", "static mapMarkerForRestaurant(restaurant, map) {\r\n\t\tconst marker = new google.maps.Marker({\r\n\t\t\tposition: restaurant.latlng,\r\n\t\t\ttitle: restaurant.name,\r\n\t\t\turl: DBHelper.urlForRestaurant(restaurant),\r\n\t\t\tmap: map,\r\n\t\t\tanimation: google.maps.Animation.DROP\r\n\t\t});\r\n\t\treturn marker;\r\n\t}", "mapMarkerForRestaurant(restaurant, map) {\r\n const marker = new google.maps.Marker({\r\n position: restaurant.latlng,\r\n title: restaurant.name,\r\n url: this.urlForRestaurant(restaurant),\r\n map: map,\r\n animation: google.maps.Animation.DROP\r\n });\r\n return marker;\r\n }", "static mapMarkerForRestaurant(restaurant, map) {\n const marker = new google.maps.Marker({\n position: restaurant.latlng,\n title: restaurant.name,\n url: DBHelper.urlForRestaurant(restaurant),\n map: map,\n animation: google.maps.Animation.DROP\n });\n marker.tabindex = -1;\n return marker;\n }", "static addMarkerForRestaurant(restaurant, map) {\n const marker = new google.maps.Marker({\n position: restaurant.latlng,\n title: restaurant.name,\n url: DBHelper.getRestaurantURL(restaurant),\n map: map,\n animation: google.maps.Animation.DROP}\n );\n return marker;\n }", "static mapMarkerForRestaurant(restaurant, map) {\n // https://leafletjs.com/reference-1.3.0.html#marker \n const marker = new L.marker([restaurant.latlng.lat, restaurant.latlng.lng],\n {title: restaurant.name,\n alt: restaurant.name,\n url: DBHelper.urlForRestaurant(restaurant)\n });\n marker.addTo(map);\n return marker;\n }", "static mapMarkerForRestaurant(restaurant, map) {\n // https://leafletjs.com/reference-1.3.0.html#marker \n const marker = new L.marker([restaurant.latlng.lat, restaurant.latlng.lng],\n {title: restaurant.name,\n alt: restaurant.name,\n url: DBHelper.urlForRestaurant(restaurant)\n })\n marker.addTo(newMap);\n return marker;\n }", "mapMarkerForRestaurant(restaurant, map) {\n const marker = new google.maps.Marker({\n position: restaurant.latlng,\n title: restaurant.name,\n url: this.urlForRestaurant(restaurant),\n map: map,\n animation: google.maps.Animation.DROP}\n );\n return marker;\n }", "static mapMarkerForRestaurant(restaurant, map) {\n // https://leafletjs.com/reference-1.3.0.html#marker \n const marker = new L.marker([restaurant.latlng.lat, restaurant.latlng.lng],\n {\n title: restaurant.name,\n alt: restaurant.name,\n url: DBHelper.urlForRestaurant(restaurant)\n })\n marker.addTo(newMap);\n return marker;\n }", "static mapMarkerForRestaurant(restaurant, map) {\n // https://leafletjs.com/reference-1.3.0.html#marker \n const marker = new L.marker([restaurant.latlng.lat, restaurant.latlng.lng], {\n title: restaurant.name,\n alt: restaurant.name,\n url: DBHelper.urlForRestaurant(restaurant)\n })\n marker.addTo(newMap);\n return marker;\n }", "static mapMarkerForRestaurant(restaurant, map) {\n /* global google */\n const marker = new google.maps.Marker({\n position: restaurant.latlng,\n title: restaurant.name,\n url: DBHelper.urlForRestaurant(restaurant),\n map: map,\n animation: google.maps.Animation.DROP}\n );\n return marker;\n }", "static mapMarkerForRestaurant(restaurant, map) {\r\n const marker = new google.maps.Marker({\r\n position: restaurant.latlng,\r\n title: restaurant.name,\r\n url: DBHelper.urlForRestaurant(restaurant),\r\n map: map,\r\n animation: google.maps.Animation.DROP\r\n }\r\n );\r\n return marker;\r\n }", "static mapMarkerForRestaurant(restaurant, map) {\r\n const marker = new google.maps.Marker({\r\n position: restaurant.latlng,\r\n title: restaurant.name,\r\n url: DBHelper.urlForRestaurant(restaurant),\r\n map: map,\r\n animation: google.maps.Animation.DROP\r\n }\r\n );\r\n return marker;\r\n }", "static mapMarkerForRestaurant(restaurant, map) {\n\t\tconst marker = new google.maps.Marker({\n\t\t\tposition: restaurant.latlng,\n\t\t\ttitle: restaurant.name,\n\t\t\turl: DBHelper.urlForRestaurant(restaurant),\n\t\t\tmap: map,\n\t\t\tanimation: google.maps.Animation.DROP}\n\t\t);\n\t\treturn marker;\n\t}", "static mapMarkerForRestaurant(restaurant, map) {\n\t\tconst marker = new google.maps.Marker({\n\t\t\tposition: restaurant.latlng,\n\t\t\ttitle: restaurant.name,\n\t\t\turl: DBHelper.urlForRestaurant(restaurant),\n\t\t\tmap: map,\n\t\t\tanimation: google.maps.Animation.DROP}\n\t\t);\n\t\treturn marker;\n\t}", "static mapMarkerForRestaurant(restaurant, map) {\n\t\t// https://leafletjs.com/reference-1.3.0.html#marker\n\t\tconst marker = new L.marker([restaurant.latlng.lat, restaurant.latlng.lng],\n\t\t\t{\n\t\t\t\ttitle: restaurant.name,\n\t\t\t\talt: restaurant.name,\n\t\t\t\turl: DBHelper.urlForRestaurant(restaurant)\n\t\t\t});\n\t\tmarker.addTo(newMap);\n\t\treturn marker;\n\t}", "mapMarkerForRestaurant(restaurant) {\r\n\t\tconst marker = new google.maps.Marker({\r\n\t\t\tposition: restaurant.latlng,\r\n\t\t\ttitle: restaurant.name,\r\n\t\t\turl: this.urlForRestaurant(restaurant),\r\n\t\t\tmap: window.map,\r\n\t\t\tanimation: google.maps.Animation.DROP\r\n\t\t});\r\n\t\treturn marker;\r\n\t}", "static mapMarkerForRestaurant(restaurant, map) {\r\n if (typeof L ==='undefined') return;\r\n // https://leafletjs.com/reference-1.3.0.html#marker \r\n const marker = new L.marker([restaurant.latlng.lat, restaurant.latlng.lng],\r\n {title: restaurant.name,\r\n alt: restaurant.name,\r\n url: DBHelper.urlForRestaurant(restaurant),\r\n keyboard: false\r\n })\r\n marker.addTo(newMap);\r\n return marker;\r\n }", "static mapMarkerForRestaurant(restaurant, map) {\n // https://leafletjs.com/reference-1.3.0.html#marker \n const marker = new L.marker([restaurant.latlng.lat, restaurant.latlng.lng],\n {title: restaurant.name,\n alt: restaurant.name,\n url: DBHelper.urlForRestaurant(restaurant)\n })\n marker.addTo(newMap);\n // marker.addTo(map);\n return marker;\n }", "static mapMarkerForRestaurant(restaurant, map) {\n\t\treturn new google.maps.Marker({\n\t\t\tposition: restaurant.latlng,\n\t\t\ttitle: restaurant.name,\n\t\t\turl: DBHelper.urlForRestaurant(restaurant),\n\t\t\tmap: map,\n\t\t\tanimation: google.maps.Animation.DROP\n\t\t});\n\t}", "static mapMarkerForRestaurant(restaurant, map) {\r\n if (map == null) {\r\n return;\r\n }\r\n\r\n const marker = new google.maps.Marker({\r\n position: restaurant.latlng,\r\n title: restaurant.name,\r\n url: DBHelper.urlForRestaurant(restaurant),\r\n map: map,\r\n animation: null //google.maps.Animation.DROP\r\n }\r\n );\r\n return marker;\r\n }", "static mapMarkerForRestaurant(restaurant, map) {\r\n const marker = new google.maps.Marker({\r\n position: restaurant.latlng,\r\n title: restaurant.name,\r\n url: DBHelper.urlForRestaurant(restaurant),\r\n map: map,\r\n icon: {\r\n anchor: new google.maps.Point(16, 16),\r\n url: 'data:image/svg+xml;utf-8, \\\r\n <svg width=\"32\" height=\"32\" viewBox=\"0 0 32 32\" xmlns=\"http://www.w3.org/2000/svg\"> \\\r\n <path fill=\"red\" stroke=\"white\" stroke-width=\"1.5\" d=\"M3.5 3.5h25v25h-25z\" ></path> \\\r\n </svg>'\r\n }, \r\n animation: google.maps.Animation.DROP}\r\n );\r\n return marker;\r\n }", "static mapMarkerForRestaurant(restaurant = self.restaurant, map) {\n // console.log('>>>>>>> DBHelper - mapMarkerForRestaurant(restaurant = self.restaurant, map)');\n const marker = new google.maps.Marker({\n position: restaurant.latlng,\n title: restaurant.name,\n url: DBHelper.urlForRestaurant(restaurant),\n map: map,\n animation: google.maps.Animation.DROP}\n );\n return marker;\n }", "mapMarkerForRestaurant(restaurant, map) {\n let marker = L.marker([restaurant.latlng.lat, restaurant.latlng.lng],\n {title: restaurant.name,\n bounceOnAdd: true,\n bounceOnAddOptions: {duration: 500, height: 100},\n }).addTo(map);\n marker.bindPopup(`<a href=\"${this.urlForRestaurant(restaurant)}\">${restaurant.name}</a>`);\n return marker;\n }", "static createMarkerData (restaurant) {\r\n return {\r\n position: restaurant.latlng,\r\n title: restaurant.name,\r\n url: DBHelper.urlForRestaurant(restaurant)\r\n };\r\n }", "addMarker(restaurant) {\n // https://leafletjs.com/reference-1.3.0.html#marker \n const marker = new L.marker([restaurant.latlng.lat, restaurant.latlng.lng], {\n title: restaurant.name,\n alt: restaurant.name,\n url: this.dataService.urlForRestaurant(restaurant)\n })\n marker.on(\"click\", () => {\n this.window.location.href = marker.options.url;\n });\n marker.addTo(this.map);\n this.markers.push(marker);\n }", "function addRestMarker(restaurant) {\n let lat = restaurant.location[0];\n let lng = restaurant.location[1];\n //console.log(\"****addRestMarker lat\", lat);\n var marker = L.marker([lat, lng], {icon: new L.Icon({\n iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.png',\n shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',\n iconSize: [25, 41],\n iconAnchor: [12, 41],\n popupAnchor: [1, -34],\n shadowSize: [41, 41]\n })\n }); //.addTo(mymap);\n //console.log(\"****addRestMarker marker\", marker);\n marker.on('click', (e) => {\n var images = restaurant.dishes;\n var slideshowContent = '';\n for(var i = 0; i < images.length; i++) {\n var img = images[images.length - 1 - i];\n let tags = img.tags.map(tag => `<mark>${tag}</mark>`).join(',');\n let dateSubstring = img.fileURL.split('%20');\n let fileDate = dateSubstring.slice(1, 4).join(' ');\n slideshowContent += '<div class=\"image' + (i === 0 ? ' active' : '') + '\">' +\n '<img src=\"' + img.fileURL + '\" />' +\n '<div>' + fileDate + '</div>' +\n '<div class=\"caption\">' + img.dish + '</div>' +\n '<div>' + tags + '</div>' +\n '</div>';\n }\n let best_adr = restaurant.adr;\n // let best_distance = null;\n // let best_adr = '';\n // for(var i = 0; i < itemsArray.length; i++)\n // {\n // if(itemsArray[i].name === restaurant.name)\n // {\n // let distance = calcCrow(itemsArray[i].lat, itemsArray[i].lng, lat, lng).toFixed(1);\n // if (!best_distance || distance < best_distance) {\n // best_distance = distance;\n // best_adr = itemsArray[i].adr;\n // }\n // }\n // }\n // sList = best_adr.split(\",\");\n // num = sList.length;\n // if (num > 2) {\n // best_adr = sList[num-2] + \",\" + sList[num-1]\n // }\n var popupContent = '<div id=\"' + restaurant.name + '\" class=\"popup\">' +\n \"<h6><font>\"+restaurant.name+\n \"</font></h6><p>\" +best_adr+\n \"</p>\"+\n\n '<div class=\"slideshow\">' +\n slideshowContent +\n '</div>' +\n '<div class=\"cycle\">' +\n '<a href=\"#\" class=\"prev\">&laquo; Previous</a>' +\n '<a href=\"#\" class=\"next\">Next &raquo;</a>' +\n '</div>'\n '</div>';\n\n var popup = L.popup();\n popup\n .setLatLng([lat, lng])\n .setContent(popupContent)\n .openOn(mymap);\n });\n // if(restaurant.coupon > 0){\n // var label = {text: restaurant.coupon.toString(), fontSize: \"20px\", fontWeight: \"bold\"}\n // //marker.setIcon(couponIcon2);\n // //marker.setLabel(label);\n // marker.bindTooltip(label,\n // {\n // permanent: true,\n // direction: 'right'\n // }\n // );\n // }\n var restaurantObj = new Restaurant(marker, restaurant.name, restaurant.location, restaurant.id, restaurant.dishes, restaurant.cuisines);\n markers.push(restaurantObj);\n //console.log(\"****restaurantObj\", restaurantObj);\n return marker;\n}", "function displayMarker(restaurant) {\n\t// If there is already highlighted marker, revert it first\n\tif (isHighlighted) { revertMarker(previousMarker, previousInfoWindow); }\n\n\trestaurant.infowindow = new google.maps.InfoWindow();\n\tpreviousInfoWindow = restaurant.infowindow;\n\tpreviousMarker = restaurant.marker;\n\thighlightMarker(restaurant.marker);\n populateInfoWindow(restaurant.marker, restaurant);\n}", "function createMarker(place, icon, markerList, rating) {\n\tending_lat = place.geometry.location.lat();\n\tending_lng = place.geometry.location.lng();\n\n\tvar icon = {\n\t\turl: icon,\n\t\tscaledSize: new google.maps.Size(30, 30),\n\t}\n\tvar marker = new google.maps.Marker({\n\t\tmap: map,\n\t\ticon: icon,\n\t\tposition: place.geometry.location,\n\t});\n\n\tmarkerList.push(marker);\n\n\t// show name of place and rating when mouse hovers over marker\n\tgoogle.maps.event.addListener(marker, 'mouseover', (function (placeName, rating) {\n\t\treturn function () {\n\t\t\tinfowindow.setContent(placeName + \"<br>Rating: \" + rating);\n\t\t\tinfowindow.open(map, this);\n\t\t}\n\t})(place.name, rating));\n\n\t// populate destination input box with location clicked on map\n\tgoogle.maps.event.addListener(marker, 'click', (function (placeName, ending_lat, ending_lng) {\n\t\treturn function () {\n\t\t\tdestination_latlng = new google.maps.LatLng(ending_lat, ending_lng);\n\t\t\tname = placeName;\n\t\t\t$('#destination-tourist').val(placeName);\n\t\t\t$('#destination-tourist').show();\n\t\t\t$('#tourist-destination-error').hide();\n\t\t}\n\t})(place.name, ending_lat, ending_lng));\n}", "function setMarkers(map, location){\n for (var i = 0; i < restaurants.length; i++){\n var restaurant = restaurants[i];\n var myLatLng = new google.maps.LatLng(restaurant[1], restaurant[2]);\n\n var marker = new google.maps.Marker({\n map: map,\n animation: google.maps.Animation.DROP,\n position: myLatLng,\n icon: icon,\n url: restaurant[6]\n\n });\n\n var content = '<div>' + '<h5><a href=\\\"'+restaurant[6]+'\\\">'\n + restaurant[0]+ '</a></h5>'\n + '<div class=\"secondary round label small-centered rate_label\">'+ restaurant[5]\n + '</div>'+'<div class=\"info round label small-centered rate_label\">'+ restaurant[4] + '</div>' + '</div>';\n\n\n var infowindow = new google.maps.InfoWindow();\n google.maps.event.addListener(marker,'mousemove', (function(marker,content,infowindow){\n return function() {\n infowindow.setContent(content);\n infowindow.open(map,marker);\n };\n })(marker,content,infowindow));\n\n google.maps.event.addListener(marker, 'click', function() {\n window.location.href = this.url;\n });\n\n\n google.maps.event.addListener(marker,'mouseout', (function(marker,content,infowindow){\n return function() {\n infowindow.close();\n };\n })(marker,content,infowindow));\n\n }\n\n}", "function placeMarker(myLatlng) {\n if ( marker ) {\n marker.setPosition(myLatlng);\n } else {\n var image = {\n url: '/locate.png',\n size: new google.maps.Size(512,512),\n origin: new google.maps.Point(0,0),\n anchor: new google.maps.Point(13,13),\n scaledSize: new google.maps.Size(26,26)\n };\n marker = new google.maps.Marker({\n position: myLatlng,\n map: map,\n icon: image\n });\n }\n }", "addRestaurant(restaurant) {\n this.restaurants.push(restaurant)\n\n const markerResto = this.addMarker({\n restaurant: restaurant,\n position: {\n lat: restaurant.position.lat,\n lng: restaurant.position.lng\n },\n title: restaurant.getLabel(),\n animation: google.maps.Animation.DROP,\n icon: 'img/resto-location.png',\n })\n\n this.markers.push(markerResto);\n /*Action au Click sur le marker du restaurant*/\n markerResto.addListener('click', _=>this.selectRestaurant(restaurant));\n }", "function createMarker(place) {\n var placeMarker = place.geometry.location;\n var marker = new google.maps.Marker({\n map: map,\n position: placeMarker\n });\n\n // listens for a click on the map \n // and displays the name of the restaurant when a specific marker is clicked\n google.maps.event.addListener(marker, 'click', function(){\n restaurantInfo.setContent(place.name);\n restaurantInfo.open(map, this);\n });\n return marker; \n}", "function placeMarderForLocation(index){\n\tlatLng = new google.maps.LatLng(favoriteLocations[index].latitude,favoriteLocations[index].longitude);\n\taddress = favoriteLocations[index].address;\n\tfavoriteName = favoriteLocations[index].name;\n\tfavoriteLocationId = favoriteLocations[index].location_id;\n\tplaceMarker(true);\n}", "function initMap() {\n var map = new google.maps.Map(document.getElementById('map_canvas'),{\n center: {lat: 20.5937, lng: 78.9629} ,\n zoom: 5,\n });\n\n var location = gon.locations\n var restaurant = gon.restaurant\n var restaurant_dish = gon.restaurant_dish\n var pictures = gon.pictures\n\n for(var i = 0 ; i < location.length; i++ ){\n var marker = new google.maps.Marker({\n position: {lat: location[i].latitude, lng: location[i].longitude},\n map: map,\n title: restaurant[i].name,\n label: {color:'white', fontWeight: \"bold\"},\n icon: {\n path: 'M22-48h-44v43h16l6 5 6-5h16z',\n fillColor: '#697f8c',\n fillOpacity: 1,\n strokeColor: '#FFFFFF',\n strokeWeight: 5,\n title: 'fdf',\n labelClass: \"label\",// the CSS class for the label\n labelOrigin: new google.maps.Point(0, -25),\n size: new google.maps.Size(32,32),\n anchor: new google.maps.Point(16,32) \n } \n });\n \n marker.content = '<p><img width =\"80px\" height = \"60px\" src='+pictures[i].image.url+' ><b> &nbsp;&nbsp;'+ restaurant[i].name+'</b><br><br><b class=\"location_address\">'+location[i].street+','+location[i].city+\n ','+location[i].state+','+location[i].pincode+','+location[i].country+'<b>';\n \n \n // var markerCluster = new MarkerClusterer(map, marker)\n\n\n //Marker onclick show info window and show all dishes related restaurant \n var infoWindow = new google.maps.InfoWindow();\n google.maps.event.addListener(marker, 'click',(function (marker, i) {\n return function(){\n infoWindow.setContent(this.content);\n infoWindow.open(map, this);\n var restaurant_id =restaurant[i].id;\n $.ajax({\n type: \"GET\",\n url: $(this).attr('href'),\n data: {restaurant_id: restaurant_id},\n dataType: \"script\",\n success: function () {\n }\n });\n }\n })(marker,i));\n }\n}", "function routeMarkers(position, icon, title, map){\n var routeMarker = new google.maps.Marker({\n position: position,\n map: map,\n icon: {\n url: icon,\n size: new google.maps.Size(71, 71),\n origin: new google.maps.Point(0, 0),\n anchor: new google.maps.Point(40, 70),\n scaledSize: new google.maps.Size(90, 90)\n },\n title: title\n })\n}", "function addMarker(xPos, yPos, foodTruck) {\n L.marker(xy(xPos, yPos), { foodTruck })\n .setIcon(foodTruckIcon)\n .addTo(map)\n .on('mouseover', showTooltip)\n .on('mouseout', hideTooltip)\n .on('click', showDetails);\n}", "function addMarker(markerPos, map) {\n var geocoder = new google.maps.Geocoder;\n var infowindow = new google.maps.InfoWindow;\n\n // Create a new marker\n geocoder.geocode({'location': markerPos}, function(results, status) {\n if (status === 'OK') {\n if (results[1]) {\n map.setZoom(7);\n map.panTo(markerPos);\n var marker = new google.maps.Marker({\n position: markerPos,\n map: map\n });\n //\n google.maps.event.addListener(marker, 'mousedown', function() {\n infowindow.setContent(results[1].formatted_address);\n infowindow.open(map, marker);\n // Get local weather\n weather(markerPos.lat,markerPos.lng);\n // Zoom to marker\n map.panTo(this.getPosition());\n map.setZoom(8);\n });\n } else {\n window.alert('No results found');\n }\n } else {\n window.alert('Geocoder failed due to: ' + status);\n }\n });\n}", "function showMarker(name,address){\n var l = self.restaurantList().length;\n for(var i=0;i<l;i++){\n var rName = self.restaurantList()[i].restaurant.name;\n var position = self.restaurantList()[i].marker.marker.position;\n var rAddress = self.restaurantList()[i].restaurant.address;\n if(name === rName && address === rAddress){\n map.panTo(position);\n map.setZoom(15);\n populateInfoWindow(self.restaurantList()[i].marker.marker,\n largeInfowindow,\n self.restaurantList()[i].marker.content);\n self.restaurantList()[i].marker.marker.setAnimation(\n google.maps.Animation.BOUNCE);\n\n break;\n }\n }\n }", "function populateInfoWindow(marker, restaurant) {\n// Check to make sure the infowindow is not already opened on this marker.\n\tif (restaurant.infowindow.marker != marker) {\n\t\trestaurant.infowindow.marker = marker;\n\t\trestaurant.infowindow.setContent('<div>' + marker.title + '</div>' + '<div>' + restaurant.address + '</div>' + \n\t\t\t'<div style=\"margin-top:5px\">' + '<a class=\"btn btn-primary\" href=\"' + restaurant.link + '\" role=\"button\">Reserve </a>' + '</div>');\n\t\trestaurant.infowindow.open(map, marker);\n\t\t// Clear marker property and revert the marker when closed\n\t\trestaurant.infowindow.addListener('closeclick',function() {\n revertMarker(marker, restaurant.infowindow);\n });\n google.maps.event.addListener(map, \"click\", function(event) {\n revertMarker(marker, restaurant.infowindow);\n\t\t});\n\t}\n}", "function addMarker2(location, title, map, rating) {\n\tvar icon = {\n\t url: \"https://use.fontawesome.com/releases/v5.0.13/svgs/solid/home.svg\", // url\n\t scaledSize: new google.maps.Size(30,30), // scaled size\n\t origin: new google.maps.Point(0,0), // origin\n\t anchor: new google.maps.Point(0, 0) // anchor\n\t};\n\n\n\tvar marker = new google.maps.Marker({\n\t\tposition: location,\n\t\ttitle: title,\n\t\tmap: map,\n\t\tlabel : rating,\n\t\ticon : icon\n\t});\n\treturn marker;\n}", "function renderMarkers (data,map) {\n let image = {\n url: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',\n // This marker is 20 pixels wide by 32 pixels high.\n size: new google.maps.Size(20, 32),\n // The origin for this image is (0, 0).\n origin: new google.maps.Point(0, 0),\n // The anchor for this image is the base of the flagpole at (0, 32).\n anchor: new google.maps.Point(0, 32)\n };\n let shape = {\n coords: [1, 1, 1, 20, 18, 20, 18, 1],\n type: 'poly'\n };\n marker = new google.maps.Marker({\n position: new google.maps.LatLng(`${data.restaurant.location.latitude}`,`${data.restaurant.location.longitude}`),\n map: map,\n icon: image,\n shape: shape,\n title: `${data.restaurant.name}`\n });\n console.log(marker);\n infoBox(data,marker,map);\n return marker;\n}", "function createMarker(place) {\n var marker = new google.maps.Marker({\n map: map,\n icon: \"assets/images/marker.png\",\n title: place.name,\n address: place.vicinity,\n phone: place.formatted_phone_number,\n price: place.price_level,\n rating: place.rating,\n position: place.geometry.location,\n animation: google.maps.Animation.DROP\n });\n\n google.maps.event.addListener(marker, 'click', function () {\n infowindow.setContent(\n \"<div><h3>\" + this.title + \"</h3>\" +\n \"<div>\" + this.address + \"<br>\" +\n \"Rating: \" + this.rating + \"/5<br>\" +\n \"<a id='markerCrawl'>Visit Next</a>\" +\n \"</div></div>\"\n );\n infowindow.open(map, this);\n });\n }", "function showRestaurants(data){\n console.log('you found restaurants! ', data);\n data.forEach(function(restaurant){\n var location = {\n lat: restaurant.coordinates.latitude,\n lng: restaurant.coordinates.longitude\n }\n // this is the content that goes on the card associated with each restaurant in the map\n var content = '<h6>' + restaurant.name + '</h6>' + '<p>' + restaurant.location.address1 + '</p>'\n addMarker(location, content)\n })\n }", "function initMap() {\n let options = {\n zoom: 5,\n center: userCoords,\n };\n let map = new google.maps.Map(document.getElementById(\"map\"), options);\n\n // Fonction de marqueur\n const addMarker = (props) => {\n let marker = new google.maps.Marker({\n position: props.coords,\n map: map, // quelle carte?: la carte ci-dessus\n });\n if (props.iconImage) marker.setIcon(props.iconImage);\n if (props.content) {\n let infoWindow = new google.maps.InfoWindow({\n content: props.content,\n });\n marker.addListener(\"click\", () => {\n infoWindow.open(map, marker);\n });\n }\n };\n\n addMarker({\n coords: userCoords,\n iconImage: \"http://maps.google.com/mapfiles/ms/icons/green-dot.png\",\n content: \"<h2>Vous êtes ici.</h2>\",\n });\n\n foodPlaces.forEach((foodPlace) => {\n let address = foodPlace.address.split(\",\");\n addMarker({\n coords: {\n lat: parseFloat(foodPlace.lat),\n lng: parseFloat(foodPlace.long),\n },\n content: `\n <h2>${foodPlace.restaurantName}</h2>\n <address>\n <p>${address[0]}</p>\n <p>${address[1].trim()}</p>\n </address>\n `,\n });\n });\n}", "function addMarker(pos){\n new google.maps.Marker({\n position: pos,\n map: map,\n icon: 'img/icons/UserLocation.png',\n title: \"Din Lokation\"\n }\n )\n}", "renderMarkers() {\n if (this.props.NearbyLocations.length > 0) {\n const restaurants = this.props.NearbyLocations;\n const markers = restaurants.map((restaurant, key) => {\n const coordinates = {\n latitude: parseFloat(restaurant.latitude),\n longitude: parseFloat(restaurant.longitude)\n };\n return (\n <MapView.Marker\n key={key}\n coordinate={coordinates}\n restaurantName={restaurant.restaurantName}\n onCalloutPress={() => Alert.alert(restaurant.restaurantName)}\n >\n <MapView.Callout>\n <View style={Styles.customView}>\n <Thumbnail\n small\n source={{ uri: getCDNRoute('restaurantPhoto') + restaurant.logo }}\n />\n <Text style={Styles.nameTextStyle}>\n {restaurant.restaurantName}\n </Text>\n <Text style={Styles.descriptionTextStyle}>\n {restaurant.kitchenType}\n </Text>\n <View style={Styles.iconsBar}>\n <Icon\n name='google-maps'\n color='#e62531'\n size={responsiveFontSize(4)}\n />\n <Icon\n name='phone'\n color='#e62531'\n size={responsiveFontSize(4)}\n />\n </View>\n </View>\n </MapView.Callout>\n </MapView.Marker>\n );\n });\n return markers;\n }\n }", "function showMarker(marker) {\n marker.setMap(map);\n }", "function placeMarker(latLng, map) {\n\tmarker = new google.maps.Marker({\n\t\tposition: latLng,\n\t\tmap: map,\n\t});\n}", "function setMarker(lat,long,title,id){var myLatlng=new google.maps.LatLng(lat,long);var marker=new google.maps.Marker({position:myLatlng,icon:'images/farm-2.png',animation:google.maps.Animation.DROP,'title':title});marker.setMap(map);google.maps.event.addListener(marker,'click',function(){window.location='single.php?id='+id;});}", "function createMarker(user_position,map){\n // array to hold markers\n var markers = [];\n\n coordinateLookup(function(coordinateLookups){\n\n // create object containing users coords for comparison\n var origin = new google.maps.LatLng(user_position.lat,user_position.lng);\n\n // creates marker for each address in list of restaurant coordinates(coordinateLookups)\n // coordinateLookups also contains restaurant name\n coordinateLookups.forEach(function(lookup,element){\n\n // create object containing restaurantscoordinates for comparison\n var restaurant_location = new google.maps.LatLng(lookup.Longitude, lookup.Latitude);\n\n // if distance from user location to restaurant under threshold draw marker on map\n if (restaurantNearby(restaurant_location, origin)) {\n // create markers based on restaurant coordinate array\n markers[element] = new google.maps.Marker({\n position: restaurant_location,\n map: map,\n title: lookup.Name\n });\n // Add on click event to marker\n markers[element].addListener('click', function() {\n // real routes required. Below is placeholder\n window.location.href = \"restaurant.html?id=\" + lookup.Name;\n });\n }\n }); \n });\n }", "function addMarker(latLng, title, map) {\n\n var marker = new google.maps.Marker({\n\n position: latLng,\n map: map,\n title: title\n // icon : markerImage()\n\n });\n\n markers.push(marker);\n return marker;\n}", "function marker(route, team, map, flightPath) {\n var marker;\n marker = new google.maps.Marker({\n position: route[route.length-1],\n map: map\n });\n //Hide all Starting Markers\n if(route.length == 1){\n marker.setVisible(false); //but still keep them in the array\n };\n\n //Adds the last position to the markers_list for autofit\n markers_list.push(route[route.length - 1]);\n \n\n \n google.maps.event.addListener(marker, 'click', function() {\n infowindow.setContent(makeContent(team));\n infowindow.open(map, marker);\n });\n google.maps.event.addListener(flightPath, 'click', function() {\n infowindow.setContent(makeContent(team));\n infowindow.open(map, marker);\n });\n}", "function renderMap() {\n\t\n\tmypos = new google.maps.LatLng(mylat, mylng);\n\t\n\tmap.panTo(mypos);\n\t\n\tvar image = 'testmarker2.png';\n\t\n\tvar marker = new google.maps.Marker({\n\t position: mypos,\n\t title: \"You are here\",\n\t icon: image\n\t});\n\t\n\tmarker.setMap(map);\n\t\n\tvar infowindow = new google.maps.InfoWindow();\n\t\n\tgoogle.maps.event.addListener(marker, 'click', function() {\n\t infowindow.setContent(marker.title);\n\t infowindow.open(map,marker);\n\t});\n\tnearestStation = shortestdist(mylat, mylng, tMarkers);\n\tmarker.title += \"<br/>\" + \"The nearest Red Line station is \" + nearestStation[0].title + \n\t\"<br/>\" + \"and the distance is \" + nearestStation[0].distance + \" miles.\"; \n\t\n\ttParse();\n\tcwParse();\n\t\n}", "function addMarker(location, map) {\n let infowindow = new google.maps.InfoWindow();\n var marker = new google.maps.Marker({\n position: {\n lat: location.lat,\n lng: location.lng\n },\n map: map,\n animation: google.maps.Animation.DROP\n });\n markers.push(marker);\n console.log('markers', markers);\n\n // adding pins for database\n const name = location.title;\n const description = location.description;\n const lat = location.lat;\n const lng = location.lng;\n const image = location.image;\n // get map_id from route query\n // const map_id = 1;\n // const user_id = 1;\n\n mapInfo.name = location.mapTitle;\n const pin = { name, description, lat, lng, image };\n\n pins.push(pin);\n console.log('pins', pins)\n\n google.maps.event.addListener(marker, 'click', function () {\n infowindow.close(); // Close previously opened infowindow\n infowindow.setContent(\n '<h4>' + location.title + '</h4>' +\n '<p>' + location.description + '</p>' +\n '<p id = \"markerImage\"> <img src = ' + location.image + '></p>',\n );\n infowindow.open(map, marker);\n });\n }", "function mapper_create_marker(point,title,glyph) {\n var number = map_markers.length\n var marker_options = { title:title }\n if ( glyph != null ) {\n\tmarker_options[\"icon\"] = glyph;\n }\n else if ( map_icons.length > 0 ) {\n\tmarker_options[\"icon\"] = map_icons[map_icons.length-1];\n }\n var marker = new GMarker(point, marker_options );\n map_markers.push(marker)\n marker.value = number;\n GEvent.addListener(marker, \"click\", function() {\n // marker.openInfoWindowHtml(title);\n map.openInfoWindowHtml(point,title);\n });\n map.addOverlay(marker);\n return marker;\n}", "function addMarker(destination, place) {\n // creates visual route to place\n directionsDisplay = new google.maps.DirectionsRenderer();\n directionsDisplay.setMap(map);\n var directionsService = new google.maps.DirectionsService();\n var request = {\n origin: latlng,\n destination: destination,\n travelMode: google.maps.TravelMode.DRIVING\n };\n directionsService.route(request, function(result, status) {\n if (status == google.maps.DirectionsStatus.OK) {\n directionsDisplay.setDirections(result);\n }\n });\n\n // creates marker with custom icon on place\n var img = {\n url: image,\n scaledSize: new google.maps.Size(40, 40, \"px\", \"px\")\n };\n var marker = new google.maps.Marker({\n map: map,\n position: destination,\n icon: img\n });\n\n marker.setAnimation(google.maps.Animation.BOUNCE);\n markers.push(marker);\n\n // creates infowindow for marker with Yelp rating\n var nm = place.name;\n console.log(nm);\n var stars = place.rating_img_url;\n var contentString = \"<div><em>\" + nm + \"</em> is rated <img src=\" + stars + \"> on Yelp!</div>\";\n var infowindow = new google.maps.InfoWindow({\n content: contentString,\n maxWidth: 700\n });\n\n // opens and closes infowindow based on hover state\n google.maps.event.addListener(marker, 'mouseover', function() {\n infowindow.open(map, marker);\n });\n google.maps.event.addListener(marker, 'mouseout', function() {\n infowindow.close();\n });\n infowindows.push(infowindow);\n $(\".myButton\").removeAttr(\"disabled\");\n\n}", "function placeMarker(map, location) {\n var marker = new google.maps.Marker({\n position: location,\n map: map\n });\n }", "onSelectRestaurant(restaurant){\n \n this.infoWindow.setContent(`<span> ${restaurant.name} </span><span> ${restaurant.address} </span>`)\n this.infoWindow.open(this.map,this.markers.find(m=>m.restaurant.address === restaurant.address));\n }", "function addMarker(lat, lng, name, address, url, rating) {\n if (!isReady()) {\n return false;\n }\n\n var content = '<address>' +\n '<strong>' +\n '<a href=\"' + url + '\">' + name + '</a>' +\n '</strong><br>' +\n address + '<br>' +\n '<p>Rating: ' + rating + '</p>' +\n '</address>';\n\n var marker = new google.maps.Marker({\n position: {lat:lat, lng:lng},\n animation: google.maps.Animation.DROP,\n map: map,\n // Marker Icon\n icon: 'food.png',\n title: name\n });\n\n // Add new marker to markers list\n markerList.push(marker);\n\n // infoWindow click event\n marker.addListener('click', function() {\n infowindow.setContent(content);\n infowindow.open(map, marker);\n // Animate marker\n marker.setAnimation(google.maps.Animation.BOUNCE);\n setTimeout(function () {\n marker.setAnimation(null);\n }, 750);\n });\n\n return true;\n }", "function initMap(){\n\tvar Position = {lat: 51.898291, lng: -8.473279};\n\tmap = new google.maps.Map(document.getElementById('map'), {\n\tzoom: 16,\n\tcenter: Position\n\t});\n\tgeocoder = new google.maps.Geocoder();\n service = new google.maps.places.PlacesService(map);\n infowindow = new google.maps.InfoWindow();\n\n // Using html geolocation to find current position\n if (navigator.geolocation) {\n navigator.geolocation.getCurrentPosition(function(position) {\n var pos = {\n lat: position.coords.latitude,\n lng: position.coords.longitude\n };\n map.setCenter(pos);\n addRestaurantNearby(pos);\n var markerX = new google.maps.Marker({//marker for user position\n position: pos,\n map:map,\n icon:'smiley.png',\n animation: google.maps.Animation.BOUNCE\n });\n },\n function() {\n handleLocationError(true, infoWindow, map.getCenter());\n });\n } else {\n // Browser doesn't support Geolocation\n handleLocationError(false, infoWindow, map.getCenter());\n addRestaurantNearby();\n }\n function handleLocationError(browserHasGeolocation, infoWindow, pos) {\n var infoWindow = new google.maps.InfoWindow({map: map});\n infoWindow.setPosition(pos);\n infoWindow.setContent(browserHasGeolocation ?\n 'Error: The Geolocation service failed.' :\n 'Error: Your browser doesn\\'t support geolocation.');\n }\n}", "function placeMarkerAndPanTo(latLng, map) {\n\n if (markers.length >= 2) {\n $('.alert.warning').html('<span class=\"closebtn\" onclick=\"toggle()\">&times;</span><strong>Oops!</strong> Путь не может содержать более 2 точек').toggle();\n\n } else {\n var marker = new google.maps.Marker({\n position: latLng,\n map: map\n });\n markers.push(marker);\n geocodeLatLng();\n if (markers.length === 2) {\n createRoute();\n $('.order__results').fadeIn();\n }\n }\n}", "function setMarkers(location, info, map, largeInfowindow, places) {\n var image = {\n url: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',\n // This marker is 20 pixels wide by 32 pixels high.\n size: new google.maps.Size(20, 32),\n // The origin for this image is (0, 0).\n origin: new google.maps.Point(0, 0),\n // The anchor for this image is the base of the flagpole at (0, 32).\n anchor: new google.maps.Point(0, 32)\n };\n // Shapes define the clickable region of the icon. The type defines an HTML\n // <area> element 'poly' which traces out a polygon as a series of X,Y points.\n // The final coordinate closes the poly by connecting to the first coordinate.\n var shape = {\n coords: [1, 1, 1, 20, 18, 20, 18, 1],\n type: 'poly'\n };\n // Convert lat and lng data to required format.\n var latlng = new google.maps.LatLng(info.lat, info.lng);\n // Send data to markers.\n var marker = new google.maps.Marker({\n icon: image,\n shape: shape,\n position: latlng,\n map: map,\n animation: google.maps.Animation.DROP,\n content: \"<h4><mark><strong>\" + info.title + \"</strong></mark></h4>\" +\n info.address + \"<br>\" +\n \"<p style='color:red'>\" + \"Rating: \" + info.rating + \"/10</p>\" +\n \"<a href='\" + info.url + \"'>\" + info.url + \"</a>\"\n });\n var infoWindow = new google.maps.InfoWindow({\n content: marker.content\n });\n // Dispay marker one by one.\n marker.infowindow = infoWindow;\n largeInfowindow.push(marker);\n places()[places().length - 1].marker = marker;\n google.maps.event.addListener(marker, 'click', function() {\n for (var i = largeInfowindow().length - 1; i >= 0; i--) {\n largeInfowindow()[i].infowindow.close();\n }\n infoWindow.open(map, marker);\n });\n google.maps.event.addListener(marker, 'click', function() {\n toggleBounce(marker);\n });\n}", "function createMapMarker(placeData) {\n\n // The next lines save location data from the search result object to local variables\n var lat = placeData.geometry.location.lat(); // latitude from the place service\n var lon = placeData.geometry.location.lng(); // longitude from the place service\n var name = placeData.formatted_address; // name of the place from the place service\n var bounds = window.mapBounds; // current boundaries of the map window\n \n // marker is an object with additional data about the pin for a single location\n var marker = new google.maps.Marker({\n map: map,\n position: placeData.geometry.location,\n title: name,\n //icon: 'http://labs.google.com/ridefinder/images/mm_20_gray.png'\n icon: './images/mm_20_gray.png'\n \n //Other marker options could be:\n /*{\n path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,\n scale:2,\n strokeOpacity: 10\n }*/\n\n //'./images/google-map-greyoutline-marker-small.png'\n //myIcon\n //'http://labs.google.com/ridefinder/images/mm_20_gray.png'\n \n });\n\n // infoWindows are the little helper windows that open when you click\n // or hover over a pin on a map. They usually contain more information\n // about a location.\n var infoWindow = new google.maps.InfoWindow({\n content: name\n });\n\n google.maps.event.addListener(marker, 'click', function() {\n map.setZoom(6);\n map.setCenter(marker.getPosition());\n infoWindow.setContent('<h6>' + marker.title + '</h6>');\n infoWindow.open(map, marker);\n });\n \n bounds.extend(new google.maps.LatLng(lat, lon));// this is where the pin actually gets added to the map.\n // bounds.extend() takes in a map location object\n map.fitBounds(bounds);// fit the map to the new marker\n \n map.setCenter(bounds.getCenter());// center the map\n }", "function initializeMap(restaurant) {\n let url = 'https://maps.googleapis.com/maps/api/staticmap?center=';\n\n let mapImg = document.getElementById('map-img');\n if (mapImg == null) {\n let elementById = document.getElementById('map-container');\n mapImg = document.createElement('img');\n mapImg.id = 'map-img';\n elementById.append(mapImg);\n }\n\n if (restaurant != null) {\n url = url + restaurant.latlng.lat + ',' + restaurant.latlng.lng + '&zoom=12&size=300x600&scale=2&maptype=roadmap';\n\n let label = restaurant.name.charAt(0);\n url = url + '&markers=color:red%7Clabel:' + label + '%7C' + restaurant.latlng.lat + ',' + restaurant.latlng.lng;\n }\n\n url = url + '&key=AIzaSyBb39XqJKBTDU7M9zXMctKaazu6pLtCINs';\n mapImg.alt = 'Location of the restaurant shown on map.'\n mapImg.src = url;\n}", "function createLocationSearchMarker(){\n vm.map.markers['user_current_location'] = {\n lat: angular.copy(current_location.lat),\n lng: angular.copy(current_location.lng),\n message: \"Estoy aquí!\",\n draggable:'true',\n focus: true,\n icon: {\n iconUrl: '/static/image/custom_position_marker.svg',\n shadowUrl: '/static/image/custom_position_marker_shadow.png',\n iconSize: [25, 25], // size of the icon\n iconAnchor: [12, 12], // point of the icon which will correspond to marker's location\n popupAnchor: [0, -10], // point from whtich the popup should open relative to the iconAnchor\n shadowAnchor: [10, -6], // the same for the shadow\n shadowSize: [25, 10] // size of the shadow\n },\n zIndexOffset: 100,\n popupopen: true\n };\n }", "function initMap() {\n var bcit = {\n lat: 49.250,\n lng: -123.000\n };\n var map = new google.maps.Map(\n document.getElementById('map'), {\n zoom: 14,\n center: bcit\n });\n var pinImage = {\n url: './images/leafPin.png',\n labelOrigin: new google.maps.Point(15, 40)\n };\n var marker2 = new google.maps.Marker({\n position: bcit,\n map: map,\n icon: pinImage,\n label: {\n color: 'green',\n fontSize: '10pt',\n text: 'BCIT',\n fontWeight: 'bold',\n }\n });\n\n// Creates the pins for each restaurant in the database\n// Called when the map page is loaded.\ndb.collection('Restaurants').get().then(function (querySnapshot) {\n querySnapshot.forEach(function (doc) {\n console.log(doc.id, \" => \", doc.data());\n var lat = doc.data().location._lat;\n var long = doc.data().location._long;\n var name = doc.data().Name;\n var docid = doc.id;\n console.log(name);\n console.log(docid);\n var marker = new google.maps.Marker({\n position: {\n lat: lat,\n lng: long,\n },\n map: map,\n labelAnchor: new google.maps.Point(100, 0),\n title: name,\n icon: pinImage,\n url: doc.data().link,\n label: {\n textShadow: '10px 10px #ff0000',\n fontWeight: 'bold',\n color: 'green',\n fontSize: '10pt',\n text: name\n }\n });\n // When a pin is clicked, add the restaurant's unique ID to the url and move to\n // to the restaurant page. Reads the doc id from the database.\n google.maps.event.addListener(marker, 'click', function () {\n window.location.href = \"restaurantpage.html?\"+docid;\n });\n });\n});\n\n\n}", "function populateMap (restaurants) {\n\tvar bounds = new google.maps.LatLngBounds();\n\n\t// If the are any markers already, remove them from the map\n\tif (markers) { removeMarkers(); }\n\n\t// No markers are highlighted when they are created\n\tisHighlighted = false;\n\n\tfor (var i = 0; i < restaurants.length; i++) {\n\t\t(function() {\n\t\t\tvar restaurant = restaurants[i];\n\t\t\tvar location = {lat: restaurant.lat, lng: restaurant.lng};\n\t\t\t// Creare a marker\n\t\t\trestaurant.marker = new google.maps.Marker({\n\t\t\t position: location,\n\t\t\t map: map,\n\t\t\t title: restaurant.name\n\t });\n\t markers.push(restaurant.marker);\n\t restaurant.marker.addListener('click', function() {\n\t \tdisplayMarker(restaurant);\n\t });\n\n\t // Expend the map coverage to show all the markers\n\t bounds.extend(restaurant.marker.position);\n\t\t}());\n\t}\n\tmap.panToBounds(bounds);\n}", "function createMarker(infowindow, icons, store, results, map) {\n\tvar marker = new google.maps.Marker({\n\t\t\tposition: results[0].geometry.location,\n\t\t\ticon: icons[store.type].icon,\n\t\t\tmap: map\n\t});\n\t\n\tmarker.addListener('click', function () {\n\t\tmap.setCenter(results[0].geometry.location);\n\t\tmap.setZoom(17);\n\t\tinfowindow.open(map, marker);\n\t});\n\n\t//$(\"span.address.storeaddress\").css(\"cursor\", \"default\");\n\tvar address = getDataAddress(infowindow.content);\n\tif(address) {\n\t\t/*\n\t\tif($(\"[data-address='\" + address + \"']\") && $(\"[data-address='\" + address + \"']\").parent()) {\n\t\t\t$(\"[data-address='\" + address + \"']\").parent().children().css(\"cursor\", \"pointer\");\n\t\t}\n\t\t*/\n\t\t$(\"[data-address='\" + address + \"']\").click(function () {\n\t\t\tmap.setCenter(results[0].geometry.location);\n\t\t\tmap.setZoom(17);\n\t\t\tinfowindow.open(map, marker);\n\t\t});\n\t}\n\t\n\treturn marker;\n}", "function dodajMarker(latlng)\n{\n\tmarker = new google.maps.Marker({ \n\t\t\t\tposition: latlng,\n\t\t\t\t\tmap: mapa,\n\t\t\t\t});\n}", "function setMarker(x,y){\n marker = new google.maps.Marker({\n position: new google.maps.LatLng(x, y),\n map: map,\n icon: 'images/map-marker.png',\n title: 'You are here !'\n });\n\n}", "function pin(location) {\n var inputloc = new google.maps.Marker({\n clickable: false,\n icon: new google.maps.MarkerImage('//maps.gstatic.com/mapfiles/mobile/mobileimgs2.png',\n new google.maps.Size(22, 22),\n new google.maps.Point(0, 18),\n new google.maps.Point(11, 11)),\n shadow: null,\n zIndex: 999,\n map: map\n });\n inputloc.setPosition(location);\n}", "function createMarker(pokemon){\n\t\tconsole.log(myLatlng.lat);\n\t\tconsole.log(typeof(myLatlng.lat));\n\t\tvar newLat = randomLat(myLatlng.lat);\n\t\tvar newLng = randomLng(myLatlng.lng);\n\t\tvar iconClicked = false;\n\t\tvar icon = 'css/pokeball.png';\n\t\tvar ultraball = 'css/ultraball.png';\n\t\tvar pokemonLatlng = {lat: newLat, lng: newLng};\n\t\tvar marker = new google.maps.Marker({\n\t\t\tposition: pokemonLatlng,\n\t\t\tmap: map,\n\t\t\ttitle: pokemon.name,\n\t\t\t//sets the icon image\n\t\t\ticon: 'css/ultraball.png'\n\t\t});\n\t\tgoogle.maps.event.addListener(marker, 'click', function(){\n\t\t\tvar randomPoke = Math.ceil(Math.random()*20)\n\t\t\tvar newImg = 'css/pokemon/' + randomPoke + '.png';\n \tconsole.log(marker);\n \t// if(temp === 1){\n \t// \tif(marker.icon == icon){\n \t// \t\t// marker.setIcon(ultraball);\n \t// \t\tconsole.log('ultra');\n \t// \t}else{\n \t// \t\t// marker.setIcon(icon);\n \t// \t\tconsole.log('oh no!');\n \t// \t}\n \t// \ticonClicked = true;\n \t// \ttemp = 0;\n \t// }\n \t// console.log(marker);\n\t\t})\n\t\tmarkers.push(marker);\n\t\tconsole.log(marker);\n\t}", "function initMap() {\n var centerTarget = {lat: Number(item.mapY) ,lng: Number(item.mapX)};\n map = new google.maps.Map(document.getElementById('map'), {\n zoom: 12,\n center: centerTarget\n });\n\n new google.maps.Marker({\n position: centerTarget,\n map: map,\n icon: '/APIcamp/img/marker.png'\n });\n }", "function createRealtyMarker(realty) {\n\t\tvar marker = new google.maps.Marker({\n\t\t\tposition: new google.maps.LatLng(realty['latitude'], realty['longitude']),\n\t\t\ttitle: realty['address'],\n\t\t\ticon: 'moradiaicon.png'\n\t\t});\n\n\t\tgoogle.maps.event.addListener(marker, 'click', function() {\n\t\t\t$.get(\n\t\t\t\t'realties/' + realty['id'],\n\t\t\t\t{ },\n\t\t\t\tfunction(data) {\n\t\t\t\t\t$('#info').html(data);\n\t\t\t\t}\n\t\t\t);\n\t\t});\n\n\t\treturn marker;\n\t}", "function showRestaurantListings() {\n let bounds = new google.maps.LatLngBounds();\n // Extend the boundaries of the map for each marker and display the marker\n for (let i = 0; i < markersRestaurant.length; i++) {\n markersRestaurant[i].setMap(map);\n bounds.extend(markersRestaurant[i].position);\n }\n map.fitBounds(bounds);\n}", "function add_marker( $marker, map ) {\r\n\r\n var latlng = new google.maps.LatLng( $marker.attr('data-lat'), $marker.attr('data-lng') );\r\n\r\n /*var iconObj = { //38, 51\r\n url : marker_url, //<--marker_url = variable\r\n size : new google.maps.Size(38, 51),\r\n scaledSize : new google.maps.Size(38, 51),\r\n };*/\r\n var marker = new google.maps.Marker({\r\n //icon : iconObj,\r\n position : latlng,\r\n map : map\r\n });\r\n\r\n map.markers.push( marker );\r\n\r\n if( $marker.html() )\r\n {\r\n var infowindow = new google.maps.InfoWindow({\r\n content : $marker.html()\r\n });\r\n google.maps.event.addListener(marker, 'click', function() {\r\n infowindow.open( map, marker );\r\n });\r\n }\r\n }", "function addMarker(location, map) {\n\n selectIcon = document.querySelector('#iconType'),\n selectName = document.querySelector('#markerName')\n\n var marker = new google.maps.Marker({\n position: location,\n map: map,\n title: selectName.value,\n icon: selectIcon.value\n });\n }" ]
[ "0.8293048", "0.82430345", "0.8241308", "0.82409847", "0.82373875", "0.8237239", "0.8237239", "0.8235075", "0.82349753", "0.8233382", "0.8220988", "0.8219706", "0.8219706", "0.8217531", "0.82174104", "0.8216146", "0.8216146", "0.8216146", "0.8216146", "0.8216146", "0.8216146", "0.8216146", "0.8208991", "0.82013476", "0.81967455", "0.8186214", "0.818162", "0.81812257", "0.81771743", "0.8177006", "0.81739616", "0.8167768", "0.8156444", "0.81469256", "0.81469256", "0.81417894", "0.81417894", "0.814172", "0.8116268", "0.8111744", "0.8110092", "0.8104892", "0.80809206", "0.8035521", "0.7926422", "0.7470978", "0.7218752", "0.7053412", "0.69983774", "0.69286364", "0.6848073", "0.6821621", "0.6796236", "0.67954427", "0.67933434", "0.67650175", "0.67437476", "0.6728685", "0.6724524", "0.67094785", "0.66699326", "0.66590405", "0.66512793", "0.663271", "0.6626264", "0.6609219", "0.66081566", "0.6599061", "0.6583526", "0.65415853", "0.65295756", "0.6521024", "0.6518503", "0.6517531", "0.65013", "0.64968425", "0.6480305", "0.64757425", "0.6467324", "0.6451128", "0.64327127", "0.64238155", "0.6420122", "0.64195347", "0.6419442", "0.6412833", "0.6404075", "0.63975877", "0.63867956", "0.6372533", "0.6370165", "0.6365605", "0.6351177", "0.6350778", "0.6344655", "0.6332197", "0.63250095", "0.6324274", "0.6322315", "0.63214856" ]
0.82158864
22
FUNZIONI DI CONVALIDA E INVIO DEL MODULO INPUT
function validaParametri(handleFrase, handleVelocita) { frase = handleFrase.value; velocita = handleVelocita.value; if (frase == "") { alert("Inserire almeno un carattere"); handleFrase.focus(); return false; } if (frase == "") { alert("Inserire almeno un carattere"); handleFrase.focus(); return false; } if (frase.match(/[\|%]/)) // NON FUNZIONA { alert("I caratteri \, | e % non sono ammessi"); handleFrase.focus(); return false(); } if (isNaN(velocita) || velocita <= 0) { alert("La velocita' e' una quantita' intera positiva non nulla"); handleVelocita.value="120"; handleVelocita.focus(); return false; } return true; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function validNumber(obj){\n\tvar formObj = document.getElementById(obj.id);\n var filter = /^([0-9\\.])+$/;\n if (!filter.test(formObj.value)) {\n// \talert(\"Please input number !\");\n \tComShowCodeMessage('COM12178');\n \tformObj.value=\"\";\n }\n return true;\n}", "function seNaoIntReset(obj_input, valor_reset)\n{\n if (obj_input.value.trim() == \"\")\n {\n obj_input.value = valor_reset;\n return true;\n }\n\n obj_input.value = ((isNaN(obj_input.value)) || (obj_input.value.indexOf('.') > -1) ? //ATENCAO!! Kenneth removeu \"|| parseInt(vlr) == 0\" daqui pq nao aceitava \"0\"\n valor_reset : obj_input.value);\n obj_input.value = obj_input.value.trim();\n}", "function valida_numeros(e){\n tecla = (document.all) ? e.keyCode : e.which;\n //Tecla de retroceso para borrar, siempre la permite\n if (tecla == 8 ){ return true; }\n if (tecla == 9 ){ return true; }\n if (tecla == 0 ){ return true; }\n if (tecla == 13 ){ return true; }\n \n // Patron de entrada, en este caso solo acepta numeros\n patron =/[0-9-.]/;\n tecla_final = String.fromCharCode(tecla);\n return patron.test(tecla_final);\n }", "function validar_rut()\n{\n var rut = document.getElementById('rut_b');\n var digito = document.getElementById('dv_b');\n var numerico = rut.value.search( /[^0-9]/i );\n \n if(rut.value == \"\" && digito.value == \"\")\n return true\n if( numerico != -1 ) {\n alert(\"El rut contiene un caracter no numerico\")\n return false\n }\n if( digito.value == \"\" && rut.value != \"\") {\n alert(\"No ha ingresado el digito verificador\")\n return false\n }\n if( digito.value != \"K\" && digito.value != \"k\" )\n {\n var numerico1 = digito.value.search( /[^0-9]/i );\n if( numerico1 != -1 )\n {\n alert(\"El digito verificador no es valido\")\n return false\n }\n }\n var rut_aux = rut.value;\n var i = 0;\n var suma = 0;\n var mult = 2;\n var c = 0;\n var modulo11 = 0;\n var largo = rut_aux.length;\n for( i = largo - 1; i >= 0; i-- )\n {\n suma = suma + rut_aux.charAt( i ) * mult;\n mult++;\n if( mult > 7 )\n mult = 2;\n }\n modulo11 = 11 - suma % 11;\n if( modulo11 == 10 )\n modulo11 = \"K\";\n if( modulo11 == 11 )\n modulo11 = \"0\";\n if( modulo11 != digito.value.toUpperCase() )\n {\n alert( \"Rut invalido.\" );\n return false;\n }\n return true;\n}", "function validate(n) {\n n = String(n)\n let pisah = n.split('')\n let jumlah = 0\n console.log(pisah)\n if (pisah.length % 2 === 0) {\n for (let i = 0; i < pisah.length; i++) {\n if (i % 2 === 0) {\n pisah[i] = pisah[i] * 2\n }\n }\n } \n \n else if (pisah.length % 2 !== 0) {\n for (let i = 0; i < pisah.length; i++) {\n if (i % 2 !== 0) {\n pisah[i] = pisah[i] * 2\n }\n }\n }\n\n console.log(pisah)\n\n for (let i = 0; i < pisah.length; i++) {\n if (String(pisah[i]).length > 1) {\n pisah[i] = pisah[i]-9\n }\n }\n \n console.log(pisah)\n for (let i = 0; i < pisah.length; i++) {\n jumlah += Number(pisah[i])\n }\n\n console.log(jumlah)\n\n if (jumlah % 10 === 0) {\n return true\n } else {\n return false\n }\n}", "function isinputvalid() {\r\n let inputstr = field.value;\r\n let patt = /^[0-9]{1,3}$/g; //1-999\r\n let cond = patt.test(inputstr);\r\n\r\n if (!cond) {\r\n field.value = \"\";\r\n updateImg(data.default.bev);\r\n }\r\n return cond;\r\n}", "function soloNumeros(evt)\n{ \n //Validar la existencia del objeto event \n evt = (evt) ? evt : event; \n //Extraer el codigo del caracter de uno de los diferentes grupos de codigos \n var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0)); \n //Predefinir como valido \n var respuesta = true; \n //Validar si el codigo corresponde a los NO aceptables \n if (charCode > 31 && (charCode < 48 || charCode > 57))\n { \n //Asignar FALSE a la respuesta si es de los NO aceptables \n respuesta = false; \n } \n //Regresar la respuesta \n return respuesta; \n}", "fonevalidate(input, minValue) {\n let inputLength = input.value.length;\n \n let errorMessage = `Insira o telefone no padrão (00)00000-0000`;\n \n \n if(inputLength != minValue){\n this.printMessage(input, errorMessage);\n } \n }", "function verifyInput(){\r\n}", "function chequearSoloNumeros(field) {\n if (/^([0-9])*$/.test(field.value)) {\n setValido(field);\n return true;\n } else {\n setInvalido(field, `${field.name} solo debe contener números`);\n return false;\n }\n }", "function validaCampoNumero(Nombre, longitud, ActualLement, rango, decimal) {\n //errorIs = Array();\n LimitaTamCampo(Nombre, Number(longitud), '#' + ActualLement);\n $('#' + ActualLement + '_txt_' + Nombre).change(function () {\n resetCampo(Nombre, '#' + ActualLement);\n validaCampoNumeroInSave(Nombre, ActualLement, rango, decimal);\n });\n}", "function isValidDespacho(formname){\n \n var numero = document.forms[formname][\"ndespacho\"].value;\n var x= document.getElementById(\"ndespacho\");\n numero=numero.trim();\n document.forms[formname][\"ndespacho\"].value=numero; //Refrescamos los datos introducidos en el campo ndespacho de formname ahora sin espacios en los extremos\n if(!/^\\d{1,2}$/.test(numero)){ //Si no es un número de uno o dos dígitos entonces fallo\n x.innerHTML=\"Error: formato erroneo. Introduzca un solo número.\"\n return false;\n }\n \n if(numero.length == 0){ //Si está vacio entonces fallo\n x.innerHTML=\"Error: campo vacio\";\n return false;\n }\n \n\n if(numero < 0 || numero > 100){ //Si es un número negativo o mayor que 100 fallo\n \n x.innerHTML=\"Error: número despacho inexistente.\";\n return false; \n }\n x.innerHTML=\"\";\n \n numero=numero.trim();\n document.forms[formname][\"ndespacho\"].value=numero; \n \n return true;\n}", "mod() {}", "mod() {}", "function isNum(text,inputfield) {\n\tvar esum = 0;\n\tvar enumbers = \"\";\n\tvar checknum = 0;\n\tvar ch_sum = \"\";\n\tvar checkdigit = 0;\n\tvar sin = \"\";\n\tvar lastdigit = 0;\n console.log(\"inside the isNum --> text \"+text);\n console.log(\"inside the isNum --> inputfield\"+inputfield);\n \n\t if(text == \"\") {\n\t\t document.getElementById(inputfield).innerHTML = \"<span style='color:red'>*You left the SIN field blank.</span>\";\n\t //alert(\"You left the SIN field blank.\");\n \treturn false;\n\t }\n\t \tinStr = text;\n sin = text;\n inLen = inStr.length;\n\n\t\tif (inLen > 11 || inLen < 11) {\n\t\t\tdocument.getElementById(inputfield).innerHTML = \"<span style='color:red'>*SIN must be 11 characters long.</span>\";\n \t\t//alert(\"SIN must be 11 characters long\");\n\t\t\treturn false;\n\t\t\t}\n\n \t for (var i = 0; i < text.length; i++) {\n\t \t\tvar ch = text.substring(i, i + 1)\n\n\t\t\tif ((ch < \"0\" || \"9\" < ch) && (ch != \"-\")) {\n\t\t\t\tdocument.getElementById(inputfield).innerHTML = \"<span style='color:red'>*You must enter a 9 digits and two dashes.\\nFormat 999-999-999..</span>\";\n\t \t\t//alert(\"You must enter a 9 digits and two dashes.\\nFormat 999-999-999.\")\n\t\t\t\treturn false;\n\t\t \t}\n if ((i == 3 || i == 7) && (ch != \"-\")) {\n \t document.getElementById(inputfield).innerHTML = \"<span style='color:red'>*Invalid character in position 4 or 8;\\nMust be a dash!.</span>\";\n //alert(\"Invalid character in position 4 or 8;\\nMust be a dash!\");\n return false;\n }\n\t\t\t}\n lastdigit = text.substring(10, 10 + 1);\n /** add numbers in odd positions; IE 1, 3, 6, 8 */\t\t\n\t\t\tvar odd = ((text.substring(0,0 + 1)) * (1.0) + (text.substring(2,2 + 1)) * (1.0) \n\t\t\t+(text.substring(5, 5+1)) * (1.0) + (text.substring(8,8 + 1)) * (1.0));\n \t\t\t\n /** form texting of numbers in even positions IE 2, 4, 6, 8*/\n var enumbers = (text.substring(1,1 + 1)) + (text.substring(4,4 + 1))+\n (text.substring(6,6 + 1)) + (text.substring(9,9 + 1));\n /**\n add together numbers in new text string\n take numbers in even positions; IE 2, 4, 6, 8\n and double them to form a new text string\n EG if numbers are 2,5,1,9 new text string is 410218\n */\n \n for (var i = 0; i < enumbers.length; i++) {\n var ch = (enumbers.substring(i, i + 1) * 2);\n ch_sum = ch_sum + ch;\n }\n \n for (var i = 0; i < ch_sum.length; i++) {\n var ch = (ch_sum.substring(i, i + 1));\n esum = ((esum * 1.0) + (ch * 1.0));\n }\n\t\t\t\n\n\t\t\tchecknum = (odd + esum);\n\t\t\t\n /** subtextact checknum from next highest multiple of 10\n to give check digit which is last digit in valid SIN*/\n\t\t\tif (checknum <= 10) {\n \t\t\t(checdigit = (10 - checknum));\n\t\t\t\t}\n\t\t\tif (checknum > 10 && checknum <= 20) {\n\t\t\t\t(checkdigit = (20 - checknum));\n\t\t\t\t}\n if (checknum > 20 && checknum <= 30) {\n\t\t\t\t(checkdigit = (30 - checknum));\n\t\t\t\t}\n if (checknum > 30 && checknum <= 40) {\n\t\t\t\t(checkdigit = (40 - checknum));\n\t\t\t\t}\n if (checknum > 40 && checknum <= 50) {\n\t\t\t\t(checkdigit = (50 - checknum));\n\t\t\t\t}\n if (checknum > 50 && checknum <= 60) {\n\t\t\t\t(checkdigit = (60 - checknum));\n\t\t\t\t}\n\t\t\t\t\t\t\n if (checkdigit != lastdigit) {\n \t document.getElementById(inputfield).innerHTML = \"<span style='color:red'>\"+sin+\"*is an invalid SIN; \\nCheck digit incorrect!\\nShould be: .</span>\";\n //alert(sin + \" is an invalid SIN; \\nCheck digit incorrect!\\nShould be: \" + checkdigit);\n //history.go(0);\n return false;\n }\t\t\t\t\t \t\t\t\n\t \treturn true;\n\t}", "function pOdValidator(num) {\n if (num % 2 === 0) {\n return \" è un numero pari, quindi hanno vinto i pari!\";\n } else {\n return \" è un numero dispari, quindi hanno vinto i dispari!\";\n }\n }", "function ValidNum(e){\n tecla = (document.all) ? e.keyCode : e.which;\n //Tecla de retroceso para borrar, siempre la permite\n if (tecla==8 || tecla==0){\n //console.log('entro al if, deberia devolver un true');\n return true;\n }\n \n // Patron de entrada, en este caso solo acepta numeros\n patron =/[0-9]/;\n tecla_final = String.fromCharCode(tecla);\n return patron.test(tecla_final);\n }", "function ValidaSoloNumeros() \n\t{\n \t\tif ((event.keyCode < 48) || (event.keyCode > 57)) \n \t\tevent.returnValue = false;\n\t}", "function soloNumeros(evt){\n\tevt = (evt) ? evt : window.event\n var charCode = (evt.which) ? evt.which : evt.keyCode\n if (charCode > 31 && (charCode < 48 || charCode > 57)) {\n status = \"This field accepts numbers only.\"\n return false\n }\n status = \"\"\n return true\n}", "function validarCedula(elemento)\n{ \n if(elemento.value.length > 0 && elemento.value.length < 11){\n var codigA = elemento.value.charCodeAt(elemento.value.length-1)\n if((codigA >= 48 && codigA <= 57)){\n }else {\n elemento.value = elemento.value.substring(0, elemento.value.length-1)\n }\n }else{\n elemento.value = elemento.value.substring(0, elemento.value.length-1)\n }\n if (elemento.value.length == 10) {\n if((elemento.value.substring(0,2)>=1)||(elemento.value.substring(0,2)<=24)){\n //Suma impares\n var pares = 0;\n var numero =0;\n for (var i = 0; i< 4; i++) {\n numero = elemento.value.substring(((i*2)+1),(i*2)+2);\n numero = (numero * 1);\n if( numero > 9 ){ var numero = (numero - 9); }\n pares = pares + numero; \n }\n var imp=0;\n numero = 0\n for (var i = 0; i< 5; i++) {\n var numero = elemento.value.substring((i*2),((i*2)+1));\n var numero = (numero * 2);\n if( numero > 9 ){ var numero = (numero - 9); }\n imp = imp + numero; \n }\n var sum = pares + imp;\n aux = (''+sum)[0];\n var di = aux.substring(0,1);\n di++;\n di = di *10;\n numero = (di - sum);\n if (numero == (elemento.value.substring(9,10))) {\n document.getElementById('mensaje1').innerHTML='' ; \n elemento.style.border = '2px greenyellow solid';\n return true;\n }else{\n document.getElementById('mensaje1').innerHTML = 'Cedula es Incorrecta'; \n elemento.style.border = '2px red solid';\n return false;\n }\n }\n }else{\n document.getElementById('mensaje1').innerHTML = 'Cedula es Incorrecta'; \n elemento.style.border = '2px red solid';\n return false;\n }\n}", "function isValidCard(input){\n // Variable que contiene los numeros invertidos\n var array=[];\n // Contiene los numeros de posiciones impares y pares\n var newArr=[];\n //Inicializa la suma en 0\n var sum=0;\n //Se invierte los números del input y lo almacenamos en array\n for(var i=input.length-1;i>=0;i--){\n array.push(input[i]);\n\n }\n for(var j=0;j<array.length;j++){\n //multiplicamos los numeros en posiciones impares contando desde 0\n if(j%2===1){\n var multipli=array[j]*2;\n // Se evalua si el numero es mayor igual a 10\n if(multipli>=10){\n // Se obtiene el digito de la decena\n var div=Math.floor(multipli/10);\n // Se obtiene el digito de la unidad\n var resi=multipli%10;\n // Se suma los digitos del numero\n var newNum=div+resi;\n // se colocan en el newArray\n newArr.push(newNum);\n }\n else{\n //si no es mayor a 10, se coloca en el newarray\n newArr.push(multipli);\n }\n }\n //se coloca si no es una posicion par\n else{\n newArr.push(parseInt(array[j]));\n }\n }// la variable a analizar es newArr\n for(var k=0;k<newArr.length;k++){\n // se procede con la suma de todos los elementos en el newArray\n sum+=newArr[k];\n }\n // valida si la suma es divisible entre 10 para dar el mensaje de valido o no valido\n if(sum%10===0){\n return document.write ('tu número de tarjeta es válido');\n }\n else{\n return document.write('tu número de tarjeta es inválido');\n }\n\n}", "function controlIfValid(c1, c2){\r\n\tvar campo1 = getValueFormatless(c1);\r\n\tvar campo2 = getValueFormatless(c2);\r\n\tif (campo1 == 0){\r\n\t \tdocument.getElementById(c2).value='';\r\n\t \treturn;\r\n\t}\r\n\tif(campo1 <= campo2){\r\n\t\talert('El valor de la casilla '+ c2 + ' no puede ser mayor al valor de la casilla ' + c1);\r\n\t\tdocument.getElementById(c2).value = \"\";\r\n\t}\t\t\r\n}", "function controlIfValid(c1, c2){\r\n\tvar campo1 = getValueFormatless(c1);\r\n\tvar campo2 = getValueFormatless(c2);\r\n\tif (campo1 == 0){\r\n\t \tdocument.getElementById(c2).value='';\r\n\t \treturn;\r\n\t}\r\n\tif(campo1 <= campo2){\r\n\t\talert('El valor de la casilla '+ c2 + ' no puede ser mayor al valor de la casilla ' + c1);\r\n\t\tdocument.getElementById(c2).value = \"\";\r\n\t}\t\t\r\n}", "function soloNumeros(evt) {\r\n\t//Validar la existencia del objeto event \r\n\tevt = (evt) ? evt : event;\r\n\r\n\t//Extraer el codigo del caracter de uno de los diferentes grupos de codigos \r\n\tvar charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode\r\n\t\t\t: ((evt.which) ? evt.which : 0));\r\n\r\n\t//Predefinir como valido \r\n\tvar respuesta = true;\r\n\t\r\n\tif(charCode > 31 && (charCode < 48 || charCode > 57 ) &&\r\n\t\t\tcharCode != 37 && charCode != 39 && charCode != 8 && charCode != 46 ){\r\n\t\t\r\n\t\trespuesta = false;\r\n\t\treturn respuesta;\r\n\t}\r\n\t\r\n\t//Regresar la respuesta \r\n\treturn respuesta;\r\n}", "function comprobarNum( campo ,size ) {\n var exp = /^[0-9]*$/;\n if(!comprobarExpresionRegular(campo,exp,size)){//comprueba que la expresión enviada en telef sea cumplida por el campo enviado si no lo hace devuelve false\n return false;\n }else {\n campo.style.border = \"2px solid green\";\n return true;\n }\n}", "static identityNumber(form, field, settings) {\n let id = form[field];\n id = String(id).trim();\n if(settings.required && id.length > 0){\n if (id.length > 9 || isNaN(id)) return settings.errorMessage || 'מספר ת\"ז אינו תקין';\n id = id.length < 9 ? (\"00000000\" + id).slice(-9) : id;\n let valid = Array.from(id, Number).reduce((counter, digit, i) => {\n const step = digit * ((i % 2) + 1);\n return counter + (step > 9 ? step - 9 : step);\n }) % 10 === 0;\n \n if(!valid){\n return settings.errorMessage || 'מספר ת\"ז אינו תקין';\n }\n return null;\n }\n return null;\n }", "cpfvalidate(input, minValue) {\n let inputLength = input.value.length;\n\n let errorMessage = `Insira o CPF no padrão 000.000.000-00`;\n\n\n if(inputLength != minValue){\n this.printMessage(input, errorMessage);\n } \n }", "function validaDisponible(numero){ \n if (!/^([0-9])*$/.test(numero)||numero === \"\"){\n alert(\"[ERROR] Stock disponible invalido\");\n document.getElementById(\"disponible\").value= \"0\"; \n document.getElementById(\"disponible\").focus();\n }\n }", "function inputNumber (canEmpty, type, elementname) {\n var element = type + '[name=\"' + elementname + '\"]'\n var value = $(element).val()\n var returnValue\n if (canEmpty) {\n var regexIntOrEmpty = new RegExp(/^(\\s*|\\d+)$/)\n if (regexIntOrEmpty.test(value)) {\n resetinput(element)\n returnValue = false\n } else {\n inputwarning(element)\n returnValue = true\n }\n } else {\n var regexInt = new RegExp(/^\\d+$/)\n if (regexInt.test(value)) {\n resetinput(element)\n returnValue = false\n } else {\n inputwarning(element)\n returnValue = true\n }\n }\n return returnValue\n }", "function verifyInputs() {\n // Creacion de una expresion regular para verificar los inputs\n const reg = /^-?\\d+$/;\n\n // Verificacion de los inputs\n try {\n if (funcion === \"\") {\n throw new Error(\"Por favor escriba una función.\");\n }\n if (!reg.test(x_from)) {\n throw new Error(\n \"Por favor escriba un número entero en el valor de inicio de la integral.\"\n );\n }\n if (!reg.test(x_to)) {\n throw new Error(\n \"Por favor escriba un número entero en el valor final de la integral.\"\n );\n }\n if (!reg.test(cant_points)) {\n throw new Error(\n \"Por favor escriba un número entero para la cantidad de puntos a evaluar.\"\n );\n }\n } catch (error) {\n alert(error);\n return false;\n }\n\n // Pasar los inputs a integer\n x_from = parseInt(x_from);\n x_to = parseInt(x_to);\n cant_points = parseInt(cant_points);\n\n return true;\n }", "function mod(input, div){\n return (input % div + div) % div;\n}", "function validateInput(){\n\n}", "function comId(txt, input, invalid, interruptor) {\n if (txt == \"\") {\n interruptor = requiredForm(input, invalid, interruptor);\n }\n else if (!idVerify(txt)) {\n input.classList.add('is-invalid');\n invalid.innerText = \"Must be 8 characters\";\n interruptor = false;\n }\n else {\n input.value = convUpper(txt);\n }\n return interruptor;\n}", "function validate_input() {\n\tvar err = 0; // pocet chyb\n\tfor(let i = 0; i < 9; i++) {\n\t\tif(user_order[i] !== order[i])\n\t\t\terr++;\n\t}\n\t$('#errcount').val(err);// ukaz tlacitko odeslani a zvaliduj napred\n\t$('#dialogform1').toggleClass(\"disappear\"); // ukaz odesilaci formular\n}", "function SomenteNumeros(input)\r\n\t{\r\n\tif ((event.keyCode<48)||(event.keyCode>57))\r\n\t\tevent.returnValue = false;\r\n\t}", "function notCalled(input) {\n return input * 13;\n}", "function validarNumeros1(e){ \n \n tecla = e.keyCode || e.which; \n \n var apellido = window.document.getElementById(\"apellidos\");\n \n //valida que el campo no contenga numeros \n if(expre.test(apellido.value)==true){\n \n apellido.style.borderColor =\"red\";\n valApel = false;\n var aux = apellido.value.substring(apellido.value.length-1);\n var rempla = apellido.value.replace(aux,\"\");\n apellido.value=rempla;\n}\n //valida que el campo tenga el formato solicitado\n else if (expreL.test(apellido.value)==true){\n apellido.style.borderColor =\"blue\";\n valApel = true;\n}\n else{\n apellidos.style.borderColor =\"red\";\n valApel = false;\n}\n}", "checkValidate(member){\n\t\tlet a = $('#input_membership').val();\n\t\tlet b = a.toString();\n\t\tlet c = 0;\n\t\n\t\tfor (var i = 0; i < b.length; i++){\n\t\t\tlet l = 6-i;\n\t\t\tc += Number(b[i]) * l ; \n\t\t}\n\t\n\t\tif ((c % 11) !== 0 || b.length !== 6){\n\t\t\t$('#error02').show();\n\t\t\treturn false\n\t\t}\n\t\n\t\telse if ((c % 11) === 0 && b.length === 6){\n\t\t\t$('#error02').hide();\n\t\t\treturn true\n\t\t}\n\n\t}", "function DigitosNegativos(e, field) {\n var teclaPulsada = window.event ? window.event.keyCode : e.which;\n var valor = field.value;\n\n if (teclaPulsada == 08 || (teclaPulsada == 46 && valor.indexOf(\".\") == -1) || (teclaPulsada == 45 && valor.indexOf(\"-\") == -1)) return true;\n\n return /^-?\\d/.test(String.fromCharCode(teclaPulsada));\n}", "function checkCIN() {\n\tvar CIN = document.getElementById(\"cin\").value;\n\tvar onlyNumbers = /^[0-9]+$/;\n\t//If CIN is not entered, set it to 0000000000\n\tif (CIN.length == 0) {\n\t\tCIN = \"000000000\";\n\t\t}\n\telse if (!(CIN.length == 9) || !(onlyNumbers.test(CIN))) {\n\t\tdocument.getElementById(\"Error\").innerHTML = \"Your CIN must be 9 digits\";\n\t}\n\telse {\n\t\tdocument.getElementById(\"Error\").innerHTML = \"\";\n\t}\n}", "function primer() {\r\n if (numeross(0)){\r\n validar(soloN());\r\n }else if (letrass(0)) {\r\n validar(soloL());\r\n }else {\r\n validar(soloS());\r\n }\r\n}", "function angkaValid2(input,info,poin){\n\t\tvar n = $('#'+input).val();\n\n\t\tif($('#'+input).val()!=$('#'+input).val().replace(/[^0-9.]/g,'')){\n\t\t\t$('#'+input).val($('#'+input).val().replace(/[^0-9.]/g,''));\n\n\t\t\t$('#'+info).html('<span class=\"label label-important\"> hanya angka</span>').fadeIn();\n\t\t\tsetTimeout(function(){\n\t\t\t\t$('#'+info).fadeOut();\n\t\t\t},1000);\n\t\t}else{\n\t\t\tif(n<1 || n>5){\n\t\t\t\t$('#'+input).val('');\n\t\t\t\t$('#'+info).html('<span class=\"label label-important\"> antara 1 - 5</span>').fadeIn();\n\t\t\t\tsetTimeout(function(){\n\t\t\t\t\t$('#'+info).fadeOut();\n\t\t\t\t},1000);\n\t\t\t}else{\n\t\t\t\t//rumus pembagian poin ketua = (60% * poin) , anggota = (40% * poin) / n\n\t\t\t\tvar poinx = (40/100 * parseFloat(poin) )/parseInt(n);\n\t\t\t\t$('#poinTB').val(poinx.toFixed(2));\n\t\t\t}\n\t\t}\n\t}", "check(campo) {\n //Condicional para saber si existe y que sea != a vacio\n if (campo && campo !== '') {\n if (campo !== 'isbn') {\n return () => {\n return true\n }\n } else {\n return () => {\n let isbn = this.isbn,\n partesIsbn = isbn.split('-'),\n nPartes = partesIsbn.length\n if (nPartes !== 5) {\n return false\n } else {\n let valido = true\n for (let i = 0; i < nPartes; i++) {\n let estaParte = partesIsbn[i]\n if (!/^([0-9])*$/.test(estaParte)) {\n valido = false\n break\n }\n }\n return valido\n }\n }\n }\n } else {\n return () => {\n return false\n }\n }\n }", "function passNumFunc() {\n var p, z; //t= \"paragraph\", z= змінна.\n p = document.getElementById('pasword-num');\n p.innerHTML = \"\";\n z = document.getElementById('pasNum-put').value;\n try {\n if (z == \"\") throw \"is empty!\";\n if (isNaN(z)) throw \"is not a number!\";\n z = Number(z);\n if (z <= 7) throw \"is too low!\";\n if (z >= 11 ) throw \"is too height!\";\n if (z === 8) throw getPassNum8();\n if (z === 9) throw getPassNum9();\n if (z === 10) throw getPassNum10();\n } catch (err) {\n p.innerHTML = err;\n } finally {\n document.getElementById('pasNum-put').value=\"\";\n }\n}", "validateInput(char) {\n if ((new RegExp(`^${'(\\xCF*[0-9]{2}\\xCF*)'}+$`)).test(char)) {\n return undefined;\n }\n else {\n return 'Supports even number of numeric characters (00-99).';\n }\n }", "function isValidCurso(formname){\n \n var varCurso = document.forms[formname][\"curso\"].value; //Obtenemos los datos introducidos en el input curso\n \n if(varCurso.length == 0){\n var x= document.getElementById(\"curso\");\n x.innerHTML=\"Campo vacio\";\n return false;\n }\n varCurso=varCurso.trim();//quitamos los posibles espacios en blancos de los <--extremos-->\n varCurso= varCurso.replace(/ /g,' ');//sustituimos los posibles múltiples espacios entre palabras por solamente uno\n \n var x= document.getElementById(\"curso\");\n if(!/^[1-4][a-hA-H]$/.test(varCurso)){//Si los datos introducidos no cumplmen \"nl\", siendo \"n\" un número entre 1 y 4 y \"l\" una letra en a-h o A-H\n x.innerHTML=\"Error: nº curso debe estar entre 1 y 4, letra entre A y H\";\n return false; \n }\n \n x.innerHTML=\"\"; //Si no hay fallo en el parrafo anexo al input no se pone nada\n document.forms[formname][\"curso\"].value=varCurso; //refrescamos los datos introducimos en el campo curso pero ahora sin espacios en blanco inválidos.\n return true;\n}", "function verifyInt(input)\n{\n var x = parseInt(input.value, 10);\n if (isNaN(x) || x < 0) {\n input.value = \"\";\n input.focus();\n } else\n gasUse();\n return;\n}", "function isValidCard(){\n\t\n\tvar result=[];\n\tvar result=numbers.reverse();//el reverse lo coloque porque sirve para invertir los elementos\n\t//tngo que multiplicar cada casilla par(luhn)\n\tfor(var i=0; i<numbers.length; i++){ \n\t if(result==\"\"){ // puse \"\", porque el usuario no puede ingresar un campo vacío\n\t alert(\"tarjeta inválida\");\n } else{\n\t return alert(\"tarjeta válida\");\n\n}\n}\n}", "function validarArticulosModificacion()\n{\n\tvar usuario = $(\"#nombreArticulo\");\n\tvar reg = /^[A-Za-z0-9 ]{4,25}$/;\n\n\tvar match = usuario.val().match(reg);\n\tif (!match) \n\t{\n\t\tevent.preventDefault();\n\t\t$(\"#errorModificacionNombre\").siblings().addClass('hidden');\n\t\t$(\"#errorModificacionNombre\").removeClass('hidden');\n\t\treturn false;\n\t}\n\t\n\tvar stockInicial = $(\"#stockArticulo\");\n\tif (stockInicial.val()<1) {\n\t\t$(\"#errorModificacionStock\").siblings().addClass('hidden');\n\t\t$(\"#errorModificacionStock\").removeClass('hidden');\n\t\tevent.preventDefault();\t\n\t\treturn false;\t\n\t}\n\n\tif (isNaN(stockInicial.val())) {\n\t\t$(\"#errorModificacionStock\").siblings().addClass('hidden');\n\t\t$(\"#errorModificacionStock\").removeClass('hidden');\n\t\tevent.preventDefault();\t\n\t\treturn false;\n\t}\n\t$( \"#erroresModificacion\" ).find( \"*\" ).addClass('hidden');\n\t\n}", "function validateInput(input) {\n\tif(input.length != 4) {\n setMessage(\"You must enter <b class='text-info'>4</b> Digits\");\n return false;\n }\n return true;\n}", "function validInput(input) {\n return isInteger(input) && input > 0\n}", "function controlModulo() {\n\n\treturn true;\n}", "function numerico(campo)\n\t{\n\tvar charpos = campo.value.search(\"[^0-9]\");\n if (campo.value.length > 0 && charpos >= 0)\n\t\t{\n\t\tcampo.value = campo.value.slice(0, -1);\n\t\tcampo.focus();\n\t return false;\n\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\treturn true;\n\t\t\t\t}\n\t}", "function validaMinimo(numero){ \n if (!/^([0-9])*$/.test(numero)||(numero === \"\")){\n alert(\"[ERROR] Stock minimo invalido\");\n document.getElementById(\"minimo\").value=\"0\"; \n document.getElementById(\"minimo\").focus();\n }\n }", "function validarSoloNumeros(evento) {\n tecla = (document.all) ? evento.keyCode : evento.which; // con document.all verifica si es IE\n\t // o FireFox. Según lo que sea, obtiene\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // el codigo de la tecla con la \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // instruccion correspondiente\n\tif (tecla==8) return true; // para que pueda hacer backspace\n if (tecla==0) return true; // para que pueda pasar a otro campo con TAB\n patron =/\\d/; // solo acepta numeros\n te = String.fromCharCode(tecla); // convierte el char a codigo ASCII\n\treturn patron.test(te); // compara con el patron y devuelve true o false\n}", "function controlModulo() {\n\n return true;\n}", "function validarNumeros(elemento){\n if(elemento.value.length>0){\n var miAscii = elemento.value.charCodeAt(elemento.value.length-1)\n console.log(miAscii)\n if(miAscii >=48 && miAscii <= 57){ //valida solo numeros entre 0 y 9\n return true\n }else{\n elemento.value = elemento.value.substring(0, elemento.value.length-1)\n return false\n }\n }else{\n return false\n }\n}", "function validateEquipmentNo(oSrc, args) {\n var str = trimAll(args.Value);\n if (str.length != 11) {\n oSrc.errormessage = \"Invalid Equipment No Format. Must 4-Alphabets, 6-Numeric, 1 Checkdigit\";\n args.IsValid = false;\n return;\n }\n var UnitIDA = str.substr(0, 4).toUpperCase();\n var UnitIDN = str.substr(4, 6);\n if (trimAll(UnitIDN).length != 6) {\n args.IsValid = false;\n return;\n }\n // var oParent = document.getElementById(oSrc.controltovalidate);\n var oParent = document.getElementById(getIAttribute(oSrc, \"controltovalidate\"));\n if (typeof (oParent.lpCheckDigit) == 'undefined' || ((oParent.lpCheckDigit == 'false' || oParent.lpCheckDigit == 'true') && str.length == 11))//if (typeof(oParent.lpCheckDigit)=='undefined' || oParent.lpCheckDigit=='false')\n {\n if (typeof (oParent.lpCheckDigit) == 'undefined')\n oParent.lpCheckDigit = \"false\";\n var UnitIDC = str.substr(10, 1);\n }\n\n //error message format.\n var msg = \"\";\n var spmsg = \"\"; // this is specific error message.\n // msg = \"<ul type=square><li>\";\n // msg += \"4 Alpha characters - mandatory.</li>\";\n // msg += \"<li>6 digit Number - mandatory.</li>\";\n // msg += \"<li>1 check digit - optional.</li></ul>\";\n\n if (str == \"\" || str.length < 10) {\n spmsg = \"Invalid Equipment No Format. Must 4-Alphabets, 6-Numeric, 1 Checkdigit<br>\";\n spmsg += msg;\n oSrc.errormessage = spmsg;\n args.IsValid = false;\n return;\n }\n else if ((UnitIDA.charCodeAt(0) < 65 || UnitIDA.charCodeAt(0) > 91) || (UnitIDA.charCodeAt(1) < 65 || UnitIDA.charCodeAt(1) > 91) || (UnitIDA.charCodeAt(2) < 65 || UnitIDA.charCodeAt(2) > 91) || (UnitIDA.charCodeAt(3) < 65 || UnitIDA.charCodeAt(3) > 91)) {//alpha check.\n spmsg = \"Invalid Equipment No Format. Must 4-Alphabets, 6-Numeric, 1 Checkdigit<br>\";\n spmsg += msg;\n oSrc.errormessage = spmsg;\n args.IsValid = false;\n return;\n }\n else if (isNaN(UnitIDN)) {//numeric check.\n spmsg = \"Invalid Equipment No Format. Must 4-Alphabets, 6-Numeric, 1 Checkdigit<br>\";\n spmsg += msg;\n //alert(spmsg);\n oSrc.errormessage = spmsg;\n args.IsValid = false;\n return;\n }\n else if ((isNaN(UnitIDC) || UnitIDC == \"\") && oParent.lpCheckDigit == 'false') {//Check Digit\n spmsg = \"Invalid Equipment No Format. Must 4-Alphabets, 6-Numeric, 1 Checkdigit<br>\";\n spmsg += msg;\n //alert(spmsg);\n oSrc.errormessage = spmsg;\n args.IsValid = false;\n return;\n }\n\n else if (oParent.lpCheckDigit == 'true') {\n oParent.value = str.substr(0, 4).toUpperCase() + str.substr(4, 6) + getCheckSum(str.substr(0, 10));\n args.IsValid = true;\n return;\n }\n else {\n //oParent.value=str.substr(0,4).toUpperCase() + str.substr(4,6) + getCheckSum(str.substr(0,10));\n args.IsValid = true;\n return;\n }\n}", "function formatearmil(input)\n{\n var num = input.value.replace(/\\./g,'');\n if(!isNaN(num)){\n if (num>0) {\n num = num.toString().split('').reverse().join('').replace(/(?=\\d*\\.?)(\\d{3})/g,'$1.');\n num = num.split('').reverse().join('').replace(/^[\\.]/,'');\n input.value = num;\n }else{\n alert('Por favor ingrese mayor a cero');\n input.value = input.value.replace(/[^\\d\\.]*/g,'');\n }\n }else{\n alert('Solo se permiten numeros');\n input.value = input.value.replace(/[^\\d\\.]*/g,'');\n }\n}", "function enterosExtremos(n) {\n\tpermitidos = /[^0-9]/;\n\tcadena = n.value;\n\tband = false;\n\tfor (i = 0; i < cadena.length; i++) {\n\t\tletra = cadena.substring(i, i + 1);\n\t\tif (permitidos.test(letra)) {\n\t\t\tcadena2 = cadena;\n\t\t\tcadena = cadena2.replace(letra, \"\");\n\t\t\tband = true;\n\t\t}\n\t}\n\tvar cont = 0;\n\tfor (i = 0; i < cadena.length; i++) {\n\t\tletra = cadena.substring(i, i + 1);\n\t\tif (letra === \"-\") {\n\t\t\tcont++;\n\t\t\tif (cont > 1) {\n\t\t\t\tcadena2 = cadena;\n\t\t\t\tcadena = cadena2.substring(0, cadena.length - 1);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tif (band === true) {\n\t\tn.value = cadena;\n\t}\n}", "function customValidation(input){\n return input;\n \n}", "passwordvalidate(input) {\n\n // Transformar a string em array\n let carac_array = input.value.split(\"\");\n\n let uppercase = 0;\n let numbers = 0;\n\n for (let i = 0; carac_array.length > i; i++) {\n if (carac_array[i] === carac_array[i].toUpperCase() && isNaN(parseInt(carac_array[i]))) {\n uppercase++;\n } else if (!isNaN(parseInt(carac_array[i]))) {\n numbers++;\n }\n\n }\n if (uppercase === 0 || numbers === 0) {\n let mensagem_error = `A senha precisa de um caractere maiúsculo e um número`;\n\n this.imprimirMensagem(input, mensagem_error);\n }\n\n }", "function dac_ValidarNumero(num, id){\n\t\"use strict\";\n\tvar bruto, dto, total_neto, id_nro = 0;\n\tif(isNaN(num)){\n\t\tdocument.getElementById(id).value = \"\";\n\t\talert(\"Debe ingresar un valor numérico.\");\n\t}\n\n\tif(id.substring(0, 13) === \"importe_bruto\"){\n\t\tid_nro \t= id.substring(13, id.length);\n\t\tif (document.getElementById('importe_dto'+id_nro).value === '0'){\n\t\t\tdocument.getElementById('importe_neto'+id_nro).value = num;\t\t\t\t\t\n\t\t} else {\t\n\t\t\tbruto = num;\n\t\t\tdto = document.getElementById('importe_dto'+id_nro).value;\t\n\t\t\ttotal_neto = bruto - ((bruto * dto) / 100);\n\t\t\tdocument.getElementById('importe_neto'+id_nro).value = total_neto;\n\t\t}\t\t\n\t\tdac_Calcular_Diferencia();\t\t\t\n\t}\n\n\tif(id.substring(0, 11) === \"importe_dto\"){\n\t\tid_nro \t= id.substring(11, id.length);\n\t\tdto = num;\n\t\tbruto = document.getElementById('importe_bruto'+id_nro).value;\t\n\t\tif (dto !== \"\") {\n\t\t\ttotal_neto = bruto - ((bruto * dto) / 100);\n\t\t\tdocument.getElementById('importe_neto'+id_nro).value = total_neto;\n\t\t} else {\n\t\t\tdocument.getElementById('importe_neto'+id_nro).value = bruto;\n\t\t}\n\t\tdac_Calcular_Diferencia();\n\t}\n\n\tif((id.substring(0, 13) === \"pago_efectivo\") || (id.substring(0, 13) === \"pago_transfer\") || (id.substring(0, 14) === \"pago_retencion\") || (id.substring(0, 15) === \"pagobco_importe\")){\t\n\t\tdac_Calcular_Diferencia();\n\t}\t\t\t\t\t\t\t\t\n}", "function esPar(numerito) { \n //Si se hace una division para dos se recibe un entero o decimal\n if (numerito % 2 === 0) { //=== 0 quiere decir que no da reciduo\n return true;\n } else {\n return false;\n }\n}", "function validarFormulario(){\t\n\tvar valido = true ;\n\tvar valRecargaTemp = valorRecarga.value.replace(\",\",\"\");\n\tif( valRecargaTemp == 0 || valRecargaTemp == \"\" || multiploDeMil(valRecargaTemp)){\n\t\tvalido = false;\n\t\tvalorRecarga.blur();\n\t\tvalorRecarga.classList.add(\"is-invalid-input\");\n\t\tdocument.getElementById(\"icondollar\").classList.add(\"is-invalid-label\");\n\t\tdocument.getElementById(\"error-valor\").style.display = 'block';\n\t\t\n\t}\n\tconsole.log(numeroCelular.value < 10);\n\tif(numeroCelular.value.length < 10){\n\t\tvalido = false;\n\t\tnumeroCelular.blur();\n\t\tnumeroCelular.classList.add(\"is-invalid-input\");\n\t\tdocument.getElementById(\"iconmobile\").classList.add(\"is-invalid-label\");\n\t\tdocument.getElementById(\"error-numero\").style.display = 'block';\n\n\t}\n\t\n\treturn valido;\n}", "function igual(element,num,form){\n\tNumer=parseInt(element.value);\n\t//alert(\"igual=\"+element.value.length);\n\tif (!isNaN(Numer)){\n\t\tif(element.value.length != num){ \n\t\t\t//alert(\"noMayor=\"+element.name);\n\t\t\tif(element.name == \"num_tel_fijo1\")\n\t\t\t\tIndex = 10;\t\t\n\t\t\tif(element.name == \"num_tel_fijo2\")\n\t\t\t\tIndex = 11;\t\t\n\t\t\tif(element.name == \"num_celular\")\n\t\t\t\tIndex = 12;\t\n\t\t\telement.value=\"\";\n\t\t\tform.elements[Index].focus();\n\t\t\talert(\"El n\\u00FAmero de caracteres debe ser igual a \"+num);\n\t\t}\n\t}\n}", "function modulusNumbers() {\r\n const result = document.getElementById(\"addResult\");\r\n\r\n // Calculating Multiplication\r\n const output = parseInt(num1.value / num2.value);\r\n const modulusResult = num1.value - num2.value * output;\r\n if (isFinite(modulusResult)) {\r\n result.value = modulusResult;\r\n // Hide results\r\n document.getElementById(\"result\").style.display = \"block\";\r\n // Show LOader\r\n document.getElementById(\"loading\").style.display = \"none\";\r\n } else {\r\n showError(\"Please check your Numbers..\");\r\n }\r\n}", "function checkSplitNumber(element)\r\n{\r\n\tvar isNumeric = vn(element);\r\n if (isNumeric)\r\n {\r\n \t if (parseInt(element.value) <= 1)\r\n \t {\r\n \t\t alert(\"Enter value greater than 1.\")\r\n element.value = '';\r\n \t\t return false;\r\n \t }\r\n }\r\n}", "function imparPar() {\n let txtNumber = Number(document.querySelector(\"#txtNumber\").value);\n\n if (txtNumber % 2 == 0) {\n resultado.innerHTML = \"O número é PAR\";\n } else {\n resultado.innerHTML = \"O número é IMPAR\";\n }\n}", "processSid() {\n let input = this.sid\n resetError(input)\n this.changed = true\n\n if (isEmpty(input)) {\n this.valid = false\n } else if (isNumber(input)) {\n this.valid = false\n } else if (exact(input, 10)) {\n this.valid = false\n } else {\n input.success = true\n this.valid = true\n }\n }", "function customValidation(input) { \n}", "function validNumber(input){\r\n\treturn (input.length == 10 || input[0] == \"0\");\r\n}", "validateInput(value) {\n if (value.search(/^[0-9]{13}$/) !== -1 && Number(value[12]) === this.checkSumData(value)) {\n return undefined;\n }\n else if (value.search(/^[0-9]{12}$/) !== -1) {\n value += this.checkSumData(value);\n this.value = value;\n return undefined;\n }\n else {\n return 'Accepts 12 numeric characters.';\n }\n }", "handleInputChange(event) {\n let input = event.target.value;\n if (!Number(input)) {\n this.setState({ valid: false });\n return;\n }\n this.setState({ input: event.target.value });\n this.setState({ valid: true });\n }", "function EntryCheckForNumbers() {\r\n let userEntry ; \r\n do {userEntry = +prompt('attention please - only Numbers');} \r\n while (userEntry !== +userEntry || userEntry === 0); \r\n console.log ('Thank you very much');\r\n return userEntry;\r\n}", "function validateInputNumber(input) {\n\tinput.value = formatNumber(input.value);\n\tif (!isNumber(input.value)) {\n\t\tinput.value = '';\n\t}\n}", "function forth(req, res) {\n let number = req.body.pattern;\n\n // check the input validations\n if (!Number.isInteger(number) && Number.isInteger(req.body.problem)) {\n return res.status(400).send({\n message: \"Pattern should be Number\",\n status: 400\n });\n } else {\n let arr = [];\n let i = 0;\n let revbinary = \"\";\n /*\n Condition for Binary element\n */\n while (number > 0) {\n arr[i] = number % 2;\n revbinary = arr[i] + revbinary;\n number = Math.floor(number / 2);\n i++;\n } while (revbinary.length < 7) {\n revbinary = '0' + revbinary;\n }\n\n // check palindrome\n let palCheck = palindrome(revbinary);\n const result = `${revbinary}, ${palCheck ? 'Yes' : 'NO'}`;\n return res.status(200).send({\n message: result,\n status: 200,\n problem: \"Binay form & Palindrome or not\"\n });\n }\n}", "function Valida_Rut(Objeto)\n\n{\n\n var tmpstr = \"\";\n\n var intlargo = Objeto.value;\n\n if (intlargo.length > 0)\n\n {\n\n crut = Objeto.value;\n\n largo = crut.length;\n\n if (largo < 2)\n\n {\n\n sweetAlert(\"ERROR\", \"RUN INVALIDO!\", \"error\");\n\n //Objeto.focus();\n\n return false;\n\n }\n\n for (i = 0; i < crut.length; i++)\n if (crut.charAt(i) !== ' ' && crut.charAt(i) !== '.' && crut.charAt(i) !== '-')\n\n {\n\n tmpstr = tmpstr + crut.charAt(i);\n\n }\n\n rut = tmpstr;\n\n crut = tmpstr;\n\n largo = crut.length;\n\n\n\n if (largo > 2)\n rut = crut.substring(0, largo - 1);\n\n else\n rut = crut.charAt(0);\n\n\n\n dv = crut.charAt(largo - 1);\n\n\n\n if (rut === null || dv === null)\n return 0;\n\n\n\n var dvr = '0';\n\n suma = 0;\n\n mul = 2;\n\n\n\n for (i = rut.length - 1; i >= 0; i--)\n\n {\n\n suma = suma + rut.charAt(i) * mul;\n\n if (mul === 7) {\n\n mul = 2;\n\n } else {\n\n mul++;\n }\n\n }\n\n\n\n res = suma % 11;\n\n if (res === 1) {\n dvr = 'k';\n\n } else if (res === 0) {\n dvr = '0';\n\n } else {\n\n {\n\n dvi = 11 - res;\n\n dvr = dvi + \"\";\n\n }\n }\n\n\n\n if (dvr !== dv.toLowerCase())\n\n {\n\n\n sweetAlert(\"ERROR!!!\", \"RUN INCORRECTO!\", \"error\");\n }\n //Objeto.focus();\n\n return false;\n\n }\n\n\n\n // Objeto.focus();\n\n return true;\n\n}", "function angkaValid(input,info){\n\t\tvar x = $('#'+input).val();\n\n\t\tif($('#'+input).val()!=$('#'+input).val().replace(/[^0-9.]/g,'')){\n\t\t\t$('#'+input).val($('#'+input).val().replace(/[^0-9.]/g,''));\n\n\t\t\t$('#'+info).html('<span class=\"label label-important\"> hanya angka</span>').fadeIn();\n\t\t\tsetTimeout(function(){\n\t\t\t\t$('#'+info).fadeOut();\n\t\t\t},1000);\n\t\t}\n\t}", "processPhone() {\n let input = this.phone\n resetError(input)\n this.changed = true\n\n if (isEmpty(input)) {\n this.valid = false\n } else if (isNumber(input)) {\n this.valid = false\n } else if (exact(input, 11)) {\n this.valid = false\n } else {\n input.success = true\n this.valid = true\n }\n }", "function validaCampoNumeroInSave(Nombre, ActualLement, rango, decimal) {\n var cValue = $('#' + ActualLement + '_txt_' + Nombre).val();\n var TextErr = false;\n\n if (cValue !== null && cValue !== '') {\n\n if (!decimal) {\n _regEx = new RegExp(\"^[0-9]+$\");\n if (!_regEx.test(cValue)) {\n redLabel_Space(Nombre, 'Solo se permiten caracteres numéricos', '#' + ActualLement);\n ShowAlertM('#' + ActualLement, null, null, true);\n TextErr = true;\n }\n } else {\n if (!cValue.includes('.')) {\n redLabel_Space(Nombre, 'Solo se permiten decimales', '#' + ActualLement);\n ShowAlertM('#' + ActualLement, null, null, true);\n TextErr = true;\n }\n }\n\n if (rango !== undefined && Array.isArray(rango)) {\n if (cValue < rango[0]) {\n redLabel_Space(Nombre, 'El rango mínimo deber se de ' + rango[0], _G_ID_);\n ShowAlertM('#' + ActualLement, null, null, true);\n TextErr = true;\n } else {\n if (cValue > rango[1]) {\n redLabel_Space(Nombre, 'El rango máximo deber se de ' + rango[1], _G_ID_);\n ShowAlertM('#' + ActualLement, null, null, true);\n TextErr = true;\n }\n }\n }\n\n\n if (TextErr) {\n errorIs[Nombre] = true;\n } else {\n errorIs[Nombre] = false;\n }\n }\n}", "function valida_difito(rut)\n\t{\n\t\tvar tmpstr=\"\";\n\t\tvar tmprut, i;\n\t\tvar digito = \"\";\n\t\t\n\t\ttmprut = rut.value;\n\t\t\n\t\tif ( tmprut.length >= 9 && tmprut.length <= 10)\n\t\t{\n\t\t\tfor ( i=0; i < tmprut.length; i++ ) \n\t\t\t{\n\t\t\t\tif ( tmprut.charAt(i) != ' ' && tmprut.charAt(i) != '.' && tmprut.charAt(i) != '-' ) \n\t\t\t\t{\n\t\t\t\t\ttmpstr = tmpstr + tmprut.charAt(i); //obtengo el rut sin caracteres... osea: 111111111\n\t\t\t\t}\n\t\t\t}\n\t\t\ttmprut = \"\";\n\t\t\tlargo_rut = tmpstr.length; \t\n\t\t\n\t\t\tfor ( i=0; i < largo_rut-1; i++ )\n\t\t\t{\n\t\t\t\ttmprut = tmprut + tmpstr.charAt(i); //obtengo el rut sin digito verificador\n\t\t\t}\n\t\t\tdigito= tmpstr.charAt(largo_rut-1);\t\t\t//obtengo el digito verificador\n\t\t\n\t\t\tvar dvr = '0';\n\t\t\tsuma = 0;\n\t\t\tmul = 2;\n\n\t\t\tfor (i= tmprut.length - 1 ; i >= 0; i--) \n\t\t\t{\n\t\t\t\tsuma = suma + tmprut.charAt(i) * mul;\n\t\t\t\tif (mul == 7)\n\t\t\t\t\tmul = 2;\n\t\t\t\telse\n\t\t\t\t\tmul++;\n\t\t\t}\n\n\t\t\tres = suma % 11;\n\t\t\tif (res==1)\n\t\t\t{\n\t\t\t\tdvr = 'k';\n\t\t\t}\n\t\t\telse if (res==0) \n\t\t\t{\n\t\t\t\tdvr = '0';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdvi = 11-res;\n\t\t\t\tdvr = dvi + \"\";\n\t\t\t}\n\t\t\tif (dvr != digito.charAt(0).toLowerCase()) \n\t\t\t{\n\t\t\t\talert(\"El RUT ingresado es inválido, ingreselo nuevamente\");\n\t\t\t\trut.value=\"\";\n\t\t\t\trut.focus();\n\t\t\t\treturn false; //El DV no concordo con el RUT.\n\t\t\t}\n\n\t\t\treturn true; //EL DV concordo con el RUT.\n\t\t}\n\t\telse if( tmprut.length = 0 )\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\talert(\"El RUT ingresado es inválido, ingreselo nuevamente\");\n\t\t\trut.value=\"\";\n\t\t\trut.focus();\n\t\t\treturn false;\n\t\t}\n\n\t}", "function numValidate(evt) {\n\n var theEvent = evt || window.event;\n var key = theEvent.keyCode || theEvent.which;\n key = String.fromCharCode( key );\n var regex = /[0-9]/;\n if( !regex.test(key) ) {\n theEvent.returnValue = false;\n if(theEvent.preventDefault) theEvent.preventDefault();\n }\n}", "function onlyNumeric() {\n //Get element id\n const idName = this.id;\n // Regex that checks if input has somethong that is not a digit\n const current_value = $(`#${idName}`).val();\n const re = new RegExp(/(\\D+)/gi);\n const match = re.exec(current_value);\n // Check match\n if (match != null) {\n // remove user input\n $(`#${idName}`).val(\"\");\n // Put error message\n $(`#${idName}_wi`).text(\"¡Sólo se admiten valores numéricos!\");\n $(`#${idName}_wi`).show();\n } else {\n // Hide error message\n $(`#${idName}_wi`).text(\"\");\n $(`#${idName}_wi`).hide();\n }\n}", "function comprobarCPSearch( campo) {\n var comprueba=/^[0-9]{1,5}$/i;\n\n if (campo.value.length <= 0) {// si el campo esta vacio se acepta como valido\n\n document.getElementById(campo.name+\"_error\").style.visibility = \"hidden\";\n campo.style.border = \"2px solid green\";\n return true;\n }else if(!comprobarExpresionRegular(campo,comprueba,5)){//comprueba que la expresión enviada en comprueba sea cumplida por el campo enviado si no lo hace devuelve false\n return false;\n }\n else {\n campo.style.border = \"2px solid green\";\n return true;\n }\n}", "function verifyCustomInput(input) {\n if (/^[0-9]*$/.test(\"\"+input.value) && (input.value!==\"\")){\n input.className = \"valid\";\n return true;\n }\n else {\n input.className = \"error\";\n input.value = \"\";\n return false;\n }\n}", "function campo_numerico() {\r\n\r\n if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;\r\n\r\n}", "function controlIfValid(c1, c2){\n\tvar campo1 = getValueFormatless(c1);\n\tvar campo2 = getValueFormatless(c2);\n\tif (campo1 == 0){\n\t \tdocument.getElementById(c2).value='';\n\t \treturn;\n\t}\n\tif(campo1 < campo2){\n\t\talert('El valor de la casilla '+ c2 + ' no puede ser mayor al valor de la casilla ' + c1);\n\t\tdocument.getElementById(c2).value = \"\";\n\t}\t\t\n}", "function simpleMod(inputVal) {\n // Check that the input value is a number and within the correct range\n if (inputVal < 0 || inputVal > 99999 || isNaN(inputVal)) {\n error(\"Please enter a number in the range of 0-99999\");\n // Return error\n return 1;\n }\n\n // Simple Mod Function\n var pos = inputVal % arr.size();\n\n jsav.umsg(\"Hash position = Input Value % Table Size\");\n jsav.umsg(\"Hash position = \" + inputVal + \" % \" + arr.size() + ' = ' + pos);\n\n // Process function with selected collision resolution\n determineResolution(inputVal, pos, false, true);\n\n // Return success\n return 0;\n }", "function validaClave() { /*Valida la clave*/\n var valor = document.getElementById(\"clave\").value;\n\n if (!(/^\\d{1}[a-zA-Z]{3}\\W{1}\\d{1}$/.test(valor))) {\n alert(\"La clave no es correcta. Ejemplo:7aHf$8\");\n document.getElementById(\"clave\").value = \"\"; /*Deja el Campo vacio*/\n document.getElementById(\"envio\").disabled = true; /*Deshabilita el boton envio*/\n return false;\n }\n else {\n\n return true;\n }\n}", "function verify(e) {\n with (top.document.forms[0].elements[e]) {\n if (value != '1'\n && value != '2'\n && value != '3'\n && value != '4'\n && value != '5'\n && value != '6'\n && value != '7'\n && value != '8'\n && value != '9')\n value = '';\n }\n return true;\n}", "function comprobarCP( campo) {\n var comprueba=/^[0-9]{5}$/i;\n\n if (campo.value.length <= 0) {// si el campo esta vacio se acepta como valido\n\n document.getElementById(campo.name+\"_error\").style.visibility = \"hidden\";\n campo.style.border = \"2px solid green\";\n return true;\n }else if(!comprobarExpresionRegular(campo,comprueba,5)){//comprueba que la expresión enviada en comprueba sea cumplida por el campo enviado si no lo hace devuelve false\n return false;\n }\n else {\n campo.style.border = \"2px solid green\";\n return true;\n }\n}", "function validMask(event) {\n\t\t\tvar actualValue = sd.inputVal(),\n\t\t\t\tkeyString = sd.getKeyCode(event);\n\t\t\t\t\n\t\t\tif (event.ctrlKey || event.altKey) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n if (event.type === eventsType.keydown.toString()) {\n\t\t\t\tif(typeof(keyString) === 'string') {\n\t\t\t\t\tswitch (options.regex.charAt(sd.getPosition())) {\n\t\t\t\t\t\tcase \"0\":\n\t\t\t\t\t\t\tif(sd.isNumeric(keyString)) {\n\t\t\t\t\t\t\t\treturn sd.callGetNextCharacter();\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \"S\":\n\t\t\t\t\t\t\tif(globalRegExpMay.test(keyString)) {\n\t\t\t\t\t\t\t\treturn sd.callGetNextCharacter();\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \"s\":\n\t\t\t\t\t\t\tif(globalRegExpMin.test(keyString)) {\n\t\t\t\t\t\t\t\treturn sd.callGetNextCharacter();\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\treturn keyString;\n\t\t\t\t}\n\t\t\t} else if (event.type === eventsType.blur.toString()) {\n\t\t\t\toldValue = sd.inputVal();\n\t\t\t}\n\t\t\t\n\t\t\tsd.callbacks(event);\n\t\t}", "function getInput() {\n var userInput = 0; // user input (initialization)\n var check = false; //flag (initialization)\n var message = 'Inserisci uno dei numeri visti in precedenza';\n\n userInput = parseInt(prompt(message));\n\n while (!check) {\n // input validation\n if (!checkInput(userInput)) {\n userInput = parseInt(\n prompt(\n 'Il numero inserito non è valido. Sono accettati solo numeri interi da 1 a 100'\n )\n );\n } else {\n // is the inpute a duplicate?\n if (!checkUserDuplicates(userInput)) {\n userInput = parseInt(prompt('Hai già inserito questo numero. Riprova'));\n } else {\n check = true;\n }\n }\n }\n\n return userInput;\n}", "function revisarDigito( dvr )\n{\ndv = dvr \"\"\nif ( dv != '0' && dv != '1' && dv != '2' && dv != '3' && dv != '4' && dv != '5' && dv != '6' && dv != '7' && dv != '8' && dv != '9' && dv != 'k' && dv != 'K')\n{\nalert(\"Debe ingresar un digito verificador valido\");\nwindow.document.form1.rut.focus();\nwindow.document.form1.rut.select();\nreturn false;\n}\nreturn true;\n}", "function inverso(){\n\tvar a = prompt(\"Escribe un número a continuación\", \"00156420\");\n\tif(a <=0 || a >0){ //Comprobar que realmente es un número\n\t\ta = a + \"\";\n\t\ta = a.split(\"\").reverse().join(\"\");\n\t\ta = parseInt(a) + \"\"; //Eliminar ceros en el extremo izquierdo, los que antes estaban en el izquierdo se mantienen\n\t\tdocument.write(\"El resultado de inversión es: \", a);\n\t}\n\telse{\n\t\tdocument.write(\"Nope, necesitabas introducir un número.\" ,\"<br />\");\n\t}\n\t/*a = a + \"\";\n\ta = a.split(\"\").reverse().join(\"\");*/ //Esto funciona para todo string o número con ceros a los extremos\n}", "somenteletras(input) {\n\n let re = /^[A-Za-z]+$/;\n\n let inputValue = input.value;\n\n let mensagem_error = `Este campo não aceita números nem caracteres especiais`;\n\n if (!re.test(inputValue)) {\n this.imprimirMensagem(input, mensagem_error);\n }\n\n }", "receiveInput(input) {\n input = input.toString();\n if (input.length > 2) {\n throw new Error(\"Invalid input received\");\n } else if (Calc._isNumberInput(input)) {\n this._handleNumberInput(input);\n } else if (Calc._isEqualInput(input)) {\n this._handleEqual();\n } else if (Calc._isResetInput(input)) {\n this._handleReset();\n } else if (Calc._isOperationInput(input)) {\n this._handleOperationInput(input);\n } else {\n throw new Error(\"Invalid input received\");\n }\n }", "function validar(n,v) {\n\tif( ( n % v ) == 0 )\n\t\treturn true;\n\telse\n\t\treturn false;\n}", "function NumReal(fld, milSep, decSep, e,tipo) {\nif (fld.value.length > 12){ \nreturn false; }\nvar sep = 0;\nvar key = '';\nvar i = j = 0;\nvar len = len2 = 0;\nvar strCheck = '0123456789-';\nvar aux = aux2 = '';\nif (tipo){\nvar whichCode = (window.Event) ? e.which : e.keyCode;\nif (whichCode == 13) return true; // Enter\nvar key = String.fromCharCode(whichCode); // Get key value from key code\nif (strCheck.indexOf(key) == -1) return false; // Not a valid key\n}\nlen = fld.value.length;\nfor(i = 0; i < len; i++)\nif ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;\naux = '';\nfor(; i < len; i++)\nif (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);\naux += key;\nlen = aux.length;\nif (len == 0) fld.value = '';\nif (len == 1) fld.value = '0'+ decSep + '0' + aux;\nif (len == 2) fld.value = '0'+ decSep + aux;\nif (len > 2) {\naux2 = '';\nfor (j = 0, i = len - 3; i >= 0; i--) {\nif (j == 3) {\naux2 += milSep;\nj = 0;\n}\naux2 += aux.charAt(i);\nj++;\n}\nfld.value = '';\nlen2 = aux2.length;\nfor (i = len2 - 1; i >= 0; i--)\nfld.value += aux2.charAt(i);\nfld.value += decSep + aux.substr(len - 2, len);\n}\nreturn false;\n}", "function validacionCampos(nombreCampo, valorCampo, tipoCampo) {\n\n var expSoloCaracteres = /^[A-Za-zÁÉÍÓÚñáéíóúÑ]{3,10}?$/;\n var expMatricula = /^([A-Za-z]{1}?)+([1-9]{2}?)$/;\n\n if (tipoCampo == 'select') {\n valorComparar = 0;\n } else {\n valorComparar = '';\n }\n\n //validamos si el campo es rellenado.\n if (valorCampo != valorComparar) {\n $('[id*=' + nombreCampo + ']').removeClass('is-invalid');\n\n //Aplicamos validaciones personalizadas a cada campo.\n if (nombreCampo == 'contenidoPagina_nombreMedico') {\n if (expSoloCaracteres.test(valorCampo)) {\n return true;\n } else {\n mostrarMensaje(nombreCampo, 'noDisponible');\n return false;\n }\n\n }\n else if (nombreCampo == 'contenidoPagina_apellidoMedico') {\n if (expSoloCaracteres.test(valorCampo)) {\n return true;\n } else {\n mostrarMensaje(nombreCampo, 'noDisponible');\n return false;\n }\n \n }\n else if (nombreCampo == 'contenidoPagina_especialidadMedico') {\n return true;\n\n }\n else if (nombreCampo == 'contenidoPagina_matriculaMedico') {\n\n if (expMatricula.test(valorCampo)) {\n\n $(\"[id*=contenidoPagina_matriculaMedico]\").off('keyup');\n $(\"[id*=contenidoPagina_matriculaMedico]\").on('keyup', function () {\n return validarMatriculaUnica($(this).val(), matAcomparar);\n });\n\n return validarMatriculaUnica($(\"[id*=contenidoPagina_matriculaMedico]\").val(), matAcomparar);\n } else {\n mostrarMensaje(nombreCampo, 'estructuraInc');\n return false;\n } \n }\n } else {\n mostrarMensaje(nombreCampo, 'incompleto');\n return false;\n }\n }" ]
[ "0.5763435", "0.5737794", "0.5683836", "0.5661459", "0.5640382", "0.56215405", "0.5608176", "0.5550166", "0.5526072", "0.55046415", "0.5495679", "0.5492356", "0.54776305", "0.54776305", "0.54729456", "0.54717577", "0.5460662", "0.545548", "0.5453171", "0.5432027", "0.54206365", "0.5408203", "0.5408203", "0.5404823", "0.54048175", "0.5401001", "0.54008085", "0.54000574", "0.5381647", "0.53732896", "0.53657097", "0.5362564", "0.534767", "0.5345152", "0.5329255", "0.53281206", "0.532109", "0.5319702", "0.53084326", "0.53082836", "0.53062606", "0.5299711", "0.5299272", "0.52986056", "0.5276224", "0.526413", "0.52576274", "0.5255338", "0.5246998", "0.52407056", "0.5237594", "0.5235137", "0.5222907", "0.52222246", "0.5215581", "0.5213368", "0.5211419", "0.5205097", "0.5203084", "0.5202051", "0.5196283", "0.5191664", "0.5188698", "0.5188017", "0.51832205", "0.5178988", "0.51736593", "0.51679707", "0.5166943", "0.5157186", "0.514452", "0.5140203", "0.5134353", "0.51265645", "0.5124771", "0.51241016", "0.5123385", "0.51177144", "0.5117503", "0.5112093", "0.5110738", "0.5103792", "0.5103681", "0.50957924", "0.5092898", "0.5090608", "0.5089988", "0.50876844", "0.5082033", "0.5082031", "0.50815403", "0.5080062", "0.50701374", "0.50696594", "0.5064832", "0.5063526", "0.5063044", "0.50628847", "0.5057254", "0.50567126", "0.505212" ]
0.0
-1
FUNZIONE PER OTTENERE DURATE VISEMI
function ottieni_durate() { var MAX_INT=9007199254740992; parametri="fileRichiesto=durate&randomizer="+THREE.Math.randInt(-MAX_INT, MAX_INT); xmlhttp_durate=creaConnessioneXMLHTTP_POST("/ServerWebGl/MandaJSON",parametri.length); xmlhttp_durate.onreadystatechange=function(){ //passiamo alla funzione riempi_campi la risp della servlet if(xmlhttp_durate.readyState==4 && xmlhttp_durate.status==200){ risposta = xmlhttp_durate.responseText; window.opener.durate_visemi=JSON.parse(risposta); window.opener.aggiorna_render(); } //4 significa richiesta completata - 200 significa richiesta http andata a buon fine }; if(parametri!="") { xmlhttp.send(parametri); //manda la richiesta HTTP e attendiamo che si verifichi l'evento onreadystatechange } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function afase_luna(njd){\n\n // calcola l'angolo di fase della luna per la data (njd)\n // gennaio 2012\n\n var dati_luna=pos_luna(njd); // recupero fase/elongazione (1)\n var dati_sole=pos_sole(njd);\n\n var elongazione1=dati_luna[4]; // elongazione in gradi sessadecimali.\n var dist_luna=dati_luna[7]/149597870; \n var dist_sole=dati_sole[4]; // distanza del sole in UA.\n\n elongazione=Math.abs(elongazione1)*1;\n\n var dist_sl=dist_luna*dist_luna+dist_sole*dist_sole-2*dist_luna*dist_sole*Math.cos(Rad(elongazione)); // distanza sole-luna\n dist_sl=Math.sqrt(dist_sl);\n\n // calcolo dell'angolo di fase in gradi . \n\n var Dpt= dist_luna; // distanza pianeta-terra.\n var Dts= dist_sole; // distanza terra-sole.\n var Dps= dist_sl; // distanza pianeta-sole.\n\n // teorema del coseno\n\n var delta_fase=(Dts*Dts+Dps*Dps-Dpt*Dpt)/(2*Dps*Dts);\n delta_fase=Math.acos(delta_fase); \n delta_fase=Rda(delta_fase);\n\n var angolo_fase=180-elongazione-delta_fase; // angolo di fase in gradi.\n\n if(elongazione1<0) {angolo_fase=-angolo_fase; }\n\n return angolo_fase;\n\n}", "function perimetroCuadradoFuncion(lado){\n return lado * 4\n }", "function IndicadorRangoEdad () {}", "function operacion(){\r\n if (numeros.segundo === null || numeros.segundo === \"\" || Number.isNaN(numeros.segundo)){ \r\n return raiz(); // Si hay un solo número, llamar a la funcion raiz\r\n } else {\r\n return aritmetica(); // Si hay dos a la función aritmética\r\n }\r\n }", "function obli_ecli(njd){\n\n // calcola l'obliquità dell'eclittica.\n // per l'equinozio della data.\n // T= numero di secoli giuliani dallo 0.5 gennaio 1900.\n\n var T=(njd-2415020.0)/36525;\n\n var obli_eclittica=23.452294-0.0130125*T-0.00000164*T*T+0.000000503*T*T*T;\n\nreturn obli_eclittica; //obliquità in gradi\n\n}", "function eq_tempo(){\n\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) ottobre 2011.\n // funzione per il calcolo del valore dell'equazione del tempo per la data odierna.\n // algoritmo di P.D. SMITH.\n \nvar njd=calcola_jd(); // giorno giuliano in questo istante a Greenwich.\n njd=jdHO(njd)+0.5; // g. g. a mezzogiorno di Greenwich.\n\nvar ar_sole=pos_sole(njd); // calcolo dell'ascensione retta del sole.\nvar anno=jd_data(njd); // anno di riferimento.\n\nvar Tempo_medio_Greenw=tsg_tmg_data(ar_sole[0],anno[2],njd); // tempo medio di Greenwich.\nvar valore_et=12-Tempo_medio_Greenw; // valore dell'equazione del tempo.\n\n valore_et=valore_et*60; // valore in minuti.\n\n valore_et=valore_et.toFixed(6);\n\n\n\nreturn valore_et\n\n}", "function kiekDienuIkiKaledu() {\n console.log(\"266\");\n // siandienos data\n let today = new Date();\n // kaledu data\n let christmas = new Date(\"2021-12-24\");\n console.log(\"today\", today.toDateString(), \"christmas\", christmas.toDateString());\n\n // skirtumo tarp datu\n let diffMs = christmas - today;\n console.log(\"diffMs\", diffMs);\n // paversti ta skirtuma dienom\n let msToDays = diffMs / 1000 / 3600 / 24;\n // gaunam kiek pilnu dienu\n let wholeDays = Math.floor(msToDays);\n\n // panaudojom pagalbine funkcija\n //let wholeDays = daysDiff(today, christmas);\n\n // atspausdinti\n console.log(\"iki kaledu liko\", wholeDays, \"dienu\");\n}", "function condiçaoVitoria(){}", "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}", "static GetUtilidad(cadenaDeConexion, fI, fF, idSucursal, result) {\n\n var sucursal = '';\n if (idSucursal != 1) {\n sucursal = `AND info_ingresos.codSucursal=` + idSucursal;\n }\n console.log(\"sucursal \", sucursal);\n sqlNegocio(\n cadenaDeConexion,\n ` SELECT base.codMes, SUM(base.precioVenta) as totalVenta from (SELECT info_grupopartidas.nombreGrupo,info_ingresos.codMes,\n\n CASE info_grupopartidas.nombreGrupo\n WHEN 'EGRESOS' THEN -(SUM(info_ingresos.sumPrecioVenta))\n WHEN 'INGRESOS' THEN SUM(info_ingresos.sumPrecioVenta)\n END as precioVenta\n \n \n from info_ingresos LEFT JOIN\n info_partidas on info_ingresos.idPartida = info_partidas.idPartida LEFT JOIN \n info_grupopartidas on info_grupopartidas.idGrupoPartida = info_partidas.idGrupo \n where info_ingresos.fecEmision BETWEEN '`+ fI + `' AND '` + fF + `' AND info_ingresos.estado=1 ` + sucursal + ` AND ( info_grupopartidas.nombreGrupo = 'EGRESOS' or info_grupopartidas.nombreGrupo = 'INGRESOS')\n group by info_grupopartidas.nombreGrupo,info_ingresos.codMes)as base group by base.codMes\n order by base.codMes ASC`,\n [],\n function (err, res) {\n if (err) {\n console.log(\"error: \", err);\n result(null, err);\n }\n else {\n result(null, res);\n }\n });\n }", "function activaFuncionamientoReloj() {\n let tiempo = {\n hora: 0,\n minuto: 0,\n segundo: 0\n };\n\n tiempo_corriendo = null;\n\n\n tiempo_corriendo = setInterval(function () {\n // Segundos\n tiempo.segundo++;\n if (tiempo.segundo >= 60) {\n tiempo.segundo = 0;\n tiempo.minuto++;\n }\n\n // Minutos\n if (tiempo.minuto >= 60) {\n tiempo.minuto = 0;\n tiempo.hora++;\n }\n\n $horasDom.text(tiempo.hora < 10 ? '0' + tiempo.hora : tiempo.hora);\n $minutosDom.text(tiempo.minuto < 10 ? '0' + tiempo.minuto : tiempo.minuto);\n $segundosDom.text(tiempo.segundo < 10 ? '0' + tiempo.segundo : tiempo.segundo);\n }, 1000);\n corriendo = true;\n\n }", "function areacuadrado (lado){\n return lado * lado;\n}", "function perimetroCuadrado(lado){\n return lado*4;\n}", "function perimetroCuadrado(lado) {\n return lado * 4 ;\n}", "function DescuentoJudicial(){ \n //obtiene el valor anterior de sal_jud\n var sal_jud=document.getElementById(\"sal_jud\").value\n //valor del input de sueldo neto\n var SaldoNeto= document.getElementById('sueldoNeto').value;\n //si anteriormente ya tenia un valor restaura ante cambios del operador\n if(sal_jud > 0)\n {\n var suma=parseFloat(SaldoNeto) + parseFloat(sal_jud);\n document.getElementById(\"sueldoNeto\").value=suma;\n }\n //valor del input del descuento judicial\n var monto= document.getElementById('inputJudicial').value;\n //el nuevo valor de Saldo Neto\n var SaldoNeto= document.getElementById(\"sueldoNeto\").value;\n document.getElementById(\"sueldoNeto\").value=(SaldoNeto-monto);\n document.getElementById(\"sal_jud\").value=monto;\n //guardamos el valor de salario neto(esto se actualizara con cada descuento)\n var sueldoneto=document.getElementById('sueldoNeto').value;\n document.getElementById(\"sal_neto\").value=sueldoneto;\n \n }", "function perimetroCuadrado(lado) {\n return lado * 4; \n}", "function dodajClana() {\n if (ime.value == \"\" || prezime.value == \"\" || datumRodjenja.value == \"\") {\n alert(\"Unesite sve potrebne podatke: Ime, prezime, datum rođenja!!!\");\n } else if (danasnjDatum < new moment(datumRodjenja.value)) {\n alert(\"Potrebno je da unesete datum ne mlađi od današnjeg !!!\");\n } else {\n var ispis = racunjanjeDatuma(datumRodjenja.value);\n brojClanovaPorodice();\n var row =\n \"<tr><td>\" +\n ime.value +\n \"</td><td>\" +\n prezime.value +\n \"</td><td>\" +\n datumRodjenja.value +\n \"</td><td>\" +\n ispis +\n \"</td>\" +\n trash +\n edit +\n check +\n \"</tr>\";\n var novi = tableTbody.innerHTML + row;\n tableTbody.innerHTML = novi;\n obrisiVrijednosti();\n console.table(porodica);\n }\n}", "function perimetroCuadrado(lado) {\n return lado * 4; \n}", "function perimetroCuad(lado){\n return lado * 4;\n}", "function mostraNotas(){}", "function x( d ){ return d.anio; } // Devuelve el valor del año de un punto dado", "function sc_oresd(ore_dec){\n\n // by Salvatore Ruiu Irgoli-Sardegna (Italy). \n // scomposizione delle ore decimali [ore_dec], in hh |mm |ss.decimali con 2 decimali.\n // restituisce la variabile stringa [ore_hms].\n // ATTENZIONE! La funzione riporta le ore all'interno dell'intervallo: 0-24.\n // agg: Dicembre 2011\n \n var ored=ore_24(ore_dec); // Intervallo ore: 0-24\n\n var ore= parseInt(ored); // Ore.\n var minuti= parseInt((ored-ore)*60); // Minuti.\n var secondi= (((ored-ore)*60-minuti)*60).toFixed(2); // Secondi con 2 decimali.\n\n // verifica arrotondamenti. \n\n if (secondi>=60){secondi=secondi-60; minuti=minuti+1;}\n if ( minuti>=60){ minuti= minuti-60; ore=ore+1; }\n if ( ore>=24){ ore=ore_24(ore);} // Intervallo ore: 0-24\n \n ore= String(ore); // trasforma il numero in stringa.\n minuti= String(minuti ); // trasforma il numero in stringa. \n secondi= String(secondi); // trasforma il numero in stringa. \n \n if (ore.length<2 ){ ore='0'+ore;}\n if (minuti.length<2 ){ minuti='0'+minuti;}\n if (secondi.length<=4){secondi='0'+secondi;}\n\n var ore_hms=ore+\"h. \"+minuti+\"m. \"+secondi+\"s.\";\n\t \nreturn ore_hms; \n\n}", "getEleccionPaquete(){\r\n\r\n if( eleccion == \"IGZ\" ){\r\n //Igz - descuento del 15\r\n console.log(\"Elegiste Iguazú y tiene el 15% de decuento\");\r\n return this.precio - (this.precio*0.15);\r\n }\r\n else if (eleccion == \"MDZ\"){\r\n //mdz - descuento del 10\r\n console.log(\"Elegiste Mendoza y tiene el 10% de descuento\");\r\n return this.precio - (this.precio*0.10);\r\n }\r\n else if (eleccion == \"FTE\"){\r\n //fte - no tiene descuento \r\n console.log(\"Elegiste El Calafate, lamentablemente no tiene descuento\");\r\n return \"\";\r\n }\r\n \r\n }", "function ustawId(pole) {\r\n aktualnePole = pole.id; \r\n aktualnaWartosc = pole.value;\r\n}", "function azarDulce(){\n var NroDulce = Math.floor(Math.random()*MAXIMO_IMAGENES);\n return tipoDulce[NroDulce];\n}", "function DescuentoAusencia(){\n //recupero el valor de ausencia\n var sal_aus= document.getElementById(\"sal_aus\").value;\n var SaldoNeto= document.getElementById('sueldoNeto').value;\n //reestablece los valores al cambiar dias\n if(sal_aus > 0)\n {\n var suma=parseFloat(SaldoNeto) + parseFloat(sal_aus);\n document.getElementById(\"sueldoNeto\").value=suma;\n \n }\n var SueldoBrutoIni=document.getElementById('sueldoBruto').value;\n //calcula el jpornal diario\n var jornal=SueldoBrutoIni/30;\n //obtiene la cantidad de dias\n var dias=document.getElementById('DiaAusencia').value;\n //calcula jornal diario por cantidad de dias\n document.getElementById(\"sal_aus\").value=jornal*dias;\n //Actualiza el neto a cobrar\n var SaldoNeto= document.getElementById('sueldoNeto').value;\n document.getElementById(\"sueldoNeto\").value=SaldoNeto-(jornal*dias);\n //guardamos el valor de salario neto(esto se actualizara con cada descuento)\n var sueldoneto=document.getElementById('sueldoNeto').value;\n document.getElementById(\"sal_neto\").value=sueldoneto;\n \n \n }", "function perimetroCuadrado(lado) {\n return lado * 4;\n}", "function perimetroCuadrado(lado) {\n return lado * 4;\n}", "function perimetroCuadrado(lado) {\n return lado * 4;\n}", "function perimetroCuadrado(lado) {\n return lado * 4;\n}", "function TipoDescuento4(){\n //recuperamos el valor descuento 4 anterior\n var descuento4=document.getElementById(\"tipo_des4\").value;\n \n //recuperamos el sueldo neto del input\n var SueldoNeto=document.getElementById('sueldoNeto').value;\n //si anteriormente ya tenia un valor, debe reestablecer\n if(descuento4 > 0)\n {\n var suma=parseFloat(SueldoNeto) + parseFloat(descuento4);\n document.getElementById(\"sueldoNeto\").value=suma;\n }\n \n var monto= document.getElementById('tipoDescuento4').value;\n document.getElementById(\"tipo_des4\").value=monto;\n //Actualiza el neto a cobrar\n var SaldoNeto= document.getElementById('sueldoNeto').value;\n document.getElementById(\"sueldoNeto\").value=SaldoNeto-monto;\n \n //codigo de descuento la cual guardaremos\n var posicion=document.getElementById('tipodescuento4').options.selectedIndex;\n var codigoDescuento4=document.getElementById('tipodescuento4').options[posicion].value;\n document.getElementById(\"cod_des4\").value=codigoDescuento4;\n //guardamos el valor de salario neto(esto se actualizara con cada descuento)\n var sueldoneto=document.getElementById('sueldoNeto').value;\n document.getElementById(\"sal_neto\").value=sueldoneto;\n }", "function calcola_jdUT0(){\n\n // funzione per il calcolo del giorno giuliano per l'ora 0 di oggi in T.U.\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) giugno 2010.\n // restituisce il valore numerico dataGiuliana.\n \n \n var data=new Date();\n\n var anno = data.getYear(); // anno\n var mese = data.getMonth(); // mese 0 a 11 \n var giorno= data.getDate(); // numero del giorno da 1 a 31\n var ora = 0; // ora del giorno da 0 a 23 in T.U.\n var minuti= 0; // minuti da 0 a 59\n var secondi=0; // secondi da 0 a 59\n \n mese =mese+1;\n\nif (anno<1900) {anno=anno+1900;} // correzione anno per il browser.\n\nvar dataGiuliana=costanti_jd(giorno,mese,anno,ora,minuti,secondi);\n\n dataGiuliana=dataGiuliana*1 // definire come valore numerico.\n\nreturn dataGiuliana; // restituisce il giorno giuliano\n\n}", "function crearFuncionExplorarUnidades(id, coste){\r\n\t\t\t\tvar funcion = function (){\r\n\t\t\t\t\t\tvar a = find(\"//input[@type='text']\", XPList).snapshotItem(id - 1);\r\n\t\t\t\t\t\tvar b = find(\"//div[@name='exp\" + id + \"']\", XPFirst);\r\n\t\t\t\t\t\tvar c = calculateResourceTime(arrayByN(coste, a.value));\r\n\t\t\t\t\t\tif (c) b.innerHTML = c; else b.innerHTML = '';\r\n\t\t\t\t};\r\n\t\t\t\treturn funcion;\r\n\t\t}", "function perimetroCuadrado(lado) {\n return lado * 4;\n}", "function esProtesisf(diente, codigopieza){\n\t\t\n\t\tvar esProtesisf = false;\n\t\tvar color = 'blue';\n\t\tvar pdiente = \"\"; //primer diente\n\t\tvar udiente = \"\"; // ultimo diente\n\t\tvar protesisfcompleto = false;\n\t\tvar salida ='';\n\n\t\tvar esCor = false;\n\t\tvar color = 'blue';\n\n\t\tvar trat_protesisf = ko.utils.arrayFilter(vm.tratamientosAplicados(), function(t){\n\t\t\treturn t.tratamiento.id == codigopieza;\n\t\t});\t\n\n\t\ttry {\n\n \tfor (var i = 0; i <= trat_protesisf.length - 1; i++) {\n\t\t\tvar t = trat_protesisf[i];\n \n // Si esta completo el puente\n if (t.diente.id.indexOf('_') > -1) { \n\t\t pdiente = t.diente.id.substring(0, t.diente.id.indexOf('_'));\t\n\t\t\t udiente = t.diente.id.substring(t.diente.id.lastIndexOf('_')+3, t.diente.id.length - t.diente.id.lastIndexOf('_'));\n\n // si estan definidos ambos dientes del puente devuelvo el tratamiento\n\t\t\t if(pdiente>0 && udiente>0 && diente.id==pdiente){ \n\t\t\t \t esProtesisf = true;\n\t\t\t \t protesisfcompleto = true;\n\n\t\t if (t.tratamiento.id == \"01.09\" || t.tratamiento.id == \"01.03\" || t.tratamiento.id == \"01.10\"){\n\t\t\t\t\t color = t.tratamiento.color;\n\t\t } \n\t\t\t \t salida=[esProtesisf,color,pdiente,udiente, protesisfcompleto];\n\t\t\t }\n\t\t\t // con que uno este definido ya es puente\n\t\t\t if(pdiente>0 && udiente>0 && diente.id==pdiente){ \n\t\t\t \t esProtesisf = true;\n\t\t\t \t salida=[esProtesisf,color,pdiente,udiente, protesisfcompleto];\n\t\t\t }\n\t\t\t \n\t\t\t} \n\t\t};\n \n }\n catch(err) {\n\t\t \n\t\t}\n \treturn salida;\n\n\t}", "function perimetrocuadrado(lado) {\n return lado * 4;\n}", "function perimetro(lado2){\n return lado2*4;\n}", "function dwa() {\n \n //wypisanie do konsoli zawartości zmienna1, zdeklarowanej w funkcji nadrzednej, wartośc zostanie pobrana poprzez hoisting\n console.log(zmienna1);\n \n //Deklaracja i przypisanie w funkcji wewnetrznej\n var zmienna2 = 3;\n }", "function atkDuMonstre (monstre){\n cible();\n if (vieCible == vieGue){\n nomCible = \"au Guerrier\";\n }\n if (vieCible == viePre){\n nomCible = \"au Prêtre\";\n }\n if (vieCible == vieArc){\n nomCible = \"à l'Archer\";\n }\n if (vieCible == vieVol){\n nomCible = \"au Voleur\";\n }\n\tvieCible.value -= atkMonstre;\n\tvieCible.innerHTML = vieCible.value;\n\tdescription.innerHTML = monstre+\" inflige \"+atkMonstre+\" \"+nomCible;\n}", "function tienenSaldoDisponible (callback){\n \n var arg = {}\n arg['falseId'] = {}\n arg['falseId']['$gt'] = rangos[0] \n arg['falseId']['$lt'] = rangos[1]\n \n obtenerParametros.conFiltros(arg,function(error,parametros){\n \n if (error){throw error}\n else {\n \n console.log('Tienen saldo ', parametros)\n var result = [] // Id's de los usuarios\n \n for (var a=0;a<parametros.length;a++){\n \n if (parametros[a]['totalDisponible'] >= parametros[a]['totalXInvs']){\n \n result.push(parametros[a]['_id']) // Id del usuario\n \n }\n }\n\n if (result.length > 0){\n\n return callback(result)\n\n }else {\n\n acabarPreInversion()\n\n }\n }\n })\n}", "function perimetroCuadrado(lado){\n return lado * 4\n}", "recibirDisparo(potencia) {\n this.escudo = this.escudo - potencia;\n return this.escudo;\n }", "function ControlloDataInserita(datadafiltrare,campo,dt,colore,sfondo) {\r\n\r\nvar gg; //variabile per i giorni\r\nvar mm; // variabile per i mesi\r\nvar yy; // variabile per l'anno\r\nvar dateNow = new Date(); // assegna la data corrente (presa dal pc locale)\r\nvar yearNow = dateNow.getFullYear(); //assegna l'anno corente\r\nvar indice=0; // variabile di servizio\r\n\r\nvar nrgiorni = new Array();\r\n\tnrgiorni[0]=29; // febbraio bisestile\r\n\tnrgiorni[1]=31; // gennaio\r\n\tnrgiorni[2]=28; // febbraio\r\n\tnrgiorni[3]=31; // marzo\r\n\tnrgiorni[4]=30;\t// aprile\r\n\tnrgiorni[5]=31; // maggio\r\n\tnrgiorni[6]=30; // giugno\r\n\tnrgiorni[7]=31; // luglio\r\n\tnrgiorni[8]=31; // agosto\r\n\tnrgiorni[9]=30; // settembre\r\n\tnrgiorni[10]=31; // ottobre\r\n\tnrgiorni[11]=30; // novembre\r\n\tnrgiorni[12]=31; // dicembre\r\n\r\nif (datadafiltrare==null || datadafiltrare==\"\") { //se il campo è vuoto esce dalla funzione\r\n document.getElementById(campo).style.color=colore;\r\n document.getElementById(campo).style.background=\"white\";\r\n return;\r\n}\r\n\r\nswitch (datadafiltrare.length) { //analizza il formato della data e prepara le variabili gg, mm, yy\r\n case is = 6: //formato data breve\r\n gg = datadafiltrare.slice(0,2);\r\n mm = datadafiltrare.slice(2,4);\r\n yy = datadafiltrare.slice(4,6);\r\n break; \r\n \r\n case is = 8: //formato data a 8 caratteri\r\n if (datadafiltrare.indexOf(\"/\") >= 0 || datadafiltrare.indexOf(\"-\")>=0) { //con separatori\r\n gg = datadafiltrare.slice(0,2);\r\n mm = datadafiltrare.slice(3,5);\r\n yy = datadafiltrare.slice(6,8);\r\n } else { //data a 8 cifre senza separatori\r\n gg = datadafiltrare.slice(0,2);\r\n mm = datadafiltrare.slice(2,4);\r\n yy = datadafiltrare.slice(4,8);\r\n }\r\n break;\r\n \r\n case is = 10: //formato data completa\r\n gg = datadafiltrare.slice(0,2);\r\n mm = datadafiltrare.slice(3,5);\r\n yy = datadafiltrare.slice(6,10);\r\n break;\r\n\r\n default: //negli altri formati inseriti la routine genera un errore\r\n alert(\"Attenzione! La data che hai inserito e' errata. Sono validi i seguenti formati: 'ggmmaa','gg/mm/aa','ggmmaaaa' e 'gg/mm/aaaa'\");\r\n document.getElementById(campo).focus();\r\n //datadafiltrare.focus();\r\n datadafiltrare=\"\";\r\n return datadafiltrare;\r\n}\r\n\r\n//controlla che i dati di riferimento al giorno, al mese e all'anno siano dati numerici \r\nif (isNaN(gg) || isNaN(mm) || isNaN(yy)) {\r\n\talert(\"Attenzione! La data che hai inserito e' errata.\");\r\n document.getElementById(campo).focus();\r\n //datadafiltrare.focus();\r\n datadafiltrare=\"\";\r\n return datadafiltrare;\r\n}\r\n\r\n//controlla che siano stati inseriti giusti tutti gli elementi che compongono la data\r\nif (Number(gg) <= 0 || Number(mm) <= 0 || Number(mm) > 12 || Number(yy) < 0) { \r\n alert(\"Attenzione! La data che hai inserito e' errata.\");\r\n document.getElementById(campo).focus();\r\n //datadafiltrare.focus();\r\n datadafiltrare=\"\";\r\n return datadafiltrare;\r\n}\r\n\r\n//porta l'anno a quattro cifre calcolando il cambio del millennio\r\nif (Number(yy) <= (Number(yearNow)-2000)) { \r\n yy = (Number(yy)+2000); \r\n } else if (Number(yy) < 100 && Number(yy) > (Number(yearNow)-2000)){\r\n yy = (Number(yy)+1900);\r\n }\r\n\r\n//controlla che l'anno non sia maggiore o uguale a quello corrente\r\n//(dt e dn significano data tesseramento e data di nascita)\r\nif (dt==\"dn\") {\r\n if (Number(yy) >= Number(yearNow)) { \r\n alert(\"Attenzione! L'anno che hai inserito e' errato!\");\r\n document.getElementById(campo).focus;\r\n //datadafiltrare.focus();\r\n datadafiltrare=\"\";\r\n return datadafiltrare;\r\n }\r\n}\r\n// controlla che l'anno inserito non sia bisestile e assegna il valore alla variabile indice\r\nif ((Number(yy) % 4) == 0 && Number(mm)==2) {\r\n\tindice=0;\r\n} else {\r\n\tindice=Number(mm);\r\n}\r\n\r\n// controlla che l'utente non abbia inserito un numero giorni del mese errato\r\nif (Number(gg) > nrgiorni[indice]) {\t\r\n\talert(\"Attenzione! La data che hai inserito e' errata.\");\r\n document.getElementById(campo).focus();\r\n //datadafiltrare.focus();\r\n datadafiltrare=\"\";\r\n return datadafiltrare;\r\n}\r\n// ricompone e stampa la data filtrata\r\ndatadafiltrare=gg+\"/\"+mm+\"/\"+yy;\r\ndocument.getElementById(campo).value=datadafiltrare;\r\ndocument.getElementById(campo).style.color=colore;\r\ndocument.getElementById(campo).style.background=\"white\";\r\nreturn;\r\n}", "static update_fuente(cadenaDeConexion, idIngreso) {\n var flag = (-1);\n //1 - ingreso, 0-egreso\n ///verificar si es ingreso o egreso para sumar o restar el valor a la caja fuente\n sqlNegocio(\n cadenaDeConexion,\n \"SELECT * from info_ingresos WHERE idIngreso = \" + idIngreso,\n [],\n function (err, res) {\n if (res[0].movimiento == 0) { flag = 1; }\n sqlNegocio(\n cadenaDeConexion,\n \"UPDATE info_fuente SET saldo = saldo +\" + (res[0].aCuenta * flag) + \" WHERE codFuente = \" + res[0].codFuente,\n [],\n function (err, res18) {\n if (err) {\n console.log(\"error: \", err);\n result(null, err);\n }\n });\n });\n }", "function obliczPunkty(dane)\n{\n var ro = 1.21; // gęstośc czynnika\n var stosunek_et = [0.86, 0.98, 1, 0.966, 0.86]; // stosunek sprawności izentropowych\n\n var mi0 = (1 - (Math.sqrt(Math.sin(dane.beta2 * (Math.PI / 180))) / (Math.pow(dane.z, 0.7)))).toPrecision(3); // współczynnik zmniejszenia mocy wentylatora\n var u2 = ((dane.D2 * Math.PI * dane.n) / 60).toPrecision(3); // prędkość obwodowa wirnika\n var c2u = ((dane.deltapzn * 1000) / (ro * u2 * dane.etazn)).toPrecision(3); // prędkość zależna od ułopatkowania wirnika\n var fi2r = ((c2u * Math.tan(dane.alfa2 * Math.PI / 180)) / u2).toPrecision(3); // wskaźnik prędkości koła wirnikowego\n var fi2r0 = ((mi0 * fi2r) / (mi0 - (c2u / u2))).toPrecision(3); // wartośc wskaznika prędkości koła wirnikowego dla wartości zerowej charakterystyki koła wirnikowego\n var Qmax = (dane.Qzn * (fi2r0 / fi2r)).toPrecision(3); // przepływ maksymalny\n\n var krok = 0.6;\n\n var daneDoWykresu = {};\n daneDoWykresu.deltap = []; // tablica wartości sprężu (deltap)\n daneDoWykresu.Q = []; // tablica wartości wydajności\n daneDoWykresu.Q = []; // tablica wartości wydajności\n daneDoWykresu.eta = []; // etazn * stosunek_et\n\tdaneDoWykresu.wspQ = []; //współczynnik Q: 1-Q/Qmax\n\tdaneDoWykresu.mp = [] ; // tablica wartości mocy pobieranej\n\t\n /* obliczanie punktów charakterystyk */\n\t\n for (var i = 0; i < 5; i++)\n\t{\n daneDoWykresu.Q[i] = krok * dane.Qzn;\n daneDoWykresu.wspQ[i] = 1 - (daneDoWykresu.Q[i] / Qmax);\n daneDoWykresu.eta[i] = dane.etazn * stosunek_et[i];\n\t\tdaneDoWykresu.deltap[i] =((293/(273+dane.tc))*((ro * (Math.pow(u2, 2)) * mi0 * daneDoWykresu.wspQ[i] * daneDoWykresu.eta[i])) / 1000); // kPa\n\t\tdaneDoWykresu.mp[i] = ((daneDoWykresu.Q[i]*daneDoWykresu.deltap[i])/(daneDoWykresu.eta[i]*dane.etas))/100; // kW/100\n krok += 0.2;\n }\n return daneDoWykresu;\n}", "function adivinarOrigenRecinto(estudiantes) {\n //valor que se utilizará para comparar\n var resultado = 100000;\n //tupla que almacenará la posición más cercana \n var numeroTupla = 0;\n //for que recorre todos los datos como parámetro de la consulta \n //de la tabla estudiantes\n for (var i = 0; i < estudiantes.length; i++) {\n var sexoTupla = 0;\n var estiloTupla = 0;\n \n //le da parámetro de 1 para masculino\n //si es femenino es 2\n if (estudiantes[i].sexo === 'F') {\n sexoTupla = 2;\n }\n //switch para identificar el valor del estilo de aprendizaje de 1 a 4\n //se le asigna el valor a estiloTupla\n switch (estudiantes[i].estilo) {\n case 'DIVERGENTE':\n estiloTupla = 1;\n break;\n case 'CONVERGENTE':\n estiloTupla = 2;\n break;\n case 'ASIMILADOR':\n estiloTupla = 3;\n break;\n case 'ACOMODADOR':\n estiloTupla = 4;\n break;\n }\n \n //distancia euclidiana aplicada a los valores de las tuplas para definir distancia\n var sumatoria = Math.pow((estiloTupla - (parseInt(document.getElementById('estiloAprendizaje').value))), 2) + Math.pow(sexoTupla - (parseInt(document.getElementById('sexo').value)), 2) + Math.pow((parseFloat(estudiantes[i].promedio)) - (parseFloat(document.getElementById('promedio').value)), 2);\n var distancia = Math.sqrt(sumatoria);\n \n //aquí comparan para mostrar el más cercano al que entra como parámetro\n //comparando los datos de la tupla y los ingresados\n if (resultado > distancia) {\n resultado = distancia;\n numeroTupla = i;\n } \n }\n //se imprime el recinto al que más se acerca dependiendo de las tupñas\n //la que tiene menor distancia euclidiana además de id de la tupla\n document.getElementById('mensaje2').innerHTML = 'Su recinto de origen es: ' + estudiantes[numeroTupla].recinto + ' de id ' + estudiantes[numeroTupla].id;\n}", "function TinhTien() {\n //Lay loai xe\n var loaiXe = LayloaiXe();\n console.log(loaiXe);\n //Lay thoi gian cho\n var tgCho = getEle('tgCho').value;\n //lay so km\n var soKM = getEle('soKm').value;\n var tongHoaDon = 0;\n //Tinh theo loai xe\n switch (loaiXe) {\n case 'uberX':\n tongHoaDon = TinhTheoLoaiXe(soKM, tgCho, UberX_1, UberX_2, UberX_3, tgCho_UberX);\n break;\n case 'uberSUV':\n tongHoaDon = TinhTheoLoaiXe(soKM, tgCho, UberSUV_1, UberSUV_2, UberSUV_3, tgCho_UberSUV);\n break;\n case 'uberBlack':\n tongHoaDon = TinhTheoLoaiXe(soKM, tgCho, UberBlack_1, UberBlack_2, UberBlack_3, tgCho_UberBlack);\n break;\n default:\n break;\n }\n}", "function idade(ano_nascimento, mes_nascimento, dia_nascimento) {\r\n ano_atual = new Date;\r\n ano_atual = ano_atual.getFullYear();\r\n mes_atual = new Date().getMonth() + 1\r\n dia_atual = new Date().getDate()\r\n if (mes_atual < mes_nascimento || mes_atual == mes_nascimento && dia_atual < dia_nascimento) {\r\n ano_atual -= 1\r\n }\r\n return ano_atual - ano_nascimento;\r\n\r\n }", "function costanti_jd(giorno,mese,anno,ora,minuti,secondi){\n\n var yy_negativo=0; // sottrae 1 quando l'anno è negativo. \n var mese_str=String(mese); // il mese in formato stringa.\n \n if(anno<0) {yy_negativo=1;} // verifica l'anno negativo. \n \n if (mese==1 || mese==2) {mese_str=\"0\"+mese_str; anno=anno-1; mese=mese+12;} // verifica il mese e l'anno.\n\n var verifica_yy=String(anno)+\".\"+mese_str+String(giorno); // verifica l'anno formato stringa. \n var yy_num=eval(verifica_yy); // riporta l'anno in formato numerico.\n \n \n var a = parseInt( anno / 100 );\n var b = 2 - a + parseInt( a / 4 );\n\n if(yy_num<1582.1015) {a=0; b=0; } // azzera le variabili a e b quando l'anno è minore di 1582.1015.\n\n var c = parseInt( 365.25 * anno );\n var d = parseInt( 30.6001 * ( mese + 1 ) );\n\n var dataGiuliana = b + c + d + giorno + 1720994.50 - yy_negativo;\n\n var offsetGiornata = ( 3600 * ora + 60 * minuti + secondi ) / 86400;\n\n dataGiuliana = dataGiuliana + offsetGiornata;\n\n dataGiuliana=dataGiuliana.toFixed(6);\n\nreturn dataGiuliana ;\n\n}", "function ejercicio04(user){\n console.log(user);\n adulto = 0;\n if (user.edad>18)\n {\n adulto = 1;\n }\n else\n {\n return \"El usuario \" + user.nombre + \" no es mayor de edad\";\n }\n\n if (adulto == 1)\n {\n return \"El usuario \" + user.nombre + \" es mayor de edad. Por lo tanto, le he creado un usuario con el correo \" + user.correo;\n }\n \n}", "function frutaYverdura(fruta, verdura){\n console.log(fruta + \" \" + verdura)\n}", "function jeden() {\n\n //deklaracja zmiennej zmienna1 - zmienna lokalna dla funkcji jeden\n var zmienna1 = 1;\n\n //Deklaracja funkcji dwa we wnętrzu funkcji jeden. stworzenie nowego zakresu dla funkcji dwa\n function dwa() {\n\n //wypisanie do konsoli zawartości zmiennej jeden - jest to zmienna dostępne z poziomu funkcji dwa\n console.log(zmienna1);\n\n //deklaracja zmienna2 jako zmiennej lokalnej dla zakresu dwa\n var zmienna2 = 3;\n }\n\n //wywołanie funkcji dwa w ramach wykonywania funkcji jeden\n dwa();\n\n //wypisanie do do konsoli zawartosci zmiennej2 - niedostępnej z poziomu funkcji jeden ponieważ jest zadeklarowana jako zmienna lokalna dla funkcji dwa\n console.log(zmienna2)\n}", "function duplicarTreinta(){\n return 30*2;\n}", "function attaquer() \n{\n if (presenceEnnemi === 666){\n dialogBox(\"MORT DE CHEZ MORT ARRETE MAINTENANT. TU PEUX PAS ATTAQUER T'ES MORT. MORT. MOOOOORT\");\n }else if (presenceEnnemi === 0){\n dialogBox(\"Tu n'as pas d'adversaire, va chercher la merde on en reparle après.\");\n }else if (presenceEnnemi = 1, tourJoueur(tour)=== true){\n var Min= Number(personnage.force - 10)\n var Max= Number(personnage.force + 10)\n\n function getRndInterger(min, max) {\n return Math.floor(Math.random() * (max - min + 1) ) + min;}\n\nvaleurAttaque = getRndInterger(Min, Max);\nactionPerso = 1;\nreactionEnnemi();\nesquiveReussie = 0;\nresetSpecial();\n}\n\n}", "function perimetroCuadrado(ladoCuadrado){\n return ladoCuadrado * 4;\n}", "function eq_tempo_data2(anno,njd){\n\n // funzione per il calcolo dell'equazione del tempo.\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) gennaio 2012.\n // algoritmo di MEEUS.\n \n njd=jdHO(njd); // riporta il g.g. all'ora H0(zero) del giorno. \n \nvar ar_sole=pos_sole(njd); // calcolo dell'ascensione retta del sole.\nvar ar_sole_app=pos_app(njd,ar_sole[0],ar_sole[1]);\nvar TSG=temposid_app(njd);\nvar valore_et=0;\nvar h=TSG-ar_sole_app[0];\n \nif(h<0 ) {valore_et=12+h;}\nif(h>0 ) {valore_et=h-12;}\n \n valore_et=valore_et*60; // valore in minuti.\n\n valore_et=valore_et.toFixed(6);\n\nreturn valore_et\n\n}", "function calcularDoble(numero) {\n return { // <- no dejar un enter\n original: numero,\n doble: numero * 2\n };\n}", "function cnsFrn_fecha(preencheLinha){\n if(!empty($CNSFORNECdimmer)){\n \n //A CONSULTA NAO ESTA INCLUIDA EM UMA OUTRA TELA\n if(empty(objFornecedor.divDaConsulta)){\n //VOLTA O SCROLL PRA CIMA\n $(CNSFORNEC_DIV_TABELA).animate({ scrollTop: \"=0\" }, \"fast\");\n $(\"#cnsFornec_pesquisa\").select();\n return;\n }\n\n // VOU FECHAR A CONSULTA SEM TER QUE PREENCHER AS LINHAS\n if(!preencheLinha){\n $CNSFORNECdimmer.dimmer(\"consulta hide\");\n\n //RETORNA O FOCO\n if(!empty(objFornecedor.returnFocus)) objFornecedor.returnFocus.select();\n // if(!empty(objCliente.returnFocus)) objCliente.returnFocus.select();\n\n return;\n }\n\n var posicao = $('#cnsFornec_position').val();\n var divDaConsulta = objFornecedor.divDaConsulta; //conteudo do objeto\n\n objFornecedor.fornecNum = objTabelaFornec.registros[posicao].fo_number;\n objFornecedor.fornecAbrev = objTabelaFornec.registros[posicao].fo_abrev;\n objFornecedor.razao = objTabelaFornec.registros[posicao].fo_razao;\n objFornecedor.cnpj = objTabelaFornec.registros[posicao].fo_cgc;\n objFornecedor.telefone = objTabelaFornec.registros[posicao].fo_fone;\n objFornecedor.cep = objTabelaFornec.registros[posicao].fo_cep;\n objFornecedor.endereco = objTabelaFornec.registros[posicao].fo_ender;\n objFornecedor.enderNum = objTabelaFornec.registros[posicao].fo_endnum;\n objFornecedor.bairro = objTabelaFornec.registros[posicao].fo_bairro;\n objFornecedor.cidade = objTabelaFornec.registros[posicao].fo_cidade;\n objFornecedor.uf = objTabelaFornec.registros[posicao].fo_uf;\n objFornecedor.calculoSt = objTabelaFornec.registros[posicao].fo_calc_st;\n objFornecedor.lucro = objTabelaFornec.registros[posicao].fo_lucro;\n objFornecedor.conta = objTabelaFornec.registros[posicao].fo_grdesp;\n objFornecedor.divDaConsulta = divDaConsulta; //recupera divDaConsulta\n\n for(var i in objTabelaFornec.registros[posicao]){\n objFornecedor[i] = objTabelaFornec.registros[posicao][i];\n }\n \n if($('#'+objFornecedor.divDaConsulta).hasClass('active')){\n $CNSFORNECdimmer.dimmer(\"consulta hide\");\n }\n cnsFrn_retorno();\n }\n}", "get darTN() {\n return contador_filas - (this.FN + this.TP + this.darFP);\n }", "function volar(golondrina, distancia) {\n \n return{\n energia: golondrina.energia - (2*distancia), \n nombre:golondrina.nombre}\n}", "function adivinarEstiloAprendizaje(estudiantes) {\n //valor que se utilizará para comparar\n var resultado = 100000;\n //tupla que almacenará la posición más cercana \n var numeroTupla = 0;\n //for que recorre todos los datos como parámetro de la consulta \n //de la tabla estudiantes\n for (var i = 0; i < estudiantes.length; i++) {\n var recintoTupla = 1;\n var sexoTupla = 1;\n \n //se le da valor a los recintos que pertenecen las personas en las\n //tuplas si es paraíso es 1 y turrialba es 2 \n\n if (estudiantes[i].recinto === 'Turrialba') {\n recintoTupla = 2;\n }\n //le da parámetro de 1 para masculino\n //si es femenino es 2\n if (estudiantes[i].sexo === 'F') {\n sexoTupla = 2;\n }\n //distancia euclidiana aplicada a los valores de las tuplas para definir distancia\n var sumatoria = Math.pow((sexoTupla - (parseInt(document.getElementById('sexo').value))), 2) + Math.pow(recintoTupla - (parseInt(document.getElementById('recinto').value)), 2) + \n Math.pow((parseFloat(estudiantes[i].promedio)) - (parseFloat(document.getElementById('promedio').value)), 2);\n var distancia = Math.sqrt(sumatoria);\n \n //aquí comparan para mostrar el más cercano al que entra como parámetro\n //comparando los datos de la tupla y los ingresados\n if (resultado > distancia) {\n resultado = distancia;\n numeroTupla = i;\n }\n }\n //select para cambiar el color y mostrar \n //el estilo de aprendizaje del estudiante\n switch (estudiantes[numeroTupla].estilo) {\n case \"ACOMODADOR\":\n document.getElementById('mensaje4').style.color = \"orange\";\n document.getElementById('mensaje4').innerHTML = 'Su estilo de aprendizaje es: ' + (estudiantes[numeroTupla].estilo) + ' en la posición '+estudiantes[numeroTupla].id+'.';\n break;\n case \"CONVERGENTE\":\n document.getElementById('mensaje4').style.color = \"blue\";\n document.getElementById('mensaje4').innerHTML = 'Su estilo de aprendizaje es: ' + (estudiantes[numeroTupla].estilo) + ' en la posición '+estudiantes[numeroTupla].id+'.';\n break;\n case \"ASIMILADOR\":\n document.getElementById('mensaje4').style.color = \"green\";\n document.getElementById('mensaje4').innerHTML = 'Su estilo de aprendizaje es: ' + (estudiantes[numeroTupla].estilo) + ' en la posición '+estudiantes[numeroTupla].id+'.';\n break;\n case \"DIVERGENTE\":\n document.getElementById('mensaje4').style.color = \"red\";\n document.getElementById('mensaje4').innerHTML = 'Su estilo de aprendizaje es: ' + (estudiantes[numeroTupla].estilo) + ' en la posición '+estudiantes[numeroTupla].id+'.';\n break;\n }\n}", "function TipoDescuento1(){\n //recuperamos el valor descuento 1 anterior\n var descuento1=document.getElementById(\"tipo_des1\").value;\n \n //recuperamos el sueldo neto del input\n var SueldoNeto=document.getElementById('sueldoNeto').value;\n //si anteriormente ya tenia un valor, debe reestablecer\n if(descuento1 > 0)\n {\n var suma=parseFloat(SueldoNeto) + parseFloat(descuento1);\n document.getElementById(\"sueldoNeto\").value=suma;\n }\n\n //el valor que se ingreso en monto\n var monto= document.getElementById('tipoDescuento1').value;\n document.getElementById(\"tipo_des1\").value=monto;\n //Actualiza el neto a cobrar\n var SaldoNeto= document.getElementById('sueldoNeto').value;\n document.getElementById(\"sueldoNeto\").value=SaldoNeto-monto;\n \n //codigo de descuento la cual guardaremos\n var posicion=document.getElementById('tipodescuento1').options.selectedIndex;\n var codigoDescuento1=document.getElementById('tipodescuento1').options[posicion].value;\n document.getElementById(\"cod_des1\").value=codigoDescuento1;\n \n //guardamos el valor de salario neto(esto se actualizara con cada descuento)\n var sueldoneto=document.getElementById('sueldoNeto').value;\n document.getElementById(\"sal_neto\").value=sueldoneto;\n }", "function restarDinero(monto) {\n saldoCuenta -= monto;\n return saldoCuenta;\n}", "function afase_pianeta(njd,AR,DE,dist_ps,dist_pt){\n\n // funzione per il calcolo dell'angolo di fase per un pianeta.\n // AR,DE sono le coordinate equatoriali decimali, del pianeta.\n // njd= numero del giorno giuliano.\n // dist_ps=distanza pianeta-sole in UA.\n // dist_pt=distanza pianeta-Terra in UA.\n // by Salvatore Ruiu - gennaio 2013.\n\n var coo_sole=pos_sole(njd); // coordinate equatoriali decimali del Sole.\n var Rs=coo_sole[4]; // distanza Terra-Sole. \n var elongaz=elong(AR,DE,coo_sole[0],coo_sole[1]); // elongazione in gradi dal Sole.\n\n // calcolo dell'angolo di fase in gradi . \n\n var Dpt= dist_pt; // distanza pianeta-terra.\n var Dts= Rs; // distanza terra-sole.\n var Dps= dist_ps; // distanza pianeta-sole.\n\n // risolve il teorema del coseno (noti i 3 lati del triangolo).\n\n var delta_fase=(Dts*Dts+Dps*Dps-Dpt*Dpt)/(2*Dps*Dts);\n delta_fase=Math.acos(delta_fase); \n delta_fase=Rda(delta_fase);\n\n var angolo_fase=180-Math.abs(elongaz)-delta_fase; // risultato: angolo di fase in gradi.\n\nreturn angolo_fase;\n\n}", "function extraerNodoP(){\r\n\tvar nuevo = this.raiz;\r\n\tif(!this.vacia()){\r\n\t\tthis.raiz = this.raiz.sig;\r\n\t\t//window.alert(nuevo.nombre);\r\n\t}\r\n\treturn nuevo;\r\n\t\r\n}", "function seleccionarDia () {\n \n var fecha = $('#fechas_seleccionadas_cita').val();\n globalFecha = fecha;\n var idMedico = $('#idMedico').text();\n\n if (fecha) {\n var date = new Date(fecha);\n //alert(date, idMedico);\n var obj_dates_idMedico = _dates_idMedico(fecha, date.getDay(), idMedico);\n tramosDisponibles(obj_dates_idMedico);\n\n } else { \n alert(\"Selecione una fecha\");\n }\n}", "esconder(){\n console.log(`${this._nombre} corre a ${this._velocidad}m/s y da un salto de ${this._salto}m y se esconde`)\n }", "function calculadora(){\n\tconsole.log(\"soy una calculadora\");\n}", "function DescuentoASO(){\n //obtiene sal_aso\n var sal_aso=document.getElementById(\"sal_aso\").value\n //valor del input de sueldo neto\n var SaldoNeto= document.getElementById('sueldoNeto').value;\n //si anteriormente ya tenia un valor restaura ante cambios del operador\n if(sal_aso > 0)\n {\n var suma=parseFloat(SaldoNeto) + parseFloat(sal_aso);\n document.getElementById(\"sueldoNeto\").value=suma;\n }\n //valor del input ASO\n var monto= document.getElementById('InputASO').value;\n //el nuevo valor de Saldo Neto\n var SaldoNeto= document.getElementById(\"sueldoNeto\").value;\n document.getElementById(\"sueldoNeto\").value=(SaldoNeto-monto);\n document.getElementById(\"sal_aso\").value=monto;\n //guardamos el valor de salario neto(esto se actualizara con cada descuento)\n var sueldoneto=document.getElementById('sueldoNeto').value;\n document.getElementById(\"sal_neto\").value=sueldoneto;\n }", "function idade(date) {\n\n var nascimento = new Date(date.value);\n var hoje = new Date(Date.now());\n\n var idadePessoa = Math.floor(Math.ceil(Math.abs(nascimento.getTime() - hoje.getTime()) / (1000 * 3600 * 24)) / 365.25);\n\n if (idadePessoa < 19) {\n alert(\"Idade não pode ser inferior a 19 anos =/\");\n inputDataNascimento.value = \"\";\n }\n\n}", "function miFuncion(x) {\n\n return this.numero + x;\n\n}", "function upisDoleFunc()\n{\n\n\tif (brojBacanja === 0)\n\t\treturn;\n\n\tif (indNajave > 0)\n\t{\n\t\talert(\"Igrali ste najavu!\")\n\t\treturn;\n\t}\n\t/* get the value of the field clicked */\n\tvar vred = Number(this.id.slice(1, ));\n\n\t/* see if the previous field is not -1 */\n\t/* else disable writting to preserve order */\n\tif(vred > 1 && kDole[vred-2] < 0)\n\t{\n\t\talert(\"Nedozvoljen upis!\");\n\t\treturn;\n\t}\n\n\t/* did we already write into this field */\n\tif(kDole[vred-1] >= 0)\n\t{\n\t\talert(\"Vec ste upisali u ovo polje!\");\n\t\treturn;\n\t}\n\tvar tmp = 0;\n\n\tvar tmpNiz = [];\n\n\t/* splice izabraneKockice and baceneKockice */\n\tfor(var i=0; i<5; ++i)\n\t{\n\t\t/* if innerText is a number add it to tmpNiz */\n\t\tif (Number(izabraneKockice[i].innerText))\n\t\t\ttmpNiz.push(Number(izabraneKockice[i].innerText));\n\t}\n\n\tfor(var i=0; i<5; ++i)\n\t{\n\t\t/* if innerText is a number add it to tmpNiz */\n\t\tif (Number(baceneKockice[i].innerText))\n\t\t\ttmpNiz.push(Number(baceneKockice[i].innerText));\n\t}\n\n\tif(tmpNiz.length != 5)\n\t\talert(\"Niz nije 5! vec: \" + tmpNiz.length);\n\n\t/* decide which field was clicked: broj, maxmin ili igra */\n\tswitch(vred)\n\t{\n\t\tcase 1:\n\t\tcase 2:\n\t\tcase 3:\n\t\tcase 4:\n\t\tcase 5:\n\t\tcase 6:\n\t\t\tfor(var i=0; i<5; ++i)\n\t\t\t{\n\t\t\t\tif(tmpNiz[i] == vred)\n\t\t\t\t\ttmp += tmpNiz[i]\n\t\t\t}\n\t\t\t/* write the sum into coresponding header */\n\t\t\tkDole[vred-1] = tmp;\n\t\t\tsumaKolFunc(kDole, \"suma1\");\n\t\t\tbreak;\n\t\tcase 7:\n\t\tcase 8:\n\t\t\ttmp = zbir(tmpNiz);\n\t\t\tkDole[vred-1] = tmp;\n\t\t\tsumaRazFunc(kDole, \"suma5\")\n\t\t\tbreak;\n\t\tcase 9:\n\t\t\ttmp = jelFul(tmpNiz);\n\t\t\tkDole[vred-1] = tmp;\n\t\t\tsumaIgFunc(kDole, \"suma9\");\n\t\t\tbreak;\n\t\tcase 10:\n\t\t\ttmp = jelPoker(tmpNiz);\n\t\t\tkDole[vred-1] = tmp;\n\t\t\tsumaIgFunc(kDole, \"suma9\");\n\t\t\tbreak;\n\t\tcase 11:\n\t\t\ttmp = jelKenta(tmpNiz);\n\t\t\tkDole[vred-1] = tmp;\n\t\t\tsumaIgFunc(kDole, \"suma9\");\n\t\t\tbreak;\n\t\tcase 12:\n\t\t\ttmp = jelYamb(tmpNiz);\n\t\t\tkDole[vred-1] = tmp;\n\t\t\tsumaIgFunc(kDole, \"suma9\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\t/* write number of vred thrown */\n\tdocument.getElementById(this.id).innerText=Number(tmp);\n\n\tresetuj(izabraneKockice, baceneKockice);\n\n}", "function cfasi_lunari(mese,anno,fase){\n\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) Luglio 2010\n // funzione per il calcolo delle fasi lunari.\n // mese= numero del mese da 1 a 12.\n // anno=anno di riferimento.\n // k=0.00 per la luna nuova\n // k=0.25 per il primo quarto.\n // k=0.50 per la luna piena\n // k=0.75 per l'ultimo quarto.\n // fase= valore numerico per la fase 0 - 0.25 - 0.50 - 0.75 sono ammessi solo questi valori.\n \nvar anno_dec=anno+(mese/12);\nvar k=(anno_dec-1900)*12.3685; // calcolo della costante k. (parseInt) tronca la parte decimale\n k=parseInt(k)*1+fase*1;\n \nvar T=k/1236.85;\n\nvar fseno=166.56+132.87*T-0.009173*T*T;\n fseno=fseno/180*Math.PI;\n\nvar njd_fase =2415020.75933+29.53058868*k+0.0001178*T*T-0.000000155*T*T*T+0.00033*Math.sin(fseno);\n\n // calcolo anomalia media del sole.\n\nvar M=359.2242+29.10535608*k-0.0000333*T*T-0.00000347*T*T*T;\n M=gradi_360(M);\n M=M/180*Math.PI;\n\n // calcolo anomalia media della luna.\n\nvar M1=306.0253+385.81691806*k+0.0107306*T*T+0.00001236*T*T*T;\n M1=gradi_360(M1);\n M1=M1/180*Math.PI;\n\n // calcolo dell'argomento della latitudine della luna.\n\nvar F=21.2964+390.67050646*k-0.0016528*T*T-0.00000239*T*T*T;\n F=gradi_360(F);\n F=F/180*Math.PI;\n\n // calcolo correzioni per la luna nuova e piena.\n\nvar correzione1=0;\n\nif (fase==0 || fase==0.50) {\n \n correzione1= (0.1734-0.000393*T)*Math.sin(M)\n +0.0021*Math.sin(2*M)\n -0.4068*Math.sin(M1)\n +0.0161*Math.sin(2*M1)\n -0.0004*Math.sin(3*M1)\n +0.0104*Math.sin(2*F)\n -0.0051*Math.sin(M+M1)\n -0.0074*Math.sin(M-M1)\n +0.0004*Math.sin(2*F+M)\n -0.0004*Math.sin(2*F-M)\n -0.0006*Math.sin(2*F+M1)\n +0.0010*Math.sin(2*F-M1)\n +0.0005*Math.sin(M+2*M1); \n}\n\nelse if (fase==0.25 || fase==0.75) {\n \n correzione1= (0.1721-0.0004*T)*Math.sin(M)\n +0.0021*Math.sin(2*M)\n -0.6280*Math.sin(M1)\n +0.0089*Math.sin(2*M1)\n -0.0004*Math.sin(3*M1)\n +0.0079*Math.sin(2*F)\n -0.0119*Math.sin(M+M1)\n -0.0047*Math.sin(M-M1)\n +0.0003*Math.sin(2*F+M)\n -0.0004*Math.sin(2*F-M)\n -0.0006*Math.sin(2*F+M1)\n +0.0021*Math.sin(2*F-M1)\n +0.0003*Math.sin(M+2*M1)\n +0.0004*Math.sin(M-2*M1)\n -0.0003*Math.sin(2*M+M1); \n}\n\nelse {alert(\"Valore fase \"+fase+\" non valido!\");}\n\nvar njd_fase=njd_fase+correzione1; // per la luna nuova.\n\n // njd_fase= numero dei giorni giuliani.\nreturn njd_fase;\n\n}", "getResultatCodificat(){ // SI EL MÈTODE NO PASSA ALGUN VALOR, SE LI POSSA this. MÉS EL ATRIBUT CORRESPONENT.\n this.eliminarEspaisBlanc();\n this.senseAccent();\n for (var i = 0; i < this._entrada.length; i++){\n\n // IGUALEM LA LLARGADA DE LA CLAU A LA DE L'ENTRADA\n var y = 0;\n var max_lenght = this._entrada.length;\n while (this._entrada.length != this._clau.length){\n\n this._clau = this._clau + this._clau[y];\n\n if(y >= max_lenght){\n\n y = 0;\n }\n else{\n\n y++;\n }\n }\n\n // BUSQUEM ON ESTAN SITUATS TANT LA LLETRA DE L'ENTRADA COM DE LA CLAU\n var posicio_lletra_entrada = this._alfabet.indexOf(this._entrada[i]);\n var posicio_lletra_clau = this._alfabet.indexOf(this._clau[i]);\n\n // SUMEM LES DUES POSICIONS\n var suma_posicions = posicio_lletra_entrada + posicio_lletra_clau;\n\n // ANEM RESTANT MENTRE QUE EL MOD SIGUI MÉS GRAN QUE EL LENGTH DEL ABECEDARI\n while (suma_posicions >= this._alfabet.length){\n\n suma_posicions = suma_posicions - this._alfabet.length;\n }\n \n // ARA BUSQUEM LA LLETRA AMB LA QUAL SUBSTITUIREM L'ENTRADA\n this._resultat = this._resultat + this._alfabet[suma_posicions];\n }\n\n // RETORNEM EL RESULTAT\n return (document.form.sortida.value = this._resultat);\n }", "function TipoDescuento2(){\n //recuperamos el valor descuento 2 anterior\n var descuento2=document.getElementById(\"tipo_des2\").value;\n \n //recuperamos el sueldo neto del input\n var SueldoNeto=document.getElementById('sueldoNeto').value;\n //si anteriormente ya tenia un valor, debe reestablecer\n if(descuento2 > 0)\n {\n var suma=parseFloat(SueldoNeto) + parseFloat(descuento2);\n document.getElementById(\"sueldoNeto\").value=suma;\n }\n var monto= document.getElementById('tipoDescuento2').value;\n document.getElementById(\"tipo_des2\").value=monto;\n //Actualiza el neto a cobrar\n var SaldoNeto= document.getElementById('sueldoNeto').value;\n document.getElementById(\"sueldoNeto\").value=SaldoNeto-monto;\n \n //codigo de descuento la cual guardaremos\n var posicion=document.getElementById('tipodescuento2').options.selectedIndex;\n var codigoDescuento2=document.getElementById('tipodescuento2').options[posicion].value;\n document.getElementById(\"cod_des2\").value=codigoDescuento2;\n //guardamos el valor de salario neto(esto se actualizara con cada descuento)\n var sueldoneto=document.getElementById('sueldoNeto').value;\n document.getElementById(\"sal_neto\").value=sueldoneto;\n }", "async function pedidogen() {\r\n let pedido_buscar = await Pedidocounter.find({});\r\n let fecha = new Date().toISOString().slice(0, 10);\r\n let verificar = false;\r\n verificar = isEmpty(pedido_buscar);\r\n if (verificar == true) {\r\n let numero = fecha.split(\"-\");\r\n numero.push(\"1\");\r\n numero = numero.join(\"-\");\r\n return numero;\r\n } else {\r\n fecha1 = fecha.split(\"-\");\r\n let counter = pedido_buscar[0];\r\n let counter1 = counter.pedido_counter;\r\n counter1 = counter1.split(\"-\");\r\n /*\r\n mesBd = counter1[1];\r\n diaBd = counter1[2];\r\n mesNow = fecha1[1];\r\n diaNow = fecha1[2];\r\n mes = Math.abs(mesBd - mesNow);\r\n dia = Math.abs(diaBd - diaNow);\r\n */\r\n anioBD = counter1[0];\r\n anioNow = fecha[0];\r\n anio = Math.abs(anioNow - anioBD);\r\n if (anio == 0) {\r\n fechacompro = '\"' + fecha;\r\n let counter2 = parseInt(counter1[3]) + 1;\r\n counter2 = counter2.toString();\r\n let numero = fecha.split(\"-\");\r\n numero.push(counter2);\r\n numero = numero.join(\"-\");\r\n return numero;\r\n } else {\r\n let numero = fecha.split(\"-\");\r\n numero.push(\"1\");\r\n numero = numero.join(\"-\");\r\n return numero;\r\n }\r\n }\r\n}", "function miFuncion(){}", "function miFuncion(){}", "function miFuncion(){}", "function TipoDescuento3(){\n //recuperamos el valor descuento 3 anterior\n var descuento3=document.getElementById(\"tipo_des3\").value;\n \n //recuperamos el sueldo neto del input\n var SueldoNeto=document.getElementById('sueldoNeto').value;\n //si anteriormente ya tenia un valor, debe reestablecer\n if(descuento3 > 0)\n {\n var suma=parseFloat(SueldoNeto) + parseFloat(descuento3);\n document.getElementById(\"sueldoNeto\").value=suma;\n }\n \n var monto= document.getElementById('tipoDescuento3').value;\n document.getElementById(\"tipo_des3\").value=monto;\n //Actualiza el neto a cobrar\n var SaldoNeto= document.getElementById('sueldoNeto').value;\n document.getElementById(\"sueldoNeto\").value=SaldoNeto-monto;\n \n //codigo de descuento la cual guardaremos\n var posicion=document.getElementById('tipodescuento3').options.selectedIndex;\n var codigoDescuento3=document.getElementById('tipodescuento3').options[posicion].value;\n document.getElementById(\"cod_des3\").value=codigoDescuento3;\n //guardamos el valor de salario neto(esto se actualizara con cada descuento)\n var sueldoneto=document.getElementById('sueldoNeto').value;\n document.getElementById(\"sal_neto\").value=sueldoneto;\n }", "efficacitePompes(){\n\n }", "function verifReglement() {\n\n\tvar choix = document.getElementById('frmDifference').hdnChoix.value;\n\tvar du = parseFloat (document.getElementById('frmDifference').txtDu.value);\n\tvar encaisse = parseFloat (document.getElementById('frmDifference').txtEncaisse.value);\n\n\tif ( du > 0 ) {\n\n\t\tif ( choix == 'ESP' ) {\n\n\t\t\tif ( encaisse != 0 && encaisse >= du ) {\n\n\t\t\t\treturn true;\n\n\t\t\t} else {\n\n\t\t\t\tdocument.getElementById('frmDifference').txtEncaisse.select();\n\t\t\t\tdocument.getElementById('frmDifference').txtEncaisse.focus();\n\t\t\t\treturn false;\n\n\t\t\t}\n\n\t\t} else if ( choix == 'DIF' ) {\n\n\t\t\tif ( document.getElementById('frmDifference').txtDatePaiement.value ) {\n\n\t\t\t\treturn true;\n\n\t\t\t} else {\n\n\t\t\t\tdocument.getElementById('frmDifference').txtDatePaiement.select();\n\t\t\t\tdocument.getElementById('frmDifference').txtDatePaiement.focus();\n\t\t\t\treturn false;\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\treturn true;\n\n\t\t}\n\n\t} else {\n\n\t\treturn false;\n\n\t}\n}", "function Suma(one, two) {\n let resultado = one + two;\n //console.log(suma)\n // return te permite regresar un valor de esa funcion\n return resultado;\n}", "get saldo() {\n\t\treturn this.ingreso - this.deuda\n\t}", "function checaDiferencia1() //Verifica que la diferencia sea 0, si es cero elimina las comas de los valores\n {\n totDif=0;\n for ( i=0; i < numFilasPi; i=i+4)\n {\n elemento=\"form1:table1:\"+i+\":diferencia\";\n dif=document.getElementById(elemento).innerHTML;\n dif=parseFloat(eliminacomas(dif));\n totDif=totDif+dif;\n \n }\n if (totDif!=0)\n {\n alert(\"No se puede actualizar calendario porque existen diferencias !!\");\n return false; \n }\n else\n {\n \n for ( i=0; i < numFilasPi; i=i+4)\n {\n for (j=0; j<12; j++)\n {\n elemento=\"form1:table1:\"+i+\":\"+mes[j]; \n valor = parseFloat(eliminacomas(document.form1.elements[elemento].value));\n document.form1.elements[elemento].value = valor;\n }\n }\n \n return true;\n } \n }", "function funcion() {\n return numeracion;\n}", "function escrever(){\n //.value para saber o valor de um input\n var minhaIdade = ano.value - anoNascimento\n resposta.textContent = minhaIdade\n}", "saludar(fn){//recepcion de funcion\n var {nombre, apellido}=this //desgrloce de variables\n console.log(`Hola me llamo ${nombre} ${apellido}`)\n if(fn){\n fn(nombre, apellido, true)\n }\n }", "saludar(fn){\n console.log(`Hola me llamo ${this.nombre} ${this.apellido}`)\n if(fn){\n fn(this.nombre,this.apellido, false)\n }\n }", "function calculTempsPreparationRestant(commandes){\n angular.forEach(commandes,function(commande){\n angular.forEach(commande.detailCommandes,function(detailCommande){\n detailCommande.plat.dureePreparation = getDureeRestant(commande.dateCommande,detailCommande.plat.dureePreparation*1000)*detailCommande.quantite;\n })\n });\n }", "function contrari(fantasma){\n var vContrari;\r\n if(fantasma[3] == 1) vContrari = 3;\n if(fantasma[3] == 2) vContrari = 4;\n if(fantasma[3] == 3) vContrari = 1;\n if(fantasma[3] == 4) vContrari = 2;\n return vContrari;\r\n}", "function miFuncion (){}", "function actualizarProtesisf(diente, codigopieza){\n\t\t\n\t\tvar actualizarProtesis = false;\n\t\tvar error = false;\n\t\n\t\tvar tratamiento_abierto_protesis = ko.utils.arrayFilter(vm.tratamientosAplicados(), function(t){\n\t\t var eldiente = t.diente.id.toString(); \n \n // SI no tienes guiones y es protesis fija, esta incompleta la protesis fija\n\t\t if (eldiente.indexOf('_') <= -1 && t.tratamiento.id == codigopieza) { \n\t\t \terror = true;\n\t\t \tactualizarProtesis = true; // esto es para que no agregue un registro\n\n\t\t \tif((t.diente.id>=11 && t.diente.id<=28) && (diente.id>=11 && diente.id<=28)){\n\t\t \t\tt.diente.id += \"_\"+diente.id.toString();\n\t\t \t error = false;\n\t\t \t}\n\t\t \tif((t.diente.id>=51 && t.diente.id<=65) && (diente.id>=51 && diente.id<=65)){\n\t\t \t\tt.diente.id += \"_\"+diente.id.toString();\n\t\t \t error = false;\n\t\t \t}\n\t\t \tif((t.diente.id>=71 && t.diente.id<=85) && (diente.id>=71 && diente.id<=85)){\n\t\t \t\tt.diente.id += \"_\"+diente.id.toString();\n\t\t \t error = false;\n\t\t \t}\n\t\t \tif((t.diente.id>=31 && t.diente.id<=48) && (diente.id>=31 && diente.id<=48)){\n\t\t \t\tt.diente.id += \"_\"+diente.id.toString();\n\t\t \t error = false;\n\t\t \t}\n\n\t\t \t} \n\t\t});\t\n\n\t\tvar salida=[actualizarProtesis,error];\n\t\treturn salida;\n\n }", "function cumpleanosDos(persona){\n\n return {\n \n ...persona,\n edad: persona.edad + 1\n\n }\n\n /* Aqui lo que hacemos es retornar un nuevo objeto con los atributos de la\n persona y podremos cambiar los atributos y agregar atributos nuevos\n \n Esto arreglara el problema de que cuando se invoque la funcion tambien se\n cambie el objeto, con este ejemplo retornara un objeto nuevo con la \n edad modificada y si vemos el objeto este no tendra ningun cambio\n \n \n */\n}", "function validar(){\r\n\tvar funcion=document.getElementById('funcion').value;\r\n\tvar fun=document.getElementById('fun').value;\r\n\tvar a=document.getElementById('aa').value;\r\n\tvar enlace=document.getElementById('enlace');\r\n\r\n\tif(funcion==''){alert('Ingrese su g(x)');}\r\n\tif(fun==''){alert('Ingrese su f(x)');}\r\n\tif(a==''){alert('Ingrese el valor de la primera aproximacion');}\r\n\r\n\tvar derivada = math.derivative(funcion, 'x').eval({x: a})\r\n\tderivada = Math.abs(derivada);\r\n console.log(derivada);\r\n \t\r\n\r\n\tif(funcion!='' && a!='' && fun!=''){\r\n\t\tif(derivada>1){\r\n\t\t\talert('No existe raiz en el intervalo ingresado');\r\n\t\t}else{\r\n\t\t\tenlace.href=\"#tabla\"\r\n\t\t\tmostrarTabla();\r\n\t\t}\r\n\t}\r\n\r\n}", "function adivinarSexoEstudiante(estudiantes) {\n //valor que se utilizará para comparar\n var resultado = 100000;\n //tupla que almacenará la posición más cercana \n var numeroTupla = 0;\n //for que recorre todos los datos como parámetro de la consulta \n //de la tabla de estudiantes\n for (var i = 0; i < estudiantes.length; i++) {\n var recintoTupla = 1;\n var estiloTupla = 0;\n \n \n //se le da valor a los recintos que pertenecen las personas en las\n //tuplas si es paraíso es 1 y turrialba es 2 \n if (estudiantes[i].recinto === 'Turrialba') {\n recintoTupla = 2;\n }\n //se elige el estilo de aprendizaje y se le asigna un valor\n //de 1 a 4\n switch (estudiantes[i].estilo) {\n case 'DIVERGENTE':\n estiloTupla = 1;\n break;\n case 'CONVERGENTE':\n estiloTupla = 2;\n break;\n case 'ASIMILADOR':\n estiloTupla = 3;\n break;\n case 'ACOMODADOR':\n estiloTupla = 4;\n break;\n }\n \n //distancia euclidiana aplicada a los valores de las tuplas para definir distancia\n var sumatoria = Math.pow((estiloTupla - (parseInt(document.getElementById('estilo').value))), 2) + Math.pow(recintoTupla - (parseInt(document.getElementById('recinto').value)), 2) + Math.pow((parseFloat(estudiantes[i].promedio)) - (parseFloat(document.getElementById('promedio').value)), 2);\n var distancia = Math.sqrt(sumatoria);\n \n //aquí comparan para mostrar el más cercano al que entra como parámetro\n //comparando los datos de la tupla y los ingresados\n if (resultado > distancia) {\n resultado = distancia;\n numeroTupla = i;\n } \n }\n \n //if para mostrar el sexo en la pantalla dependiendo de la tupla\n if(estudiantes[numeroTupla].sexo === 'M')\n document.getElementById('mensaje3').innerHTML = 'Su sexo es: Masculino y el número de tupla es: '+estudiantes[numeroTupla].id+'.';\n else\n document.getElementById('mensaje3').innerHTML = 'Su sexo es: Femenino y el número de tupla es: '+estudiantes[numeroTupla].id+'.';\n}", "function controllaDati() {\r\n\t\tvar err=false;\r\n\t\tvar check=true;\r\n\t\tvar elem = document.getElementById(\"nomeRicetta\");\r\n\t\tif(elem.value.length == 0) {\r\n\t\t\t\tdocument.getElementById(\"nomeRicettaErr\").innerHTML= \"Inserisci il titolo\";\r\n\t\t\t\terr=true;\r\n\t\t\t\tcheck=false;\r\n\t\t} else {\r\n\t\t\t\tdocument.getElementById(\"nomeRicettaErr\").innerHTML= \"\";\r\n\t\t}\r\n\t\telem = document.getElementById(\"nomeAutore\");\r\n\t\tif( elem.value.length==0 ) {\r\n\t\t\t\tdocument.getElementById(\"nomeAutoreErr\").innerHTML= \"Inserisci il nome dell'autore\";\r\n\t\t\t\terr=true;\r\n\t\t\t\tcheck=false;\r\n\t\t} else {\r\n\t\t\t\tdocument.getElementById(\"nomeAutoreErr\").innerHTML= \"\";\r\n\t\t}\r\n\t\telem = document.getElementById(\"areaProcedimento\");\r\n\t\tif( elem.value.length==0 ) {\r\n\t\t\t\tdocument.getElementById(\"areaProcedimentoErr\").innerHTML= \"Inserisci il procedimento\";\r\n\t\t\t\terr=true;\r\n\t\t\t\tcheck=false;\r\n\t\t} else {\r\n\t\t\t\tdocument.getElementById(\"areaProcedimentoErr\").innerHTML= \"\";\r\n\t\t}\r\n\t\telem = document.getElementById(\"ingrediente0\");\r\n\t\tif( elem.value.length==0 ) {\r\n\t\t\t\tdocument.getElementById(\"ingrediente0Err\").innerHTML= \"<p>Inserisci almeno il primo ingrediente</p>\";\r\n\t\t\t\terr=true;\r\n\t\t\t\tcheck=false;\r\n\t\t} else {\r\n\t\t\t\tdocument.getElementById(\"ingrediente0Err\").innerHTML= \"\";\r\n\t\t}\r\n\t\telem = document.getElementById(\"quantita0\");\r\n\t\tif( isNaN(elem.value) || parseInt(elem.value)<0 || parseInt(elem.value) > 9999) {\r\n\t\t\t\tdocument.getElementById(\"quantitaN0Err\").innerHTML= \"La quantità deve essere numerica\";\r\n\t\t\t\terr=true;\r\n\t\t\t\tcheck=false;\r\n\t\t} else {\r\n\t\t\t\tdocument.getElementById(\"quantitaN0Err\").innerHTML= \"\";\r\n\t\t}\r\n\t\tif (check==false) {\r\n\t\t\treturn !err;\r\n\t\t}\r\n\t\t\r\n}", "function fun1(){} //toda a função de js retorna alguma coisa", "function eq_tempo_data(anno,njd){\n\n // funzione per il calcolo dell'equazione del tempo.\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) dicembre 2009\n // algoritmo di P.D. SMITH.\n\n njd=jdHO(njd)+0.5; // riporta il g.g. della data al mezzogiorno. \n \nvar ar_sole=pos_sole(njd); // calcolo dell'ascensione retta del sole.\nvar Tempo_medio_Greenw=tsg_tmg_data(ar_sole[0],anno,njd); // tempo medio di Greenwich.\nvar valore_et=12-Tempo_medio_Greenw; // valore dell'equazione del tempo.\n\n valore_et=valore_et*60; // valore in minuti.\n\n valore_et=valore_et.toFixed(6);\n\nreturn valore_et\n\n}", "function esquiver() \n{\n //Cas spéciaux : Mort, ou pas d'ennemi\n if (presenceEnnemi === 666){\n dialogBox(\"Eh me saoule pas là relance le jeu ou casse toi connard J'AI AUTRE CHOSE A FOUTRE LA.\")\n \n }else if(presenceEnnemi ===0){ \n dialogBox(\"Tu donnes l'impression de danser sur les chemins, c'est mignon mais ça va pas t'aider.\")\n }\n \n //PROCEDURE HABITUELLE\n else if (presenceEnnemi = 1, tourJoueur(tour)=== true){\n var Min= Number(personnage.esquive - 5)\n var Max= Number(personnage.esquive + 15)\n var Miin = Number(1)\n var Maax = Number(100)\n function getRndInterger(min, max) {\n return Math.floor(Math.random() * (max - min + 1) ) + min;}\n\njetEsquive = getRndInterger(Min, Max);\nvaleurEsquive = getRndInterger(Miin, Maax);\nconsole.log(\"jetEsquive du joueur : \"+jetEsquive+\" et la valeur minimale à avoir était \"+valeurEsquive);\n //Esquive réussie\n if (jetEsquive >= valeurEsquive){\n actionPerso = 2;\n } \n //Echec de l'esquive\n else if (jetEsquive < valeurEsquive){\n actionPerso = 3;\n }\nreactionEnnemi();\nresetSpecial();\n }\n \n}", "function falso(){\n\tif(cont==2||cont==3||cont==5||cont==6||cont==7||cont==8||cont==10||cont==11||cont==13||cont==17||cont==19){\n\t\talert(\"ESA ES MI CHICA! CORRECTO\");\n\t\tpuntos = puntos + 1;\n\t}else{\n\t\talert(\"MALA NOVIA!!! ERROR\");\n\t}\n\tconsole.log(puntos);\n\tcambiarPagina();\n}" ]
[ "0.6130146", "0.6073634", "0.6020267", "0.6007445", "0.59536994", "0.5925734", "0.59139097", "0.58795923", "0.5870959", "0.5862134", "0.58434796", "0.5808702", "0.58043987", "0.5781277", "0.5774835", "0.57675636", "0.5759565", "0.5758692", "0.5752386", "0.57417756", "0.57195956", "0.5707791", "0.5701638", "0.56929445", "0.5692057", "0.56845134", "0.56836253", "0.56836253", "0.56836253", "0.56836253", "0.5682979", "0.56759846", "0.56725067", "0.56699324", "0.5664414", "0.566379", "0.5663134", "0.5662833", "0.56604534", "0.5648012", "0.5646592", "0.5633405", "0.56296915", "0.5627833", "0.560768", "0.56073964", "0.5605985", "0.5604886", "0.56042373", "0.5602938", "0.5597953", "0.55972725", "0.5586687", "0.5585336", "0.5584276", "0.557892", "0.55761737", "0.5571401", "0.5571233", "0.557101", "0.5570319", "0.55680394", "0.5565674", "0.55591756", "0.55590874", "0.55555445", "0.555041", "0.5548478", "0.55465096", "0.5545378", "0.5543071", "0.55410326", "0.5540318", "0.55401134", "0.55336607", "0.5520809", "0.5516153", "0.5516153", "0.5516153", "0.5510742", "0.550762", "0.54989314", "0.54975677", "0.5494575", "0.5489007", "0.5483815", "0.5482318", "0.548175", "0.5479947", "0.5471968", "0.54705673", "0.546576", "0.54656875", "0.54633456", "0.54581374", "0.5457088", "0.5454026", "0.54522896", "0.5451968", "0.54450786", "0.5444015" ]
0.0
-1
Resets sorting criterias to defaults
function switchSortCriterias(qDef){ qDef.qSortCriterias.forEach((sortCrit, i) => { qDef.qSortCriterias[i].qSortByStateCheck = false; qDef.qSortCriterias[i].qSortByState = 0; qDef.qSortByState = 0; qDef.qSortByStateCheck = false; qDef.qSortCriterias[i].qSortByLoadOrderCheck = true; qDef.qSortCriterias[i].qSortByLoadOrder = 1; qDef.qSortByLoadOrder = 1; qDef.qSortByLoadOrderCheck = true; qDef.qSortCriterias[i].qSortByAsciiCheck = true; qDef.qSortCriterias[i].qSortByAscii = 1; qDef.qSortByAscii = 1; qDef.qSortByAsciiCheck = true; qDef.qSortCriterias[i].qSortByNumericCheck = false; qDef.qSortCriterias[i].qSortByNumeric = 0; qDef.qSortByNumeric = 0; qDef.qSortByNumericCheck = false; qDef.qSortCriterias[i].qSortByFrequencyCheck = false; qDef.qSortCriterias[i].qSortByFrequency = 0; qDef.qSortByFrequency = 0; qDef.qSortByFrequencyCheck = false; qDef.qSortCriterias[i].qSortByExpressionCheck = false; qDef.qSortCriterias[i].qExpression = { qv: ''}; qDef.qExpression = { qv: ''}; qDef.qSortByExpressionCheck = false; }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "resetSorting() {\n this.sortBy = undefined;\n this.sortDir = 0;\n }", "clearSort() {\r\n this.sortBy(null);\r\n }", "set overrideSorting(value) {}", "resetSorting() {\n this.sortings = [];\n }", "resetSortState() {\n this.props.dispatch(couponsActions.toggleSort(false, 4, 'Recommended'));\n this.props.dispatch(couponsActions.setSortResults([]));\n }", "function resort(){\n if(scope.sorting && scope.sorting.obj){\n var sortKey = scope.sorting.obj.field;\n sorter(sortKey,scope.sorting.direction);\n }\n }", "function resort(){\n if(scope.sorting && scope.sorting.obj){\n var sortKey = scope.sorting.obj.field;\n sorter(sortKey,scope.sorting.direction);\n }\n }", "function initializeSortingState() {\n let datasetFields = Object.values(classNameToKeyMap);\n datasetFields.forEach(function(field) {\n ascendingOrder[field] = false;\n });\n}", "clearSort() {\n this.sort([]);\n }", "changeSorting() {\n this.currentlySelectedOrder =\n (this.currentlySelectedColumn === this.columnName) ? !this.currentlySelectedOrder : false;\n this.currentlySelectedColumn = this.columnName;\n }", "function clearAllSorts() {\n\n // Loop over all the columns, set sort properties to null\n _.each(properties.sortColumns, function (item) {\n item.enhancedTable.sort.position = null;\n item.enhancedTable.sort.direction = null;\n });\n\n // Update the headers with the sort information (graphic, position)\n updateTableHeaders();\n\n }", "function _fakeSort() {\n var resultsEls = $( '.all-results .search-result-full' ).get();\n var sortOn = this.attributes[\"sort-trigger\"].value;\n\n // toggle the classes\n $( '.search-results-order .selected' ).removeClass('selected');\n $( this ).addClass('selected');\n\n // change our parent sort val\n $( '.search-step-3' ).attr('sort', sortOn);\n\n $( resultsEls.reverse() ).each(function() {\n $(this).detach().appendTo('.all-results');\n });\n }", "set sortingOrder(value) {}", "function sort () {\n index++;\n predicate = ng.isFunction(getter(scope)) ? getter(scope) : attr.stSort;\n if (index % 3 === 0 && attr.stSkipNatural === undefined) {\n //manual reset\n index = 0;\n ctrl.tableState().sort = {};\n ctrl.tableState().pagination.start = 0;\n ctrl.pipe();\n } else {\n ctrl.sortBy(predicate, index % 2 === 0);\n }\n }", "_resetOldSorting() {\n const rowChildren = this.shadowRoot.querySelectorAll('.th[sorted]');\n rowChildren.forEach((el) => el.removeAttribute('sorted'));\n }", "clearSorters() {\n const me = this;\n me.sorters.length = 0;\n me.sort();\n }", "clearSorters() {\n const me = this;\n\n me.sorters.length = 0;\n\n me.sort();\n }", "sort() {\n if (this.sortOrder === 'asc') {\n this.set('sortOrder', 'desc');\n\n } else if (this.sortOrder === '') {\n this.set('sortOrder', 'asc');\n\n } else {\n this.set('sortOrder', '');\n\n }\n }", "get overrideSorting() {}", "function toogleSort(){\r\n\t\tif(settings.sort_type=='desc'){\r\n\t\t\tsettings.sort_type='asc';\r\n\t\t }else{\r\n\t\t\t settings.sort_type='desc';\r\n\t\t }\r\n\t}", "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 refreshSortPriorities() {\n\tfor (filterId in Filters) {\n\t\tvar f = Filters[filterId];\n\n\t\tif (f.Priority > 0) {\n\t\t\t$(\"#\" + f.Column.OrderButtonName).text(f.Priority);\n\t\t}\n\t}\n}", "_sortValues() {\n if (this.multiple) {\n const options = this.options.toArray();\n this._selectionModel.sort((a, b) => {\n return this.sortComparator ? this.sortComparator(a, b, options) :\n options.indexOf(a) - options.indexOf(b);\n });\n this.stateChanges.next();\n }\n }", "setSortByPopular() {\n this.setSort(SortbyContainer.SORT_BY_POPULAR);\n }", "reset () {\n this.setState({\n sortType: ''\n });\n this.state.filter.resetFilter();\n }", "function clearSortOrder(){\n var view = tabsFrame.newView;\n var index = view.tableGroups.length - tabsFrame.selectedTableGroup - 1;\n var curTgrp = view.tableGroups[index];\n \n curTgrp.sortFields = \"\";\n /*\n if (hasGroupByDate(curTgrp)){\n var groupByDate = curTgrp.sortFields[0].groupByDate;\n if ((groupByDate == 'year') || (groupByDate == 'month') || (groupByDate == 'quarter') || (groupByDate == 'day') || (groupByDate == 'week')){\n curTgrp.sortFields = new Array();\n }\n }\n */\n resetTable('sortOrderSummary');\n onLoadSortSummary();\n \t\n tabsFrame.newView = view;\n myTabsFrame.selectTab('page4c');\n \n}", "sort(predicate) {\n if (this._multiple && this.selected) {\n this._selected.sort(predicate);\n }\n }", "function sortBy(value) {\n if ($scope.sort[value] === null) {\n $scope.sort.first = null;\n $scope.sort.last = null;\n $scope.sort.company = null;\n $scope.sort.address = null;\n $scope.sort[value] = true;\n } else {\n $scope.sort[value] = !$scope.sort[value];\n }\n }", "function setSort(x) { //these 3 functions are connected to the event of the buttons\n sortby = x;\n updateDoctorsList(); //they then invoke updatedoctorslist, that is meant to access the doctors on the server with the current criteria, the fetch..\n}", "_resort() {\n // Ensure there's something to do.\n if (!this.orderComponents) return;\n\n // Define the comparator for the sort.\n /**\n * Return a comparison result for the two given models, honouring each\n * comparitor in order of their inclusion in the component list. \n */\n const compareModels = (a, b) => {\n for (let i = 0; i < this.orderComponents.length; i++) {\n // Comprehend this order component.\n const {\n identity: {attribute, type}, value: direction\n } = this.orderComponents[i];\n\n // Use the type comparator to retrieve and integer result of\n // the comparison.\n let value = type.compareValues(a[attribute], b[attribute]);\n // Modify based on order.\n if (direction == 'desc') value *= -1;\n // If this comparator found a difference between the two,\n // return it. Note that if it didn't, the next gets a chance\n // to.\n if (value > 0 || value < 0) return value;\n }\n\n return 0;\n };\n\n // Perform the sort.\n this._value.sort(compareModels);\n }", "function removeSort() {\n if (numberOfSorts > 0) {\n $(\"#thenBy\" + numberOfSorts).val(\"\");\n $(\"#thenBy\" + numberOfSorts).hide(\"fast\");\n numberOfSorts--;\n }\n checkSorts();\n}", "function setSortPref(newPref) {\n \n var filter = $(\"#search-input\").val();\n if (!filter) {\n filter = \"\";\n }\n \n displContactList.setSortPref(newPref, filter);\n}", "function sort () {\n if (descendingFirst) {\n index = index === 0 ? 2 : index - 1;\n } else {\n index++;\n }\n\n var func;\n predicate = ng.isFunction(getter(scope)) || ng.isArray(getter(scope)) ? getter(scope) : attr.stSort;\n if (index % 3 === 0 && !!skipNatural !== true) {\n //manual reset\n index = 0;\n ctrl.tableState().sort = {};\n ctrl.tableState().pagination.start = 0;\n func = ctrl.pipe.bind(ctrl);\n } else {\n func = ctrl.sortBy.bind(ctrl, predicate, index % 2 === 0);\n }\n if (promise !== null) {\n $timeout.cancel(promise);\n }\n if (throttle < 0) {\n func();\n } else {\n promise = $timeout(func, throttle);\n }\n }", "function applyOrder( toData ) {\n var sortField = '', sortDir = 0;\n if( args.options && args.options.sort ) {\n if( args.options.sort.max ) {\n sortField = 'max';\n sortDir = args.options.sort.max;\n }\n if( args.options.sort.min ) {\n sortField = 'min';\n sortDir = args.options.sort.min;\n }\n if( args.options.sort.unit ) {\n sortField = 'unit';\n sortDir = args.options.sort.unit;\n }\n if( args.options.sort.type ) {\n sortField = 'type';\n sortDir = args.options.sort.type;\n }\n }\n\n if( '' !== sortField ) {\n if( 1 === sortDir ) {\n toData.sort( orderDataAsc );\n } else {\n toData.sort( orderDataDesc );\n }\n }\n\n function orderDataAsc( a, b ) {\n if( a[sortField] < b[sortField] ) {\n return -1;\n }\n if( a[sortField] > b[sortField] ) {\n return 1;\n }\n return 0;\n }\n\n function orderDataDesc( a, b ) {\n if( a[sortField] > b[sortField] ) {\n return -1;\n }\n if( a[sortField] < b[sortField] ) {\n return 1;\n }\n return 0;\n }\n\n }", "function sortby(picked) {\n // Based on what we picked, style spans and trigger sorting functions \n if (picked==1){$('#by-date').removeClass('sort-selected');$('#by-cat').addClass('sort-selected');catsort();}\n if (picked==0){$('#by-cat').removeClass('sort-selected');$('#by-date').addClass('sort-selected');datesort();}\n}", "function sortby(picked) {\n // Based on what we picked, style spans and trigger sorting functions \n if (picked==1){$('#by-date').removeClass('sort-selected');$('#by-cat').addClass('sort-selected');catsort();}\n if (picked==0){$('#by-cat').removeClass('sort-selected');$('#by-date').addClass('sort-selected');datesort();}\n}", "function Sort() {}", "sort(predicate) {\n if (this._multiple && this.selected) {\n this._selected.sort(predicate);\n }\n }", "sort(predicate) {\n if (this._multiple && this.selected) {\n this._selected.sort(predicate);\n }\n }", "function sort() {\n index++;\n var func;\n predicate = ng.isFunction(getter(scope)) || ng.isArray(getter(scope)) ? getter(scope) : attr.ltSort;\n if (index % 3 === 0 && !!skipNatural !== true) {\n //manual reset\n index = 0;\n ctrl.tableState().sort = {};\n ctrl.tableState().pagination.start = 0;\n func = ctrl.pipe.bind(ctrl);\n } else {\n func = ctrl.sortBy.bind(ctrl, predicate, index % 2 === 0);\n }\n if (promise !== null) {\n $timeout.cancel(promise);\n }\n if (throttle < 0) {\n scope.$apply(func);\n } else {\n promise = $timeout(func, throttle);\n }\n }", "clearSort() {\n this.setState({\n colSortDirs: [],\n firstSortColumn: '',\n secondSortColumn: '',\n thirdSortColumn: '',\n\n columnSortData: {}\n })\n }", "updateSorters(sortColumns, presetSorters) {\n let currentSorters = [];\n const odataSorters = [];\n if (!sortColumns && presetSorters) {\n // make the presets the current sorters, also make sure that all direction are in lowercase for OData\n currentSorters = presetSorters;\n currentSorters.forEach((sorter) => sorter.direction = sorter.direction.toLowerCase());\n // display the correct sorting icons on the UI, for that it requires (columnId, sortAsc) properties\n const tmpSorterArray = currentSorters.map((sorter) => {\n const columnDef = this._columnDefinitions.find((column) => column.id === sorter.columnId);\n odataSorters.push({\n field: columnDef ? ((columnDef.queryFieldSorter || columnDef.queryField || columnDef.field) + '') : (sorter.columnId + ''),\n direction: sorter.direction\n });\n // return only the column(s) found in the Column Definitions ELSE null\n if (columnDef) {\n return {\n columnId: sorter.columnId,\n sortAsc: sorter.direction.toUpperCase() === SortDirection.ASC\n };\n }\n return null;\n });\n // set the sort icons, but also make sure to filter out null values (that happens when columnDef is not found)\n if (Array.isArray(tmpSorterArray)) {\n this._grid.setSortColumns(tmpSorterArray);\n }\n }\n else if (sortColumns && !presetSorters) {\n // build the SortBy string, it could be multisort, example: customerNo asc, purchaserName desc\n if (sortColumns && sortColumns.length === 0) {\n // TODO fix this line\n // currentSorters = new Array(this.defaultOptions.orderBy); // when empty, use the default sort\n }\n else {\n if (sortColumns) {\n for (const columnDef of sortColumns) {\n if (columnDef.sortCol) {\n let fieldName = (columnDef.sortCol.queryFieldSorter || columnDef.sortCol.queryField || columnDef.sortCol.field) + '';\n let columnFieldName = (columnDef.sortCol.field || columnDef.sortCol.id) + '';\n let queryField = (columnDef.sortCol.queryFieldSorter || columnDef.sortCol.queryField || columnDef.sortCol.field || '') + '';\n if (this._odataService.options.caseType === CaseType.pascalCase) {\n fieldName = titleCase(fieldName);\n columnFieldName = titleCase(columnFieldName);\n queryField = titleCase(queryField);\n }\n if (columnFieldName !== '') {\n currentSorters.push({\n columnId: columnFieldName,\n direction: columnDef.sortAsc ? 'asc' : 'desc'\n });\n }\n if (queryField !== '') {\n odataSorters.push({\n field: queryField,\n direction: columnDef.sortAsc ? SortDirection.ASC : SortDirection.DESC\n });\n }\n }\n }\n }\n }\n }\n // transform the sortby array into a CSV string for OData\n currentSorters = currentSorters || [];\n const csvString = odataSorters.map((sorter) => {\n let str = '';\n if (sorter && sorter.field) {\n const sortField = (this._odataService.options.caseType === CaseType.pascalCase) ? titleCase(sorter.field) : sorter.field;\n str = `${sortField} ${sorter && sorter.direction && sorter.direction.toLowerCase() || ''}`;\n }\n return str;\n }).join(',');\n this._odataService.updateOptions({\n orderBy: csvString\n });\n // keep current Sorters and update the service options with the new sorting\n this._currentSorters = currentSorters;\n // build the OData query which we will use in the WebAPI callback\n return this._odataService.buildQuery();\n }", "function setSort(objName) {\n vm.predicate = objName;\n vm.reverse = !vm.reverse;\n }", "function prepareSortingAndOrders(container) {\n\n\t\t\tvar opt = getOptions(container);\n\n\t\t\t/************************************************\n\t\t\t\t-\tHANDLING OF SORTING ISSUES -\n\t\t\t*************************************************/\n\n\t\t\t// PREPARE THE DATE SRINGS AND MAKE A TIMESTAMP OF IT\n\t\t\tcontainer.find('.tp-esg-item').each(function() {\n\t\t\t\tvar dd = new Date(jQuery(this).data('date'));\n\t\t\t\tjQuery(this).data('date',dd.getTime()/1000);\n\t\t\t})\n\n\t\t\tjQuery(opt.filterGroupClass+'.esg-sortbutton-order,'+opt.filterGroupClass+' .esg-sortbutton-order').each(function() {\n\t\t\t\tvar eso = jQuery(this);\n\t\t\t\teso.removeClass(\"tp-desc\").addClass(\"tp-asc\");\n\t\t\t\teso.data('dir',\"asc\");\n\t\t\t})\n\t}", "_sortFilters() {\n this.$filterSelects.each(function() {\n const $select = $(this);\n const $toSort = $select.find('option');\n const sortingFunction = sortingFunctions[$select.data('filters-type')];\n\n if (sortingFunction) {\n $toSort.sort((a, b) => {\n return sortingFunction($(a).val(), $(b).val());\n });\n }\n });\n }", "function setDefaults(scope) {\n if (typeof scope.enableFilter === 'undefined') {\n scope.enableFilter = true;\n scope.filters = {};\n }\n if (typeof scope.enableSort === 'undefined') {\n scope.enableSort = true;\n scope.sortColumn = undefined;\n scope.sortDirection = undefined;\n }\n if (scope.sortColumn !== undefined) {\n scope.sortDirection = \"asc\";\n }\n }", "function onSortValueChanged() {\n $scope.options.filter = { sort: $scope.sortValue };\n }", "sortDataset() {\n if (this.settings.disableClientSort) {\n this.restoreSortOrder = true;\n return;\n }\n\n if (this.settings.groupable && this.originalDataset) {\n this.settings.dataset = this.originalDataset;\n }\n const sort = this.sortFunction(this.sortColumn.sortId, this.sortColumn.sortAsc);\n\n this.saveDirtyRows();\n this.settings.dataset.sort(sort);\n this.setTreeDepth();\n this.restoreDirtyRows();\n\n // Resync the _selectedRows array\n if (this.settings.selectable) {\n this.syncDatasetWithSelectedRows();\n }\n }", "function initialSort() {\n var column, direction;\n column = $j('#paginationSort').val() || '';\n column = column.match(/none/) ? '' : column;\n direction = ($j('#paginationSortOrder').val() || '').match(/desc|false/) ? desc : asc\n return { column: column, direction: direction };\n }", "function supports_sort_by(sort) {\n $('input[name=\"supports_sort_by\"]').val(sort);\n $('.table-supports').DataTable().ajax.reload();\n $('input[name=\"supports_sort_by\"]').val('');\n}", "onSortChange(newSortSettings) {\n const comments = this.filterAndSort(this.state.comments,\n newSortSettings.comparator,\n this.state.commentFilter.filterFn);\n\n this.setState({\n comments: comments,\n sortSettings: newSortSettings\n });\n }", "function restoreSortOrder()\r\n\t{\r\n\t\tvar\t\tcolObject ;\r\n\t\t\r\n\t\tvar\t\tdoReverse = false;\r\n\t\tvar\t\tcol = class_sortColumn;\r\n\t\t\r\n\t\t\r\n\t\tif( class_sortColumn.charAt( 0 ) === '-' )\r\n\t\t{\r\n\t\t\tdoReverse = true;\r\n\t\t\tcol = class_sortColumn.substring( 1 );\r\n\t\t}\t\t\t\r\n\t\t\r\n\t\tfor ( idx = 0; idx < class_columnDefinitionArray.length ; idx++ )\r\n\t\t{\r\n\r\n\t\t\tif( class_columnDefinitionArray[ idx ].GetColName() == col )\r\n\t\t\t{\r\n\t\t\t\tcolObject = class_columnDefinitionArray[ idx ];\r\n\t\t\t\tclass_myRows.sort( colObject.SortComparitor ) ;\t\r\n\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t\tif( doReverse === true ) \r\n\t\t{\r\n\t\t\tclass_myRows.reverse();\r\n\t\t}\r\n\r\n\t\tclass_buildTable();\r\n\r\n\t}", "function sort(defaultStatusSort){\n\t\t$scope.defaultStatusSort = defaultStatusSort;\n\t\tif($scope.defaultStatusSort === true){\n\t\t\tvar list = $scope.opPatientList;\n\t\t\tif(enableStatusSort === true){\n\t\t\t\tfor(var i = 0; i < list.length; i++){\n\t\t\t\t\tfor(var j = i + 1; j < list.length; j++){\n\t\t\t\t\t\tif(list[j].status.toLowerCase() === 'new'){\n\t\t\t\t\t\t\tvar temp = list[i];\n\t\t\t\t\t\t\tlist[i] = list[j];\n\t\t\t\t\t\t\tlist[j] = temp;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$scope.opPatientList = list;\n\t\t\t\tenableStatusSort = false;\n\t\t\t}else{\n\t\t\t\tfor(var i = 0; i < list.length; i++){\n\t\t\t\t\tfor(var j = i + 1; j < list.length; j++){\n\t\t\t\t\t\tif(list[j].status.toLowerCase() === 'consulted'){\n\t\t\t\t\t\t\tvar temp = list[i];\n\t\t\t\t\t\t\tlist[i] = list[j];\n\t\t\t\t\t\t\tlist[j] = temp;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$scope.opPatientList = list;\n\t\t\t\tenableStatusSort = true;\n\t\t\t}\n\t\t\t$scope.defaultStatusSort = false;\n\t\t}else{\n\t\t\tvar list = $scope.opPatientList;\n\t\t\tif(enableDateSort === true){\n\t\t\t\tlist.sort(function(a,b){\n\t\t\t\t\tvar c = new Date(a.createdOn);\n\t\t\t\t\tvar d = new Date(b.createdOn);\n\t\t\t\t\treturn c - d;\n\t\t\t\t});\n\t\t\t\t$scope.opPatientList = list;\n\t\t\t\tenableDateSort = false;\n\t\t\t}else{\n\t\t\t\tlist.sort(function(a,b){\n\t\t\t\t\tvar c = new Date(a.createdOn);\n\t\t\t\t\tvar d = new Date(b.createdOn);\n\t\t\t\t\treturn d - c;\n\t\t\t\t});\n\t\t\t\t$scope.opPatientList = list;\n\t\t\t\tenableDateSort = true;\n\t\t\t}\n\t\t\t$scope.defaultStatusSort = true;\n\t\t}\n\t}", "changeSort(sort, sortAscending) {\n\t\tthis.fetchExternalData(\n\t\t\t\tthis.state.filter, \n\t\t\t\tthis.state.currentPage, \n\t\t\t\tthis.state.externalResultsPerPage,\n\t\t\t\tsort,\n\t\t\t\tsortAscending);\n }", "updateSorters(sortColumns, presetSorters) {\n let currentSorters = [];\n const odataSorters = [];\n if (!sortColumns && presetSorters) {\n // make the presets the current sorters, also make sure that all direction are in lowercase for OData\n currentSorters = presetSorters;\n currentSorters.forEach((sorter) => sorter.direction = sorter.direction.toLowerCase());\n // display the correct sorting icons on the UI, for that it requires (columnId, sortAsc) properties\n const tmpSorterArray = currentSorters.map((sorter) => {\n const columnDef = this._columnDefinitions.find((column) => column.id === sorter.columnId);\n odataSorters.push({\n field: columnDef ? ((columnDef.queryFieldSorter || columnDef.queryField || columnDef.field) + '') : (sorter.columnId + ''),\n direction: sorter.direction\n });\n // return only the column(s) found in the Column Definitions ELSE null\n if (columnDef) {\n return {\n columnId: sorter.columnId,\n sortAsc: sorter.direction.toUpperCase() === SortDirection.ASC\n };\n }\n return null;\n });\n // set the sort icons, but also make sure to filter out null values (that happens when columnDef is not found)\n if (Array.isArray(tmpSorterArray)) {\n this._grid.setSortColumns(tmpSorterArray);\n }\n }\n else if (sortColumns && !presetSorters) {\n // build the SortBy string, it could be multisort, example: customerNo asc, purchaserName desc\n if (sortColumns && sortColumns.length === 0) ;\n else {\n if (sortColumns) {\n for (const columnDef of sortColumns) {\n if (columnDef.sortCol) {\n let fieldName = (columnDef.sortCol.queryFieldSorter || columnDef.sortCol.queryField || columnDef.sortCol.field) + '';\n let columnFieldName = (columnDef.sortCol.field || columnDef.sortCol.id) + '';\n let queryField = (columnDef.sortCol.queryFieldSorter || columnDef.sortCol.queryField || columnDef.sortCol.field || '') + '';\n if (this._odataService.options.caseType === CaseType.pascalCase) {\n fieldName = titleCase(fieldName);\n columnFieldName = titleCase(columnFieldName);\n queryField = titleCase(queryField);\n }\n if (columnFieldName !== '') {\n currentSorters.push({\n columnId: columnFieldName,\n direction: columnDef.sortAsc ? 'asc' : 'desc'\n });\n }\n if (queryField !== '') {\n odataSorters.push({\n field: queryField,\n direction: columnDef.sortAsc ? SortDirection.ASC : SortDirection.DESC\n });\n }\n }\n }\n }\n }\n }\n // transform the sortby array into a CSV string for OData\n currentSorters = currentSorters || [];\n const csvString = odataSorters.map((sorter) => {\n let str = '';\n if (sorter && sorter.field) {\n const sortField = (this._odataService.options.caseType === CaseType.pascalCase) ? titleCase(sorter.field) : sorter.field;\n str = `${sortField} ${sorter && sorter.direction && sorter.direction.toLowerCase() || ''}`;\n }\n return str;\n }).join(',');\n this._odataService.updateOptions({\n orderBy: csvString\n });\n // keep current Sorters and update the service options with the new sorting\n this._currentSorters = currentSorters;\n // build the OData query which we will use in the WebAPI callback\n return this._odataService.buildQuery();\n }", "inverseSorting() {\n if (this.get('order') === 'asc') {\n this.set('currentSort', this.get('inverseDasherizerized'));\n } else if (this.get('order') === 'desc') {\n this.set('currentSort', '');\n } else { // if currentSorting is not set to this field\n this.set('currentSort', this.get('dasherizerized'));\n }\n }", "Sort() {\n\n }", "setSortBy(sort_by) {\n // set sort_by radio to stored value, un-check other options.\n const sortByOptions = ['best_match', 'rating', 'review_count', 'distance'];\n sortByOptions.forEach(id => {\n if (sort_by === id) $(`#${id}`).prop('checked', true);\n else $(`#${id}`).prop('checked', false);\n });\n }", "function sortFromOption(){\n // console.log(\"sortFromOption\");\n getSortMethod(nowArray);\n pageNumber = 1;\n changeDisplayAmount(displayType,1);\n}", "sort () {\r\n this._data.sort((a, b) => a.sortOrder !== b.sortOrder ? b.sortOrder - a.sortOrder : a.value.localeCompare(b.value))\r\n }", "function resetList() {\n settings.terminals.sort(function (a, b) {\n a.distance = false;\n b.distance = false;\n return a[0].localeCompare(b[0]);\n });\n }", "onSorted(){\n if(!this.rows) return;\n\n var sorts = this.options.columns.filter((c) => {\n return c.sort;\n });\n\n if(sorts.length){\n this.onSort({ sorts: sorts });\n\n var clientSorts = [];\n for(var i=0, len=sorts.length; i < len; i++) {\n var c = sorts[i];\n if(c.comparator !== false){\n var dir = c.sort === 'asc' ? '' : '-';\n clientSorts.push(dir + c.prop);\n }\n }\n\n if(clientSorts.length){\n // todo: more ideal to just resort vs splice and repush\n // but wasn't responding to this change ...\n var sortedValues = this.$filter('orderBy')(this.rows, clientSorts);\n this.rows.splice(0, this.rows.length);\n this.rows.push(...sortedValues);\n }\n }\n\n this.options.internal.setYOffset(0);\n }", "function sortingOptions() {\n var doOrderBy = document.getElementById(\"chkOrderBy\").checked;\n if (doOrderBy !== null && doOrderBy === true) {\n document.getElementById(\"cmboFields\").disabled = false;\n document.getElementById(\"comboOrderByMode\").disabled = false;\n }\n else {\n document.getElementById(\"cmboFields\").disabled = true;\n document.getElementById(\"comboOrderByMode\").disabled = true;\n }\n}", "function resetAscending(field)\n {\n date_ascending = false;\n location_ascending = false;\n artifact_ascending = false;\n description_ascending = false;\n gps_ascending = false;\n if (field == 'date')\n {\n date_ascending = true;\n }\n if (field == 'location')\n {\n location_ascending = true;\n }\n if (field == 'artifact')\n {\n artifact_ascending = true;\n }\n if (field == 'description')\n {\n description_ascending = true;\n }\n if (field == 'gps')\n {\n gps_ascending = true;\n }\n }", "function setPKeysAsSortDefaults(){\n\t var view = tabsFrame.newView;\n var numberOfTblgrps = Number(tabsFrame.tablegroupsRestriction);\n var viewType = tabsFrame.typeRestriction;\n var index = view.tableGroups.length - tabsFrame.selectedTableGroup - 1;\n \n \n var numberofSortFields = 0;\n if (view.tableGroups[index].hasOwnProperty('sortFields')){\n \tnumberOfSortFields = view.tableGroups[index].sortFields.length;\n \t}\n\n if(numberofSortFields == 0){ \n var summaryTable = $('sortOrderSummary');\n tBody = summaryTable.tBodies[0];\n var numOfRows = tBody.rows.length;\n \t \n // loop through the summary table\n for (var j = 1; j < numOfRows; j++) {\n var pKeyCell = summaryTable.rows[j].cells[2];\n var setButtonCell = summaryTable.rows[j].cells[8];\n \n // if there is a match, display the order and hide the \"Sort\" button\n //if (pKeyCell.innerHTML != '0') {\n if ((pKeyCell.innerHTML != '0') && setButtonCell.innerHTML.match(/button/gi)) {\n var rowID = setButtonCell.parentNode.id;\n setSortAndSave('', rowID);\n }\n }\n \t}\n}", "function findSort(){\n if(!started){\n startSort();\n }\n\n if(done)\n return;\n\n randomizeButton.disabled = true;\n\n let decision = sortSelector.value;\n switch(decision){\n case \"Selection\":\n selectionSort();\n break;\n case \"Quick\":\n quicksort();\n break;\n case \"Bubble\":\n bubblesort();\n break;\n case \"Insertion\":\n insertionSort();\n break;\n case \"Merge\":\n mergeSort();\n break;\n case \"Heap\":\n heapSort();\n break;\n case \"Bogo\":\n bogoSort();\n break;\n }\n\n \n}", "function resetFilter(){\n\t\t\t\n\t\t\t// UNBIND TRANSITION END EVENTS FROM CONTAINER\n\t\t\t\n\t\t\t$par.unbind('webkitTransitionEnd transitionend otransitionend oTransitionEnd');\n\t\t\t\n\t\t\t// IF A SORT ARGUMENT HAS BEEN SENT, SORT ELEMENTS TO THEIR FINAL ORDER\n\t\t\t\n\t\t\tif(sortby){\n\t\t\t\tsort(sortby, order, $cont, config);\n\t\t\t};\n\t\t\t\n\t\t\t// EMPTY SORTING ARRAYS\n\t\t\n\t\t\tconfig.startOrder = [], config.newOrder = [], config.origSort = [], config.checkSort = [];\n\t\t\n\t\t\t// REMOVE INLINE STYLES FROM ALL TARGET ELEMENTS AND SLAM THE BRAKES ON\n\t\t\t\n\t\t\t$targets.removeStyle(\n\t\t\t\tconfig.prefix+'filter, filter, '+config.prefix+'transform, transform, opacity, display'\n\t\t\t).css(config.clean).removeAttr('data-checksum');\n\t\t\t\n\t\t\t// BECAUSE IE SUCKS\n\t\t\t\n\t\t\tif(!window.atob){\n\t\t\t\t$targets.css({\n\t\t\t\t\tdisplay: 'none',\n\t\t\t\t\topacity: '0'\n\t\t\t\t});\n\t\t\t};\n\t\t\t\n\t\t\t// REMOVE HEIGHT FROM CONTAINER ONLY IF RESIZING\n\t\t\t\n\t\t\tvar remH = config.resizeContainer ? 'height' : '';\n\t\t\t\n\t\t\t// REMOVE INLINE STYLES FROM CONTAINER\n\t\t\n\t\t\t$par.removeStyle(\n\t\t\t\tconfig.prefix+'transition, transition, '+config.prefix+'perspective, perspective, '+config.prefix+'perspective-origin, perspective-origin, '+remH\n\t\t\t);\n\t\t\t\n\t\t\t// ADD FINAL DISPLAY PROPERTIES AND OPACITY TO ALL SHOWN ELEMENTS\n\t\t\t// CACHE CURRENT LAYOUT MODE & SORT FOR NEXT MIX\n\t\t\t\n\t\t\tif(config.layoutMode == 'list'){\n\t\t\t\t$show.css({display:config.targetDisplayList, opacity:'1'});\n\t\t\t\tconfig.origDisplay = config.targetDisplayList;\n\t\t\t} else {\n\t\t\t\t$show.css({display:config.targetDisplayGrid, opacity:'1'});\n\t\t\t\tconfig.origDisplay = config.targetDisplayGrid;\n\t\t\t};\n\t\t\tconfig.origLayout = config.layoutMode;\n\t\t\t\t\n\t\t\tvar wait = setTimeout(function(){\n\t\t\t\t\n\t\t\t\t// LET GO OF THE BRAKES\n\t\t\t\t\n\t\t\t\t$targets.removeStyle(config.prefix+'transition, transition');\n\t\t\t\n\t\t\t\t// WE'RE DONE MIXING\n\t\t\t\n\t\t\t\tconfig.mixing = false;\n\t\t\t\n\t\t\t\t// FIRE \"ONMIXEND\" CALLBACK\n\t\t\t\n\t\t\t\tif(typeof config.onMixEnd == 'function') {\n\t\t\t\t\tvar output = config.onMixEnd.call(this, config);\n\t\t\t\t\n\t\t\t\t\t// UPDATE CONFIG IF DATA RETURNED\n\t\t\t\t\n\t\t\t\t\tconfig = output ? output : config;\n\t\t\t\t};\n\t\t\t});\n\t\t}", "function changeSort(columnName) {\n for (let item of sortList) {\n\n if (item.name === columnName) {\n\n /* Set new sort */\n if (item.sort === undefined) {\n item.sort = true;\n } else {\n item.sort = !item.sort;\n }\n\n if (item.sort) {\n item.element.innerText = item.name + \" ▼\";\n } else {\n item.element.innerText = item.name + \" ▲\";\n }\n\n } else {\n /* Reset sort in all another field */\n item.sort = undefined;\n item.element.innerText = item.name + \" ▼▲\";\n }\n }\n\n filter();\n}", "sortResults(sortParams) {\n\t\tlet q = this.state.query;\n\t\tq.sort = sortParams;\n\t\tq.offset = 0;\n\t\tq.term = this.refs.searchTerm.value;\n\n\t\tthis.doSearch(q, true);\n\t}", "prepareSort(orderBy, allowed_cols, tableAlias, excludeOrder = false, validatedAggAliases) {\n let column_names = this.column_names.slice(0);\n const throwErr = () => {\n throw \"\\nInvalid orderBy option -> \" + JSON.stringify(orderBy) +\n \"\\nExpecting { key2: false, key1: true } | { key1: 1, key2: -1 } | [{ key1: true }, { key2: false }] | [{ key1: 1 }, { key2: -1 }]\";\n }, parseOrderObj = (orderBy, expectOne = false) => {\n if (!isPlainObject(orderBy))\n return throwErr();\n if (expectOne && Object.keys(orderBy).length > 1)\n throw \"\\nInvalid orderBy \" + JSON.stringify(orderBy) +\n \"\\nEach orderBy array element cannot have more than one key\";\n /* { key2: bool, key1: bool } */\n if (!Object.values(orderBy).find(v => ![true, false].includes(v))) {\n return Object.keys(orderBy).map(key => ({ key, asc: Boolean(orderBy[key]) }));\n }\n else if (!Object.values(orderBy).find(v => ![-1, 1].includes(v))) {\n return Object.keys(orderBy).map(key => ({ key, asc: orderBy[key] === 1 }));\n }\n else if (!Object.values(orderBy).find(v => ![\"asc\", \"desc\"].includes(v))) {\n return Object.keys(orderBy).map(key => ({ key, asc: orderBy[key] === \"asc\" }));\n }\n else\n return throwErr();\n };\n if (!orderBy)\n return \"\";\n let allowedFields = [];\n if (allowed_cols) {\n allowedFields = this.parseFieldFilter(allowed_cols);\n }\n let _ob = [];\n if (isPlainObject(orderBy)) {\n _ob = parseOrderObj(orderBy);\n }\n else if (typeof orderBy === \"string\") {\n /* string */\n _ob = [{ key: orderBy, asc: true }];\n }\n else if (Array.isArray(orderBy)) {\n /* Order by is formed of a list of ascending field names */\n let _orderBy = orderBy;\n if (_orderBy && !_orderBy.find(v => typeof v !== \"string\")) {\n /* [string] */\n _ob = _orderBy.map(key => ({ key, asc: true }));\n }\n else if (_orderBy.find(v => isPlainObject(v) && Object.keys(v).length)) {\n if (!_orderBy.find(v => typeof v.key !== \"string\" || typeof v.asc !== \"boolean\")) {\n /* [{ key, asc }] */\n _ob = Object.freeze(_orderBy);\n }\n else {\n /* [{ [key]: asc }] | [{ [key]: -1 }] */\n _ob = _orderBy.map(v => parseOrderObj(v, true)[0]);\n }\n }\n else\n return throwErr();\n }\n else\n return throwErr();\n if (!_ob || !_ob.length)\n return \"\";\n let bad_param = _ob.find(({ key }) => !(validatedAggAliases || []).includes(key) &&\n (!column_names.includes(key) ||\n (allowedFields.length && !allowedFields.includes(key))));\n if (!bad_param) {\n return (excludeOrder ? \"\" : \" ORDER BY \") + (_ob.map(({ key, asc }) => `${tableAlias ? pgp.as.format(\"$1:name.\", tableAlias) : \"\"}${pgp.as.format(\"$1:name\", key)} ${asc ? \" ASC \" : \" DESC \"}`).join(\", \"));\n }\n else {\n throw \"Unrecognised orderBy fields or params: \" + bad_param.key;\n }\n }", "function sort() {\r\n\t// Set the and filter strings\r\n\tsortString = $('#page_sort').val();\r\n\tfilterString = $('#page_filter').val();\r\n\r\n\t// Remove current thumbnails from DOM\r\n\tclearThumbnails();\r\n\t\r\n\t// Display updated thumbnails\r\n\tdisplayThumbnails();\r\n\t\r\n\tissorting = true;\r\n}", "function applyFilters() {\n var appliedFilters = $scope.filters.sort(function (a, b) {\n return $scope.filterPriority.indexOf(a) - $scope.filterPriority.indexOf(b);\n });\n filterPreferences.filters = angular.copy(appliedFilters);\n $scope.appliedFilters = angular.copy(appliedFilters);\n document.getElementsByTagName(\"r2o-content\")[0].children[0].scrollTop = 0;\n }", "sortedRankings ({ rankings, sortBy }) {\n const { field, order } = sortBy\n const sortComparator = (a, b) => {\n if (order === 'asc') {\n return a.stats[field] - b.stats[field]\n }\n return b.stats[field] - a.stats[field]\n }\n return rankings.sort(sortComparator)\n }", "applyFiltersAndSorts() {\n var list = this.props.list.filter(this.matchesFilterEnergyLevel);\n list = list.filter(this.matchesFilterFunLevel)\n var sort_type = this.getSortFunction()\n if(sort_type != null){\n list = list.sort(sort_type)\n }\n return list\n\n }", "function sortBy(sortField1, sortField2) {\n vm.sortField1 = sortField1;\n vm.sortField2 = sortField2;\n vm.sortAsc = !vm.sortAsc;\n vm.parametersList.applyValsForFilters();\n $timeout(vm.validateNamesUnique);\n }", "function ComparisonSort(e,t,n){this.init(e,t,n)}", "async function TopologicalSort(){}", "triggerSort() {\n const logPrefix = 'SortingFilterController.changeOrderBy()\\t';\n\n if (_.isEmpty(this.filterSortingList)) {\n this.$log.warn(logPrefix + 'please define field \"entityListName\"');\n return;\n } else if (_.isEmpty(this.filterSortingField)) {\n this.$log.warn(logPrefix + 'please define field \"field\"');\n return;\n } else if (_.isUndefined(this.tableCell.tableManager.baseData)) {\n this.$log.warn(logPrefix + 'please sorting base data');\n return;\n }\n\n //TODO: read this data from the state service.\n //const sortingOptions = this.tableCell.tableManager.baseData.sorting;\n\n // Entity list or field name has changed -> reset sort order.\n if (this.sorting.entityList !== this.filterSortingList || this.sorting.field !== this.filterSortingField) {\n this.sorting.order = '';\n }\n\n let sortingType = this.filterSortingType;\n if (_.isEmpty(sortingType)) {\n sortingType = 'string';\n }\n\n let options = this.filterSortingOptions;\n if (_.isUndefined(options) || _.isPlainObject(options) === false) {\n options = {};\n }\n\n this.sorting.fnc = sortingType;\n this.sorting.entityList = this.filterSortingList;\n this.sorting.field = this.filterSortingField;\n this.sorting.options = options;\n\n // Swap the sorting order e.g. to start on a numerical sorting column with the largest value.\n if (options.swapOrder) {\n this.sorting.order = (this.sorting.order === 'desc' ? 'asc' : 'desc');\n } else {\n this.sorting.order = (this.sorting.order === 'asc' ? 'desc' : 'asc');\n }\n\n // Update class attribute onto this filter's table cell element.\n if (this.sorting.order === 'asc') {\n this.tableCell.$element\n .removeClass('desc')\n .addClass('asc');\n } else {\n this.tableCell.$element\n .removeClass('asc')\n .addClass('desc');\n }\n\n // Sort list by defined sort parameters\n this.tableCell.tableManager.baseData.data = SortUtils.sortArrayOfLists(\n this.tableCell.tableManager.baseData.data,\n this.sorting.fnc,\n this.sorting.entityList,\n this.sorting.field,\n this.sorting.order,\n this.sorting.options\n );\n\n // Trigger a view update to display the new (sorted) data.\n this.tableCell.tableManager.updateView();\n }", "function resetFilter() {\n\n\t\t\t// UNBIND TRANSITION END EVENTS FROM CONTAINER\n\n\t\t\t$par.unbind('webkitTransitionEnd transitionend otransitionend oTransitionEnd');\n\n\t\t\t// IF A SORT ARGUMENT HAS BEEN SENT, SORT ELEMENTS TO THEIR FINAL ORDER\n\n\t\t\tif (sortby) {\n\t\t\t\tsort(sortby, order, $cont, config);\n\t\t\t};\n\n\t\t\t// EMPTY SORTING ARRAYS\n\n\t\t\tconfig.startOrder = [], config.newOrder = [], config.origSort = [], config.checkSort = [];\n\n\t\t\t// REMOVE INLINE STYLES FROM ALL TARGET ELEMENTS AND SLAM THE BRAKES ON\n\n\t\t\t$targets.removeStyle(config.prefix + 'filter, filter, ' + config.prefix + 'transform, transform, opacity, display').css(config.clean).removeAttr('data-checksum');\n\n\t\t\t// BECAUSE IE SUCKS\n\n\t\t\tif (!window.atob) {\n\t\t\t\t$targets.css({\n\t\t\t\t\tdisplay: 'none',\n\t\t\t\t\topacity: '0'\n\t\t\t\t});\n\t\t\t};\n\n\t\t\t// REMOVE HEIGHT FROM CONTAINER ONLY IF RESIZING\n\n\t\t\tvar remH = config.resizeContainer ? 'height' : '';\n\n\t\t\t// REMOVE INLINE STYLES FROM CONTAINER\n\n\t\t\t$par.removeStyle(config.prefix + 'transition, transition, ' + config.prefix + 'perspective, perspective, ' + config.prefix + 'perspective-origin, perspective-origin, ' + remH);\n\n\t\t\t// ADD FINAL DISPLAY PROPERTIES AND OPACITY TO ALL SHOWN ELEMENTS\n\t\t\t// CACHE CURRENT LAYOUT MODE & SORT FOR NEXT MIX\n\n\t\t\tif (config.layoutMode == 'list') {\n\t\t\t\t$show.css({ display: config.targetDisplayList, opacity: '1' });\n\t\t\t\tconfig.origDisplay = config.targetDisplayList;\n\t\t\t} else {\n\t\t\t\t$show.css({ display: config.targetDisplayGrid, opacity: '1' });\n\t\t\t\tconfig.origDisplay = config.targetDisplayGrid;\n\t\t\t};\n\t\t\tconfig.origLayout = config.layoutMode;\n\n\t\t\tvar wait = setTimeout(function () {\n\n\t\t\t\t// LET GO OF THE BRAKES\n\n\t\t\t\t$targets.removeStyle(config.prefix + 'transition, transition');\n\n\t\t\t\t// WE'RE DONE MIXING\n\n\t\t\t\tconfig.mixing = false;\n\n\t\t\t\t// FIRE \"ONMIXEND\" CALLBACK\n\n\t\t\t\tif (typeof config.onMixEnd == 'function') {\n\t\t\t\t\tvar output = config.onMixEnd.call(this, config);\n\n\t\t\t\t\t// UPDATE CONFIG IF DATA RETURNED\n\n\t\t\t\t\tconfig = output ? output : config;\n\t\t\t\t};\n\t\t\t});\n\t\t}", "function changeSort(sortValue, alternateOrder) {\n if (alternateOrder) {\n props.onChangeSort(sortValue, 1 - props.searchFields.orderValue);\n } else {\n props.onChangeSort(sortValue, 1);\n }\n }", "clearOrderBy() {\n return new SelectQueryBuilder({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithoutOrderBy(this.#props.queryNode),\n });\n }", "sort() {\n\t}", "sort() {\n\t}", "function sortChanged(){\n\tconst url2 = url+`&q=${name.val()}&t=${type.val()}&color=${color.val()}&s=${sort.val()}`;\n\tloadData(url2, displayData);\n}", "function initialize_search_filter_sort() {\n paginate_by = [default_pagination];\n\n var page_number_text = $(\"#page_number_text\");\n var select_all_pages_checkbox = $(\"#select_all_pages_checkbox\");\n var object_list_checkbox = $(\".object-list-checkbox\");\n var action_btns = $(\".sfs-action-btn\");\n var select_all_on_page = $(\"#select_all_objects_checkbox\");\n\n $(\"#paginate_by_select\").change(function() {\n paginate_by = [$(this).val()];\n goto_new_url(true, true, true);\n });\n\n if(page_number_text.val()) {\n page_num_input_form_size(page_number_text)\n }\n\n page_num_input_form_size(page_number_text);\n\n page_number_text.on('input', function() {\n page_num_input_form_size(page_number_text);\n });\n\n $(window).keydown(function(event) {\n var key_code = event.which || event.key;\n\n if(key_code === 13 && $(\"#search_text\").is(\":focus\")) {\n search();\n }\n\n if(key_code === 13 && page_number_text.is(\":focus\")) {\n goto_page(page_number_text.val());\n }\n });\n\n select_all_pages_checkbox.change(function() {\n var disable_state = $(this).prop(\"checked\");\n\n $(\"#select_all_objects_checkbox\").attr(\"disabled\", disable_state);\n\n object_list_checkbox.each(function() {\n $(this).prop('checked', false);\n $(this).attr(\"disabled\", disable_state);\n });\n });\n\n set_filter_mousedown_functions();\n set_filter_keydown_functions();\n get_url_parameters(search_bys, \"search_by\");\n get_filter_by_parameters(); // Also sets original_filter_bys\n get_url_parameters(sort_bys, \"sort_by\");\n get_url_parameters(paginate_by, \"paginate_by\");\n set_filters();\n set_sort_symbols();\n set_pagination();\n fix_range_filters();\n\n if(search_bys.length > 0) {\n $(\"#clear_search_button\").prop(\"disabled\", false);\n }\n\n set_filter_button_states();\n\n if(sort_bys.length > 0) {\n $(\"#clear_sorts_button\").prop(\"disabled\", false);\n }\n\n select_all_on_page.change(function()\n {\n if (object_list_checkbox.length > 0) {\n action_btns.attr(\"disabled\", !this.checked);\n }\n });\n\n select_all_pages_checkbox.change(function()\n {\n if (object_list_checkbox.length > 0) {\n action_btns.attr(\"disabled\", !this.checked);\n }\n });\n\n object_list_checkbox.change(function()\n {\n if(select_all_on_page.is(\":not(:checked)\")) {\n if(!$(\"table\").find($(\".object-list-checkbox:checked\")).length > 0) {\n action_btns.attr(\"disabled\", \"disabled\");\n } else {\n action_btns.removeAttr(\"disabled\");\n }\n }\n });\n}", "_sortedByChanged(sorted) {\n const headerColumns = this.shadowRoot.querySelectorAll('.th');\n this._resetOldSorting();\n headerColumns.forEach((el) => {\n if (el.getAttribute('sortable') === sorted) {\n el.setAttribute('sorted', '');\n this.set('sortDirection', 'ASC');\n }\n });\n }", "defaultSortBy(a, b) {\n let me = this;\n\n a = a[me.property];\n b = b[me.property];\n\n if (me.useTransformValue) {\n a = me.transformValue(a);\n b = me.transformValue(b);\n }\n\n if (a > b) {\n return 1 * me.directionMultiplier;\n }\n\n if (a < b) {\n return -1 * me.directionMultiplier;\n }\n\n return 0;\n }", "processSortItemsByStatus() {\n // IF WE ARE CURRENTLY INCREASING BY STATUS SWITCH TO DECREASING\n if (window.todo.model.isCurrentItemSortCriteria(ItemSortCriteria.SORT_BY_STATUS_INCREASING)) {\n window.todo.model.sortTasks(ItemSortCriteria.SORT_BY_STATUS_DECREASING);\n }\n // ALL OTHER CASES SORT BY INCRASING\n else {\n window.todo.model.sortTasks(ItemSortCriteria.SORT_BY_STATUS_INCREASING);\n }\n }", "function sortRestaurants() {\n oneStar = false;\n twoStars = false;\n fourStars = false;\n threeStars = false;\n fiveStars = false;\n allStars = false;\n}", "resetAllFilterViews(){\n this.setProperties({'viewFilterbySearch': false, 'viewFilterbyGrade': false, 'viewFilterbyClassification': false });\n }", "function enableSortBys() {\n for (var i = 0; i < sortBys.length; i++) {\n $(\"#\" + sortBys[i] + \" option\").each(function () {\n $(this).removeAttr(\"disabled\");\n })\n }\n}", "function sort_overview_class(){\r\r\n\t\r\r\n\tvar click_num = $('#class_click_num').val();\r\r\n\t\r\r\n\tif(click_num == 0 || click_num == 2){\r\r\n\t\t\r\r\n\t\t$('#class_click_num').val(1);\r\r\n\t\t\r\r\n\t}else if(click_num == 1){\r\r\n\t\t\r\r\n\t\t$('#class_click_num').val(2);\r\r\n\t\t\r\r\n\t}\r\r\n\t\r\r\n\tfilter = {\r\r\n\t\t\r\r\n\t\tclass_of: $('#get_year').val(),\r\r\n\t\t\r\r\n\t\tsort_by_class: $('#class_click_num').val()\r\r\n\t\t\r\r\n\t};\r\r\n\t\r\r\n\tload_overview_student();\r\r\n\t\r\r\n}", "function sortingDscend() { \n setSearchData(null)\n let sorted = studentData.sort(function(a, b){\n return a.id - b.id;\n })\n\n setSearchData(sorted)\n // console.log(sorted, typeof(sorted))\n }", "function testSorts()\n{\n\n\tconsole.log(\"============= original googleResults =============\");\n\tconsole.log(googleResults);\n\t\n\tconsole.log(\"==== before sort array element index name rating ====\");\n\t\n\tgoogleResults.forEach(function(element,index)\n\t{\n\t\t console.log(index + \": name: \" + element.name + \" rating: \" + element.rating);\n\n\t});\n\n\t\t// commented for testing\n\t\t//googleResults.sortByRatingAscending();\n\t\t\n\t\t// commented for testing\n\t\tgoogleResults.sortByRatingDescending();\n\t\t\n\t//===============================================================\t\n\n\tconsole.log(\"============= after sort =============\");\n\n\tgoogleResults.forEach(function(element,index)\n\t{\n\t\t console.log(index + \": name: \" + element.name + \" rating: \" + element.rating);\n\n\t});\n\t\n}//END test", "function applyAllSorting(){\n\n\tvar sortByCost = $(\"#sortByCostCheckbox\").is(':checked') ? 1 : 0;\n\tvar sortByOrbs = $(\"#sortByOrbsCheckbox\").is(':checked') ? 1 : 0;\n\tvar sortByAlphabet = $(\"#sortByAlphabetCheckbox\").is(':checked') ? 1 : 0;\n\tvar useOrbList = $(\"#showPlayableCheckbox\").is(\":checked\") ? 1 : 0;\n\tvar sortAsc = $(\"#sortAscCheckbox\").is(':checked') ? true : false;\n\tvar name = $(\"#nameTextbox\").val();\n\n\tvar currentCards = cardsFromKeys(getAllCards());\n\tif(name != \"\"){\n\t\tcurrentCards = cardsFromKeys(getAllCardsWithNameLike(name, currentCards));\n\t}\n\n\tif(useOrbList == 1){\n\t\tvar orbCode = \"\";\n\t\torbCode += $('input[name=orbst1]:checked').val();\n\t\torbCode += $('input[name=orbst2]:checked').val();\n\t\torbCode += $('input[name=orbst3]:checked').val();\n\t\torbCode += $('input[name=orbst4]:checked').val();\n\n\t\tcurrentCards = cardsFromKeys(getCardsThatFitOrbCode(orbCode, currentCards));\n\t}\n\n\t// Each of these blocks applies one filter block\n\tvar finCards = {};\n\t$( \".colorCheckBox\" ).each(function(index) {\n\t\tif($(this).is(\":checked\")){\n\t\t\t$.extend(finCards, cardsFromKeys(getAllCardsWithColor($(this).val(), currentCards)));\n\t\t}\n\t});\n\tcurrentCards = finCards;\n\n\n\tvar finCards = {};\n\t$( \".tierCheckBox\" ).each(function(index) {\n\t\tif($(this).is(\":checked\")){\n\t\t\t$.extend(finCards, cardsFromKeys(getAllCardsInTier($(this).val(), currentCards)));\n\t\t}\n\t});\n\tcurrentCards = finCards;\n\n\n\tfinCards = {};\n\t$( \".typeCheckBox\" ).each(function(index) {\n\t\tif($(this).is(\":checked\")){\n\t\t\t$.extend(finCards, cardsFromKeys(getAllCardsWithType($(this).val(), currentCards)));\n\t\t}\n\t});\n\tcurrentCards = finCards;\n\n\n\tfinCards = {};\n\t$( \".rarityCheckBox\" ).each(function(index) {\n\t\tif($(this).is(\":checked\")){\n\t\t\t$.extend(finCards, cardsFromKeys(getAllCardsWithRarity($(this).val(), currentCards)));\n\t\t}\n\t});\n\tcurrentCards = finCards;\n\n\n\tfinCards = {};\n\t$( \".editionCheckBox\" ).each(function(index) {\n\t\tif($(this).is(\":checked\")){\n\t\t\t$.extend(finCards, cardsFromKeys(getAllCardsWithEdition($(this).val(), currentCards)));\n\t\t}\n\t});\n\tcurrentCards = finCards;\n\n\t\n\tfinCards = {};\n\t$( \".affinityCheckBox\" ).each(function(index) {\n\t\tif($(this).is(\":checked\")){\n\t\t\t$.extend(finCards, cardsFromKeys(getAllCardsWithAffinity($(this).val(), currentCards)));\n\t\t}\n\t});\n\tcurrentCards = finCards;\n\n\n\tfinCards = {};\n\t$( \".unitRangedCheckBox\" ).each(function(index) {\n\t\tif($(this).is(\":checked\")){\n\t\t\t$.extend(finCards, cardsFromKeys(getAllCardsWithUnitRange($(this).val(), currentCards)));\n\t\t}\n\t});\n\tcurrentCards = finCards;\n\n\tfinCards = {};\n\t$( \".unitSizeCheckBox\" ).each(function(index) {\n\t\tif($(this).is(\":checked\")){\n\t\t\t$.extend(finCards, cardsFromKeys(getAllCardsWithUnitSize($(this).val(), currentCards)));\n\t\t}\n\t});\n\tcurrentCards = finCards;\n\n\tfinCards = {};\n\t$( \".unitCountersCheckBox\" ).each(function(index) {\n\t\tif($(this).is(\":checked\")){\n\t\t\t$.extend(finCards, cardsFromKeys(getAllCardsWithUnitStrongAgainst($(this).val(), currentCards)));\n\t\t}\n\t});\n\tcurrentCards = finCards;\n\t\n\n\n\tif(sortByCost == 1){\n\t\tcurrentCards = cardsFromKeys(getCardsSortedByCost(sortAsc, currentCards));\n\t}\n\tif(sortByOrbs == 1){\n\t\tcurrentCards = cardsFromKeys(getCardsSortedByOrbs(sortAsc, currentCards));\n\t}\n\tif(sortByAlphabet == 1){\n\t\tcurrentCards = cardsFromKeys(getCardsSortedAlphabetically(sortAsc, currentCards));\n\t}\n\tdisplayCardList(currentCards);\n\n\n\tAddCardHovers();\n\n\t\n\t// Clean URL if it had a card or deck link added\n\tvar nameFromUrl = $.urlParam(\"c\");\n\tif(nameFromUrl.length > 1){\n\t\tvar myNewURL = refineURL();\n\t\twindow.history.pushState({}, document.title, \"/\" + myNewURL );\n\t}\t\n\tvar nameFromUrl = $.urlParam(\"d\");\n\tif(nameFromUrl.length > 1){\n\t\tvar myNewURL = refineURL();\n\t\twindow.history.pushState({}, document.title, \"/\" + myNewURL );\n\t}\n}", "sort() {\n //Check is sort is present\n if(this.queryStr.sort){\n //Handling multiple sorting paramters\n const sortBy = this.queryStr.sort.split(',').join(' ');\n this.query = this.query.sort(sortBy);\n }else{\n //Incase no paramters are specified \n //Sort based on posting date in descreasing order\n this.query = this.query.sort('-postingDate');\n }\n\n return this;\n }", "sort(sort) {\n this.options.sort = sort;\n return this;\n }", "sort(){\n\n }", "updateSorters(sortColumns, presetSorters) {\n let currentSorters = [];\n const graphqlSorters = [];\n if (!sortColumns && presetSorters) {\n // make the presets the current sorters, also make sure that all direction are in uppercase for GraphQL\n currentSorters = presetSorters;\n currentSorters.forEach((sorter) => sorter.direction = sorter.direction.toUpperCase());\n // display the correct sorting icons on the UI, for that it requires (columnId, sortAsc) properties\n const tmpSorterArray = currentSorters.map((sorter) => {\n const columnDef = this._columnDefinitions.find((column) => column.id === sorter.columnId);\n graphqlSorters.push({\n field: columnDef ? ((columnDef.queryFieldSorter || columnDef.queryField || columnDef.field) + '') : (sorter.columnId + ''),\n direction: sorter.direction\n });\n // return only the column(s) found in the Column Definitions ELSE null\n if (columnDef) {\n return {\n columnId: sorter.columnId,\n sortAsc: sorter.direction.toUpperCase() === SortDirection.ASC\n };\n }\n return null;\n });\n // set the sort icons, but also make sure to filter out null values (that happens when columnDef is not found)\n if (Array.isArray(tmpSorterArray)) {\n this._grid.setSortColumns(tmpSorterArray.filter((sorter) => sorter));\n }\n }\n else if (sortColumns && !presetSorters) {\n // build the orderBy array, it could be multisort, example\n // orderBy:[{field: lastName, direction: ASC}, {field: firstName, direction: DESC}]\n if (Array.isArray(sortColumns) && sortColumns.length > 0) {\n for (const column of sortColumns) {\n if (column && column.sortCol) {\n currentSorters.push({\n columnId: column.sortCol.id + '',\n direction: column.sortAsc ? SortDirection.ASC : SortDirection.DESC\n });\n const fieldName = (column.sortCol.queryFieldSorter || column.sortCol.queryField || column.sortCol.field || '') + '';\n if (fieldName) {\n graphqlSorters.push({\n field: fieldName,\n direction: column.sortAsc ? SortDirection.ASC : SortDirection.DESC\n });\n }\n }\n }\n }\n }\n // keep current Sorters and update the service options with the new sorting\n this._currentSorters = currentSorters;\n this.updateOptions({ sortingOptions: graphqlSorters });\n }", "_changeSortMode(e) {\n if (this.sortColumn === e.detail.columnNumber && this.sortMode === \"asc\") {\n this.sortMode = \"desc\";\n } else if (\n this.sortColumn === e.detail.columnNumber &&\n this.sortMode === \"desc\"\n ) {\n this.sortMode = \"none\";\n } else {\n this.sortMode = \"asc\";\n this.sortColumn = e.detail.columnNumber;\n }\n e.detail.setSortMode(this.sortMode);\n this.sortData(this.sortMode, e.detail.columnNumber);\n }" ]
[ "0.7344761", "0.70686644", "0.70344", "0.70155954", "0.6895858", "0.6495198", "0.6495198", "0.6469161", "0.6437964", "0.6394476", "0.6322835", "0.6287263", "0.6264788", "0.62606126", "0.62386173", "0.62311274", "0.62137145", "0.61662626", "0.615922", "0.6152911", "0.6124684", "0.6047846", "0.60442823", "0.6010145", "0.60018957", "0.5992706", "0.597663", "0.5954914", "0.59538126", "0.59234893", "0.59147316", "0.5892927", "0.58814245", "0.5872512", "0.58597815", "0.58597815", "0.5845506", "0.5836039", "0.5836039", "0.5826786", "0.58171815", "0.5815123", "0.5807747", "0.5784828", "0.57837015", "0.57570523", "0.5739125", "0.5737666", "0.5732422", "0.5724237", "0.57128245", "0.5705808", "0.570536", "0.5697555", "0.56958526", "0.5686219", "0.5679551", "0.5676953", "0.5663085", "0.56529146", "0.56493086", "0.56488293", "0.5646594", "0.563855", "0.5632135", "0.56266356", "0.56219405", "0.56189895", "0.5600866", "0.5595356", "0.5580482", "0.5571096", "0.55700165", "0.55535716", "0.5548737", "0.5543622", "0.55420953", "0.55287725", "0.5528571", "0.5525282", "0.55210394", "0.55162233", "0.55162233", "0.55148", "0.55087215", "0.5506549", "0.5502917", "0.549645", "0.5495185", "0.54677826", "0.54647505", "0.5463407", "0.5459611", "0.5454735", "0.5449395", "0.54493535", "0.5449145", "0.5432938", "0.5424317", "0.5422795" ]
0.68768775
5
A `React.Ref` that keeps track of the passed `value`.
function useLiveRef(value) { var ref = React.useRef(value); useIsomorphicEffect.useIsomorphicEffect(function () { ref.current = value; }); return ref; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function useUpdatedRef(value) {\n var valueRef = react.useRef(value);\n valueRef.current = value;\n return valueRef;\n}", "function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n }", "function useUpdatedRef(value) {\n var valueRef = (0, _react.useRef)(value);\n valueRef.current = value;\n return valueRef;\n}", "function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}", "function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}", "function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}", "function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}", "function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}", "function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}", "function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}", "function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}", "function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}", "function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}", "function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}", "function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}", "function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}", "function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}", "function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}", "function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}", "function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}", "function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}", "function useUpdatedRef(value) {\n var valueRef = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useRef\"])(value);\n valueRef.current = value;\n return valueRef;\n}", "function useUpdatedRef(value) {\n var valueRef = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useRef\"])(value);\n valueRef.current = value;\n return valueRef;\n}", "function useUpdatedRef(value) {\n var valueRef = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useRef\"])(value);\n valueRef.current = value;\n return valueRef;\n}", "function useUpdatedRef(value) {\n var valueRef = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useRef\"])(value);\n valueRef.current = value;\n return valueRef;\n}", "function useUpdatedRef(value) {\n var valueRef = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useRef\"])(value);\n valueRef.current = value;\n return valueRef;\n}", "function useUpdatedRef(value) {\n var valueRef = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useRef\"])(value);\n valueRef.current = value;\n return valueRef;\n}", "function useUpdatedRef(value) {\n var valueRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(value);\n valueRef.current = value;\n return valueRef;\n}", "function useCommittedRef(value) {\n var ref = React.useRef(value);\n React.useEffect(function () {\n ref.current = value;\n }, [value]);\n return ref;\n }", "function useCommittedRef(value) {\n var ref = react.useRef(value);\n react.useEffect(function () {\n ref.current = value;\n }, [value]);\n return ref;\n}", "function valueRef (value, opts) {\n let ref = opts.ref || emptyRef('value')\n return { ...ref, value }\n}", "function useCommittedRef(value) {\n var ref = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(value);\n (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(function () {\n ref.current = value;\n }, [value]);\n return ref;\n}", "function useCommittedRef(value) {\n var ref = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(value);\n (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(function () {\n ref.current = value;\n }, [value]);\n return ref;\n}", "function useCommittedRef(value) {\n var ref = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(value);\n (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(function () {\n ref.current = value;\n }, [value]);\n return ref;\n}", "function useCommittedRef(value) {\n var ref = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(value);\n (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(function () {\n ref.current = value;\n }, [value]);\n return ref;\n}", "function useCommittedRef(value) {\n var ref = (0, _react.useRef)(value);\n (0, _react.useEffect)(function () {\n ref.current = value;\n }, [value]);\n return ref;\n}", "function useCommittedRef(value) {\n var ref = (0, _react.useRef)(value);\n (0, _react.useEffect)(function () {\n ref.current = value;\n }, [value]);\n return ref;\n}", "function useLatestRef(value) {\n var ref = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(value);\n ref.current = value;\n return ref;\n}", "function useCommittedRef(value) {\n var ref = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useRef\"])(value);\n Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useEffect\"])(function () {\n ref.current = value;\n }, [value]);\n return ref;\n}", "function useCommittedRef(value) {\n var ref = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useRef\"])(value);\n Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useEffect\"])(function () {\n ref.current = value;\n }, [value]);\n return ref;\n}", "function useCommittedRef(value) {\n var ref = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useRef\"])(value);\n Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useEffect\"])(function () {\n ref.current = value;\n }, [value]);\n return ref;\n}", "function useCommittedRef(value) {\n var ref = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useRef\"])(value);\n Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useEffect\"])(function () {\n ref.current = value;\n }, [value]);\n return ref;\n}", "function useCommittedRef(value) {\n var ref = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useRef\"])(value);\n Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useEffect\"])(function () {\n ref.current = value;\n }, [value]);\n return ref;\n}", "function useCommittedRef(value) {\n var ref = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useRef\"])(value);\n Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useEffect\"])(function () {\n ref.current = value;\n }, [value]);\n return ref;\n}", "function useCommittedRef(value) {\n var ref = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useRef\"])(value);\n Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useEffect\"])(function () {\n ref.current = value;\n }, [value]);\n return ref;\n}", "function useCommittedRef(value) {\n var ref = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useRef\"])(value);\n Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useEffect\"])(function () {\n ref.current = value;\n }, [value]);\n return ref;\n}", "function useCommittedRef(value) {\n var ref = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useRef\"])(value);\n Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useEffect\"])(function () {\n ref.current = value;\n }, [value]);\n return ref;\n}", "_trackValue(value, valueRef) {\n let tracked = this.trackedValues.get(value);\n if (!tracked) {\n // if (value === undefined) {\n // this.logger.warn(new Error(`Tried to track value but is undefined`).stack);\n // }\n try {\n this.trackedValues.set(value, tracked = new TrackedValue(value));\n }\n catch (err) {\n let typeInfo = typeof value;\n if (isObject(value)) {\n typeInfo += `(${Object.getPrototypeOf(value)})`;\n }\n logError(`could not store value (\"${err.message}\"): ${typeInfo} ${JSON.stringify(value)}`);\n }\n }\n tracked.addRef(valueRef);\n\n return tracked;\n }", "setRefValue(value) {\n switch (value) {\n case types.MY_BOX:\n return this.box\n case types.CORONA:\n return this.corona;\n case types.HANDS:\n return this.hands;\n case types.FOREHEAD:\n return this.forehead;\n case types.FATO:\n return this.fato;\n case types.LEARNING:\n return this.learning;\n case types.PEPCOIN:\n return this.pepcoin;\n case types.WALKING:\n return this.walking;\n default:\n return null;\n }\n }", "function Ref(value, shared) {\r\n this.value = value;\r\n this.shared = shared;\r\n this.dirty = false;\r\n }", "function assignRef(ref, value) {\n if (ref == null) return;\n if (typeof ref === \"function\") {\n ref(value);\n } else {\n try {\n ref.current = value;\n } catch (error) {\n throw new Error(`Cannot assign value \"${value}\" to ref \"${ref}\"`);\n }\n }\n}", "handleRefTo(event) {\n this.setState({refTo: event.target.value});\n }", "function assignRef(ref, value) {\n if (ref == null) return;\n\n if (isFunction(ref)) {\n ref(value);\n } else {\n try {\n ref.current = value;\n } catch (error) {\n throw new Error(\"Cannot assign value \\\"\" + value + \"\\\" to ref \\\"\" + ref + \"\\\"\");\n }\n }\n}", "function usePreviousValue(value) {\n const ref = React.useRef();\n React.useEffect(() => {\n ref.current = value;\n });\n return ref.current;\n}", "function useRef(initialValue) {\n return useRefLike('useRef', initialValue);\n}", "function useRef(initialValue) {\n return useRefLike('useRef', initialValue);\n}", "makeRef(){\n let newRef = this.ref + 1\n if(newRef === this.ref){ this.ref = 0 } else { this.ref = newRef }\n\n return this.ref.toString()\n }", "getReferenceValue() {\n return (this.refs || []).map((ref) => ref.value);\n }", "function InputRef() {\n const [value, setValue] = useState([1,1,1,1,1,1,1,1,1])\n console.log(value)\n const inputRef = useRef();\n\n const submitValue = (e) => {\n setValue((prevData) => {\n prevData.push(inputRef.current.value);\n })\n inputRef.current.value = \"\";\n };\n\n let data = value.map( (li,i) => <li key={i}>{li}</li>)\n console.log(data)\n return (\n <div>\n <input ref={inputRef} />\n <button onClick={submitValue}>Submit Value</button>\n <div>{data}</div>\n </div>\n );\n}", "get valueReference () {\r\n\t\treturn this.__valueReference;\r\n\t}", "function useLatest(value) {\n const latest = React.useRef(value);\n if (value !== undefined && value !== null) {\n latest.current = value;\n }\n return latest.current;\n}", "function createRef() {\n var refObject = (function (element) {\n refObject.current = element;\n });\n // This getter is here to support the deprecated value prop on the refObject.\n Object.defineProperty(refObject, 'value', {\n get: function () {\n return refObject.current;\n }\n });\n refObject.current = null;\n return refObject;\n}", "set objectReferenceValue(value) {}", "function Fay$$writeRef(ref,x){\n ref.value = x;\n}", "static usePrevious(value) {\n const ref = useRef();\n useEffect(() => {\n ref.current = value;\n });\n return ref.current;\n }", "function get_ref(key,value) {\n var refs = [];\n if(key === \"Ref\") {\n refs.push(value);\n }\n return refs;\n}", "_triggerComponentUpdate(value) {\n if (has(this.props, 'valueLink')) {\n this.props.valueLink.requestChange(value);\n this.setState({\n focusedValue: undefined,\n isActive: false,\n });\n } else if (has(this.props, 'value')) {\n this.setState({\n focusedValue: undefined,\n isActive: false,\n });\n } else {\n this.setState({\n focusedValue: undefined,\n isActive: false,\n value,\n });\n }\n\n if (this.props.onUpdate) {\n this.props.onUpdate({ value });\n }\n }", "set value(val) {\n const input = this.refs.myInput\n input.value = val\n }", "function usePrevious(value) {\n const ref = useRef();\n useEffect(() => {\n ref.current = value;\n });\n return ref.current;}", "function Fay$$Ref(x){\n this.value = x;\n}", "function App() {\n // refs\n const refRange = React.createRef();\n const refDiv = React.createRef();\n const refWithClass = React.createRef();\n const refWithoutClass = React.createRef();\n // state\n const [s1, setS1] = useState(50);\n // ========================\n let a = 50;\n function changeHandler(event) {\n a = event.target.value;\n console.log(a);\n setS1(event.target.value);\n }\n function changeHandler2() {\n console.log(refRange.current.value);\n refRange.current.style.border = '1px solid red';\n refDiv.current.style.border = '1px solid red';\n refDiv.current.style.width = '150px';\n console.log(refDiv.current.innerHTML);\n console.log(refWithoutClass);\n console.log(refWithClass);\n refWithClass.current.go();\n }\n return (\n <div>\n <div><input type=\"range\" onChange={changeHandler} ref={refRange} /></div>\n <div><button onClick={changeHandler2}>button</button></div>\n <div>Out in app: {a}</div>\n <div>State in app: {s1}</div>\n <div ref={refDiv}>1</div>\n {/* <Ref a2={s1}/> */}\n {/* <Test ref={refWithoutClass} /> */}\n <Test2 ref={refWithClass} />\n </div>\n );\n}", "static async writeRef ({ fs: _fs, gitdir, ref, value }) {\n const fs = new FileSystem(_fs);\n // Validate input\n if (!value.match(/[0-9a-f]{40}/)) {\n throw new Error(`Unexpected ref contents: '${value}'`)\n }\n const normalizeValue = value => value.trim() + '\\n';\n await fs.write(path__WEBPACK_IMPORTED_MODULE_0___default.a.join(gitdir, ref), normalizeValue(value), 'utf8');\n }", "function MakeRef() {\n return { value: false };\n}", "function MakeRef() {\n return { value: false };\n}", "function MakeRef() {\n return { value: false };\n}", "function MakeRef() {\n return { value: false };\n}", "s(_value) {\n this.value = _value;\n this.refresh();\n }", "s(_value) {\n this.value = _value;\n this.refresh();\n }", "function usePrevious(value) {\n var ref = React.useRef(null);\n React.useEffect(function () {\n ref.current = value;\n }, [value]);\n return ref.current;\n}", "function usePrevious (value) {\n const ref = useRef();\n useEffect(() => {\n ref.current = value;\n });\n return ref.current;\n }", "function usePrevious(value) {\n var ref = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useRef\"])(); // Store current value in ref\n\n Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useEffect\"])(function () {\n ref.current = value;\n }, [value]);\n return ref.current;\n}", "constructor() {\n super();\n\n this.myRef = React.createRef();\n }", "function Sub(props, ref) {\n console.log(ref)\n let ref2 = React.useRef()\n React.useImperativeHandle(ref, () => {\n return {\n focus(){\n ref2.current.focus()\n }\n }\n })\n return <div>\n <button onClick={props.handleClick}>plus</button>\n <span>{props.data.age}</span>\n <input ref={ref2}/>\n </div>\n}", "if (\n mounted.current &&\n tracker.current.isActive &&\n (!isSingle || !tracker.current.count)\n ) {\n tracker.current.count++;\n setValue(transform(value));\n }", "function usePrevious(value) {\n var ref = Object(__WEBPACK_IMPORTED_MODULE_0_react__[\"useRef\"])(null);\n Object(__WEBPACK_IMPORTED_MODULE_0_react__[\"useEffect\"])(function () {\n ref.current = value;\n }, [value]);\n return ref.current;\n}", "function App() {\n const valueRef = React.createRef()\n const dynamicInput = React.createRef()\n const dynamicValue = React.createRef()\n\n return (\n <div className=\"App\">\n <Mouse render={mouse => (\n <Fragment>\n <header className=\"App-header\">\n (Mouse Position) x: {mouse.x} y: {mouse.y}\n </header>\n <Cat mouse={mouse} />\n </Fragment>\n )}/>\n </div>\n );\n}", "set value(value)\n {\n this.updated = true\n this._value = value\n }", "function usePrevious(value) {\n var ref = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)();\n (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(function () {\n ref.current = value;\n });\n return ref.current;\n}", "function usePrevious(value) {\n var ref = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)();\n (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(function () {\n ref.current = value;\n });\n return ref.current;\n}", "_set_value(value) {\n if (!this._has_value_flag) {\n this._update_size(1);\n this._has_value_flag = true;\n }\n this._value = value;\n }", "function usePrevious(value) {\n // The ref object is a generic container whose current property is mutable ...\n // ... and can hold any value, similar to an instance property on a class\n const ref = useRef();\n // Store current value in ref\n useEffect(() => {\n ref.current = value;\n }, [value]); // Only re-run if value changes\n // Return previous value (happens before update in useEffect above)\n return ref.current;\n}", "set(_value) {\n if (this.differs(_value)) {\n this.value = _value;\n if (this.id) {\n require('comm/values').changed(this);\n }\n Queue.push(() => {\n this.refresh();\n });\n }\n }", "set(_value) {\n if (this.differs(_value)) {\n this.value = _value;\n if (this.id) {\n require('comm/values').changed(this);\n }\n Queue.push(() => {\n this.refresh();\n });\n }\n }", "function Fay$$readRef(ref,x){\n return ref.value;\n}", "updateFocused(value) {\n debounce(() => {\n if (this.focused !== value) {\n this._focused = value;\n this.render();\n }\n }, 0, this.debounceId);\n }", "function createRef(){var refObject={current:null};{Object.seal(refObject);}return refObject;}", "function createRef(){var refObject={current:null};{Object.seal(refObject);}return refObject;}", "function usePrevious(value) {\n const ref = useRef();\n useEffect(() => {\n ref.current = value;\n });\n return ref.current;\n}", "function usePrevious(value) {\n const ref = useRef();\n useEffect(() => {\n ref.current = value;\n });\n return ref.current;\n}", "function usePrevious(value) {\n const ref = useRef();\n useEffect(() => {\n ref.current = value;\n });\n return ref.current;\n}" ]
[ "0.72959656", "0.7232126", "0.72302204", "0.7175179", "0.7175179", "0.7175179", "0.7175179", "0.7175179", "0.7175179", "0.7175179", "0.7175179", "0.7175179", "0.7175179", "0.7175179", "0.7175179", "0.7175179", "0.7175179", "0.7175179", "0.7175179", "0.7175179", "0.7175179", "0.70239836", "0.70239836", "0.70239836", "0.70239836", "0.70239836", "0.70239836", "0.6986478", "0.69244874", "0.688556", "0.672967", "0.67027354", "0.67027354", "0.67027354", "0.67027354", "0.6702101", "0.6702101", "0.66400707", "0.6628682", "0.6628682", "0.6628682", "0.6628682", "0.6628682", "0.6628682", "0.6628682", "0.6628682", "0.6628682", "0.6628599", "0.6626912", "0.6565006", "0.6382328", "0.63576657", "0.6200572", "0.6151751", "0.61158967", "0.61158967", "0.6068449", "0.6053236", "0.60070264", "0.59551954", "0.5866095", "0.5833232", "0.58099306", "0.5806988", "0.5784512", "0.5767587", "0.56498873", "0.5619105", "0.55909795", "0.5590146", "0.55892545", "0.5577169", "0.5562813", "0.5562813", "0.5562813", "0.5562813", "0.5546542", "0.5546542", "0.55413675", "0.554061", "0.5529433", "0.5514201", "0.5510966", "0.5495827", "0.54954565", "0.5493003", "0.54610294", "0.5460695", "0.5460695", "0.5456527", "0.5454816", "0.5451369", "0.5451369", "0.54280436", "0.53964996", "0.53859633", "0.53859633", "0.5384595", "0.5384595", "0.5384595" ]
0.6786521
30
this.props.sounds is a dictionary of action => Expo.Audio.Sound object see loadSounds() in App.js to see what actions are possible
playSound(action) { try { this.props.sounds[action].playAsync(); this.props.sounds[action].setPositionAsync(0); } catch (err) { console.log("Could not play", action) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "loadDefaultSounds() {\n Object.keys(this.defaultSounds).forEach((key) => {\n this.loadSound(key, this.defaultSounds[key]);\n });\n }", "handleMusicButtonClicked(musicButtonId){\n let buttons = [...this.state.buttons];\n\n\n if(this.props.mappingSound){\n buttons[musicButtonId-1].value = this.props.mappingSound;\n this.props.onMappingDone(\"\");\n return;\n }\n\n if(buttons[musicButtonId-1].value === \".\"){return;}//if some button has no sound\n\n let soundInfo = this.props.getInfoToSound(buttons[musicButtonId-1].value, false);\n\n if(soundInfo.uploadedAudio !== undefined){//if some uploaded sound should be played\n var dst = new ArrayBuffer(soundInfo.uploadedAudio.byteLength);\n new Uint8Array(dst).set(new Uint8Array(soundInfo.uploadedAudio));\n soundInfo.uploadedAudio = dst;\n }else{//if its a standard sound\n soundInfo.URL = process.env.PUBLIC_URL+'/padSoundAudio/'+ buttons[musicButtonId-1].value +'.wav';\n }\n new PadSoundPlayer(soundInfo);\n }", "setSoundState(audibleSound) {\r\n let audibleSoundAction = {\r\n type: AudibleSounds_State_Action_1.audibleSoundsStateActionTypes.SET_SOUND_PRESENCE,\r\n payload: {\r\n audibleSounds: {\r\n CurrentSound: audibleSound.CurrentSound,\r\n PlayStatus: audibleSound.PlayStatus,\r\n Position: audibleSound.Position,\r\n Volume: audibleSound.Volume,\r\n HasPlayed: audibleSound.HasPlayed\r\n }\r\n }\r\n };\r\n this.storeAccess.dispatchAction(audibleSoundAction);\r\n }", "function HomeScreen({ navigation }) {\n\n const [sound, setSound] = React.useState();\n // const [sound2, setSound2] = React.useState();\n\n //this will load the sound and play it when it has loaded\n async function playSound() {\n const { sound } = await Audio.Sound.createAsync(\n require('./assets/whoosh.mp3')\n );\n setSound(sound);\n await sound.playAsync(); }\n\n React.useEffect(() => {\n return sound\n ? () => {\n //unload the sound when it is finished playing\n sound.unloadAsync(); }\n : undefined;\n }, [sound]);\n\n //this function will make the font a size that is reponsive to the size of the screen\n function calcSize(size) {\n if (Platform.OS === 'ios') {\n return Math.round(PixelRatio.roundToNearestPixel(size * Dimensions.get('window').width / 320))\n } else {\n return Math.round(PixelRatio.roundToNearestPixel(size * Dimensions.get('window').width / 320)) - 2\n }\n }\n\n //this will load the fonts from google fonts, using the package expo-fonts\n let [fontsLoaded] = useFonts({\n FredokaOne_400Regular,\n Nunito_400Regular,});\n \n //if the fonts haven't loaded yet, the aoo should show a loading screen\n if (!fontsLoaded) {\n return <AppLoading />;\n } else {\n //when the fonts have loaded in, the rest of the document will be rendered\n return (\n <View style={{flex: 1, backgroundColor: \"#75DDDD\", alignItems: 'center', justifyContent: 'center'}}>\n <Text style={{fontFamily: \"FredokaOne_400Regular\", color: \"white\", fontSize: calcSize(40)}}>Maths Master</Text>\n {/* buttons cannot be styled so you have to make your own by using the TouchableOpacity component */}\n <TouchableOpacity>\n <Text style={{fontFamily: \"Nunito_400Regular\", fontSize: calcSize(35),paddingHorizontal: 20, paddingVertical: 10, borderRadius: 20, elevation: 4, textAlign: 'center', backgroundColor: \"#ffaa5d\",}}\n onPress={() => {\n playSound()\n navigation.navigate('Levels')\n }}>\n Start\n </Text>\n </TouchableOpacity>\n <View>\n {/* there is no conventional way to do a line break so this is used instead */}\n <Text>{\"\\n\"}</Text>\n </View>\n <TouchableOpacity>\n <Text style={{fontFamily: \"Nunito_400Regular\", fontSize: calcSize(25),paddingHorizontal: 20, paddingVertical: 10, borderRadius: 20, elevation: 4, textAlign: 'center', backgroundColor: \"#ffaa5d\",}}\n onPress={() => {\n //this will call the playSound function declared previously\n playSound()\n //this willmove to the tutorial screen\n navigation.navigate('Tutorial')\n }}>\n How to Play\n </Text>\n </TouchableOpacity>\n </View>\n );\n }\n}", "getAudibleSounds() {\r\n return this.store.getState().audibleSoundsState;\r\n }", "function setupSounds() {\n\tfor (var i = 0; i < shovelSounds.filenames.length; i++)\n\t\tshovelSounds.sounds[i] = new Audio(shovelSounds.filenames[i]);\n}", "async function playSound() {\n const sound = new Audio.Sound();\n try {\n var alarm;\n props.alarmSound.map(function (val) {\n if (val.selected) {\n alarm = val.file;\n }\n });\n await sound.loadAsync(alarm);\n await sound.playAsync();\n // Your sound is playing!\n\n // Don't forget to unload the sound from memory\n // when you are done using the Sound object\n //await sound.unloadAsync(alarm);\n } catch (error) {\n // An error occurred!\n }\n }", "initSound() {\n this.enemyDyingSound = this.level.game.add.audio('enemy_dying');\n this.playerHitSound = this.level.game.add.audio('player_hit');\n this.itemCollectSound = this.level.game.add.audio('item_collect');\n this.itemDropoffSound = this.level.game.add.audio('item_dropoff');\n this.advanceLevelSound = this.level.game.add.audio('advance_level');\n this.playerDyingSound = this.level.game.add.audio('player_dying');\n this.music = this.level.game.add.audio('music');\n this.music.volume = .4;\n }", "function Sounds() {\n\n // The audio context.\n this.audioContext = null;\n\n // The actual set of loaded sounds.\n this.sounds = {};\n}", "updateSoundManager(playStatus) {\r\n let audibleSoundFromStore = this.storeAccess.getAudibleSounds();\r\n if (playStatus === AudibleSounds_State_1.AudibleSoundStates.PLAYING && audibleSoundFromStore.Sound.HasPlayed === true) {\r\n playStatus = AudibleSounds_State_1.AudibleSoundStates.STOPPED;\r\n }\r\n else if (playStatus === AudibleSounds_State_1.AudibleSoundStates.PLAYING && audibleSoundFromStore.Sound.HasPlayed === false) {\r\n playStatus = AudibleSounds_State_1.AudibleSoundStates.PLAYING;\r\n }\r\n else if (playStatus === AudibleSounds_State_1.AudibleSoundStates.STOPPED && audibleSoundFromStore.Sound.HasPlayed === true) {\r\n playStatus = AudibleSounds_State_1.AudibleSoundStates.STOPPED;\r\n if (this.getCurrentEjabberdStatus().showBlocker === false) {\r\n audibleSoundFromStore.Sound.HasPlayed = false;\r\n }\r\n }\r\n else if (playStatus === AudibleSounds_State_1.AudibleSoundStates.STOPPED && audibleSoundFromStore.Sound.HasPlayed === false) {\r\n playStatus = AudibleSounds_State_1.AudibleSoundStates.STOPPED;\r\n }\r\n let audibleSoundAction = {\r\n type: AudibleSounds_State_Action_1.audibleSoundsStateActionTypes.SET_SOUND_PRESENCE,\r\n payload: {\r\n audibleSounds: {\r\n CurrentSound: audibleSoundFromStore.Sound.CurrentSound,\r\n PlayStatus: playStatus,\r\n Position: audibleSoundFromStore.Sound.Position,\r\n Volume: audibleSoundFromStore.Sound.Volume,\r\n HasPlayed: audibleSoundFromStore.Sound.HasPlayed\r\n }\r\n }\r\n };\r\n this.storeAccess.dispatchAction(audibleSoundAction);\r\n }", "function loadSounds() {\n createjs.Sound.on(\"fileload\", handleLoad, this);\n // register sounds, which will preload automatically\n createjs.Sound.registerSound(\"/audio/drone.mp3\", soundProximity);\n createjs.Sound.registerSound(\"/audio/water-drop.mp3\", soundClick);\n createjs.Sound.registerSound(\"/audio/snare-2.mp3\", soundSnare);\n}", "_onClickPlayButton () {\n switch (this.props.playbackState) {\n case PlaybackState.Stopped:\n this.props.audioPlayerAction.open(this.props.music, true)\n break\n\n case PlaybackState.Paused:\n this.props.audioPlayerAction.play()\n break\n\n case PlaybackState.Playing:\n this.props.audioPlayerAction.pause()\n break\n\n default:\n break\n }\n }", "componentDidMount(){\r\n this.props.playPauseAudio(this.props.screen, this.props.menu);\r\n this.props.playNext(this.props.screen, this.props.menu, this.props.menuItem,\r\n this.state.cover, this.state.song, this.props.changeMusicItem);\r\n this.props.playPrev(this.props.screen, this.props.menu, this.props.menuItem,\r\n this.state.cover, this.state.song, this.props.changeMusicItem);\r\n }", "async function playSound() {\n const { sound } = await Audio.Sound.createAsync(\n require('./assets/whoosh.mp3')\n );\n setSound(sound);\n await sound.playAsync(); }", "async playSong2() {\n console.log(\"Loading Sound\");\n const { sound } = await Audio.Sound.createAsync(\n require(\"../assets/No-More-What-Ifs.mp3\")\n );\n this.setState({ sound: sound });\n\n console.log(\"Playing Sound\");\n await sound.playAsync();\n }", "handleAudioPlayed() {\n const { activeTrackIndex } = this.props;\n if(activeTrackIndex !== undefined) this.props.actions.togglePlaying(true);\n }", "function initSounds() {\r\n sounds.set('background_music', new Audio(document.getElementById(\"background_music\").src));\r\n sounds.set('shorter_drill', new Audio(document.getElementById(\"shorter_drill\").src));\r\n sounds.set('short_drill', new Audio(document.getElementById(\"short_drill\").src));\r\n sounds.set('med_drill', new Audio(document.getElementById(\"med_drill\").src));\r\n sounds.set('long_drill', new Audio(document.getElementById(\"long_drill\").src));\r\n sounds.set('scale_b', new Audio(document.getElementById(\"scale01\").src));\r\n sounds.set('scale_t', new Audio(document.getElementById(\"scale02\").src));\r\n}", "function renderDefaultSounds() { // creates default instances and renders the audio assets for playback\r\n var thunder = new Sound('thunder', 'ogg', '100', '0.25');\r\n var rain = new Sound('rain', 'ogg', '100', '0.25');\r\n var beach = new Sound('beach', 'ogg', '0', '0');\r\n var waterfall = new Sound('waterfall', 'ogg', '85', '0.2125');\r\n var stream = new Sound('stream', 'ogg', '100', '0.25');\r\n var canopy = new Sound('canopy', 'ogg', '0', '0');\r\n var frogs = new Sound('frogs', 'ogg', '0', '0');\r\n thunder.fetchAudio();\r\n rain.fetchAudio();\r\n beach.fetchAudio();\r\n waterfall.fetchAudio();\r\n stream.fetchAudio();\r\n canopy.fetchAudio();\r\n frogs.fetchAudio();\r\n}", "function actionOnClickMult() {\n confirm_sound.play()\n this.state.start('Mult_dif')\n}", "getSoundState() {\r\n return this.storeAccess.getAudibleSounds();\r\n }", "async playSong3() {\n console.log(\"Loading Sound\");\n const { sound } = await Audio.Sound.createAsync(\n require(\"../assets/Last-Surprise.mp3\")\n );\n this.setState({ sound: sound });\n\n console.log(\"Playing Sound\");\n await sound.playAsync();\n }", "getDisplaySound() {\n\n return (this.props.properties.display ? this.transliterate(this.props.properties.display) : this.transliterate(this.props.properties.sound));\n }", "updatePlayStatus(status) {\r\n /* Get the current state for the audible sounds. */\r\n let audibleSound = this.props.audibleSoundsManager.getSoundState();\r\n /* Update the properties to disable the sound. */\r\n audibleSound.Sound.PlayStatus = status;\r\n audibleSound.Sound.HasPlayed = true;\r\n /* Call to the service to update the state in the redux store. */\r\n this.props.audibleSoundsManager.setSoundState(audibleSound.Sound);\r\n }", "function loadSounds(sounds, callback) {\n\tlet name,\n\t\tresult = {},\n\t\tcount = sounds.length;\n\tlet canplay = function () {\n\t\tcount--;\n\t\tif (count == 0) {\n\t\t\tcallback(result);\n\t\t}\n\t};\n\n\tfor (let i = 0; i < sounds.length; i++) {\n\t\tname = sounds[i];\n\t\tresult[name] = new Audio();\n\t\tresult[name].addEventListener(\"canplay\", canplay, false);\n\t\tresult[name].src = `${name}.mp3`;\n\t}\n}", "function loadSound() {\n createjs.Sound.addEventListener(\"fileload\", handleLoad);\n createjs.Sound.registerSounds(bgm);\n createjs.Sound.registerSounds(sfx);\n}", "function playAudio() {\n sounds.play();\n}", "getButtonClickId(soundId){\n let result = this.state.storeUsed.filter(sound => {\n return sound.keyTrigger === soundId\n })\n this.setState({\n soundText: result[0].id\n });\n }", "function playStartingSounds() {\n forest_ambience.play()\n piano.play()\n \n}", "playMusic(routineMusic) {\n // Load the sound file from the app bundle\n let music = new Sound(routineMusic, Sound.MAIN_BUNDLE, (error) => {\n if (error) {\n console.log('failed to load the sound', error);\n return;\n }\n // loaded successfully\n console.log('duration in seconds: ' + music.getDuration() + 'number of channels: ' + music.getNumberOfChannels());\n music.setNumberOfLoops(-1); // loop indefinitely until stop() called\n music.play((success) => {\n if (success) {\n console.log('successfully finished playing');\n } else {\n console.log('playback failed due to audio decoding errors');\n music.reset();\n }\n });\n });\n\n return music;\n }", "getRecordSound(state){\n return state.recordSound\n }", "async function playSound() {\n console.log('Loading Sound');\n const { sound } = await Audio.Sound.createAsync( // class that creates a sound object\n {uri: RecordedURI} // source of the sound\n );\n setSound(sound); // state of sound\n\n console.log('Playing Sound');\n await sound.playAsync(); }", "handleSound() {\n\n this.alarm = new Audio();\n this.alarm.src = \"https://soundbible.com/grab.php?id=1441&type=wav\";\n this.state.timerRunning === false ? this.alarm.pause() : this.alarm.play();\n\n }", "function playSound(buttonClicked)\n{\n switch(buttonClicked)\n {\n case \"a\":\n var a = new Audio(\"/Drum-kit/drum-kit sounds/tom-1.mp3\");\n a.play();\n break;\n\n case \"b\":\n var b = new Audio(\"/Drum-kit/drum-kit sounds/tom-2.mp3\");\n b.play();\n break;\n\n case \"c\":\n var c = new Audio(\"/Drum-kit/drum-kit sounds/tom-3.mp3\");\n c.play();\n break;\n\n case \"d\":\n var d = new Audio(\"/Drum-kit/drum-kit sounds/tom-4.mp3\");\n d.play();\n break;\n\n case \"e\":\n var crash = new Audio(\"/Drum-kit/drum-kit sounds/crash.mp3\");\n crash.play();\n break;\n\n\n case \"f\":\n var snare = new Audio(\"/Drum-kit/drum-kit sounds/snare.mp3\");\n snare.play();\n break;\n \n\n default: console.log(\"None\");\n }\n\n}", "playSound(config = {}) {\n\n\t\t// Contextualizing the config object\n\t\tconst conf = this.contextConfig(config);\n\n\t\t// Checking if sound is enbaled\n\t\tif (conf.sound.enabled === true) {\n\n\t\t\t// Getting a random index\n\t\t\tconst index = Math.floor((Math.random()) * 2);\n\n\t\t\t// Formatting the sound base\n\t\t\tconst typingSound = `data:audio/mpeg;base64,${TYPING_SOUNDS[index]}`\n\n\t\t\t// Constructing an audio object\n\t\t\tconst audio = new Audio(typingSound);\n\n\t\t\t// Setting the volume\n\t\t\taudio.volume = Math.max(Math.min(parseFloat(conf.sound.volume) || 0.5, 1), 0);\n\n\t\t\t// Playing the typing sounds\n\t\t\taudio.play();\n\t\t}\n\t}", "function addSound(buttonOrKey){\n switch(buttonOrKey){\n case \"w\":\n var crash = new Audio(\"sounds/crash.mp3\");\n crash.play();\n break;\n\n case \"a\":\n var kick = new Audio(\"sounds/kick-bass.mp3\");\n kick.play();\n break;\n\n case \"s\":\n var snare = new Audio(\"sounds/snare.mp3\");\n snare.play();\n break;\n\n case \"d\":\n var tom1 = new Audio(\"sounds/tom-1.mp3\");\n tom1.play();\n break;\n\n case \"j\":\n var tom2 = new Audio(\"sounds/tom-2.mp3\");\n tom2.play();\n break;\n\n case \"k\":\n var tom3 = new Audio(\"sounds/tom-3.mp3\");\n tom3.play();\n break;\n\n case \"l\":\n var tom4 = new Audio(\"sounds/tom-4.mp3\");\n tom4.play();\n break;\n\n default:\n console.log(buttonOrKey);\n }\n}", "function preload() {\n //suono\n backgroundSound = loadSound(\"./assets/sounds/background_sound.mp3\");\n\n}", "makeSound() {\n console.log('overriding sound');\n }", "function playAudio(){\n let audio = new Audio('sounds/press.wav');\n audio.play();\t\t\t\n}", "_playSound(){\n switch(this._word){\n case \"bellatrix lestrange\":\n this._audio.src = \"assets/sounds/Bellatrix.mp3\";\n break;\n case \"dolores umbridge\":\n this._audio.src = \"assets/sounds/deloros.mp3\";\n break;\n case \"hermione granger\":\n this._audio.src = \"assets/sounds/hermione.mp3\";\n break;\n case \"luna lovegood\":\n this._audio.src = \"assets/sounds/luna.mp3\";\n break;\n case \"harry potter\":\n this._audio.src = \"assets/sounds/harry.mp3\";\n break;\n default: \n this._audio.src = \"assets/sounds/harry_potter_theme.mp3\";\n break;\n }\n this._audio.play(); \n }", "constructor() {\n this.countdownSound = new Audio('assets/audio/countdown.mp3');\n this.turnSound = new Audio('assets/audio/turn.mp3');\n this.pairSound = new Audio('assets/audio/pair.mp3');\n this.winnerSound = new Audio('assets/audio/winner.mp3');\n this.gameOverSound = new Audio('assets/audio/gameover.mp3');\n // and language audio for future features\n this.countdownSound.volume = 0.5;\n this.countdownSound.loop = true;\n this.turnSound.volume = 0.5\n this.winnerSound.volume = 0.5;\n }", "initGameMenuSound()\n {\n var sound = new buzz.sound(\"assets/sciAudio.mp3\");\n sound.load();\n sound.loop().play();\n sound.setVolume(GAME_PLAY_MUS);\n }", "function preload(){\n soundFormats('wav','mp3','ogg');\n\n //load our sounds into the soundArray\n soundFile = '/assets/roland.wav'\n sound1 = loadSound(soundFile);\n}", "function initGameSounds(effect){\n var soundEffect = new THREE.AudioListener();\n scene.add(soundEffect);\n\n var sound = new THREE.Audio(soundEffect);\n\n var soundLoader = new THREE.AudioLoader();\n soundLoader.load( 'libs/sounds/'+effect, function(buffer){\n sound.setBuffer( buffer );\n sound.setLoop( false );\n sound.setVolume( 0.5 );\n sound.play();\n });\n }", "function plyanimsound(soundeffect){\n const soundplay = new Audio(`/static/frontend/sounds/cards/${soundeffect}.wav`);\n soundplay.loop = false;\n soundplay.play();\n}", "play(options) {\n const { sounds } = this;\n const index = this.count++ % sounds.length;\n sounds[index].play(options);\n }", "function preload() {\n sound = {\n hitWall: loadSound(\"./sounds/hit-wall.wav\"),\n hitPaddle: loadSound(\"./sounds/hit-paddle.wav\"),\n increasePlayerScore: loadSound(\"./sounds/increase-score.wav\"),\n };\n}", "function musicians(state=[], action){\n if(action.type === \"MUSICIANS_LOADED\"){\n return action.value;\n }\n return state;\n}", "function playSound(name){\n let audio = new Audio(\"sounds/\"+name+\".mp3\");\n audio.play();\n}", "function preload() {\n music = loadSound(\"assets/snakemenu.mp3\");\n eatSound = loadSound(\"assets/eatfoodsound.mp3\");\n}", "playCorrectSound() {\n this.correctSound.play();\n }", "function playSound() {\n // Set the src\n sound.src = `audio/${event.target.name}.mp3`;\n // Play the sound\n sound.play();\n}", "function SoundSoundSound({name, keyboard}) {\n const [isActive, setIsActive] = useState(false)\n const toneRef = useRef(null)\n\n const onDown = useCallback(() => {\n setIsActive(true)\n toneRef.current.triggerAttackRelease(\"C4\", \"4n\")\n }, [setIsActive])\n\n const handleKeyDown = useCallback((event) => {\n // this prevents multiple firings when key stays pressed\n if (event.repeat) {\n return\n }\n if (event.key === keyboard) {\n setIsActive(true)\n toneRef.current.triggerAttackRelease(\"C4\", \"4n\")\n }\n }, [toneRef]);\n\n const handleKeyUp = useCallback((event) => {\n if (event.key === keyboard) {\n setIsActive(false)\n }\n }, [setIsActive])\n\n useEffect(() => {\n document.addEventListener(\"keydown\", handleKeyDown, false);\n document.addEventListener(\"keyup\", handleKeyUp, false);\n\n return () => {\n document.removeEventListener(\"keydown\", handleKeyDown, false)\n document.removeEventListener(\"keyup\", handleKeyUp, false)\n };\n }, [handleKeyUp, handleKeyDown]);\n\n useEffect(() => {\n toneRef.current = new Tone.Sampler({\n urls: {\n C4: `${process.env.PUBLIC_URL}/drums/808/${name}.wav`\n }\n }).toDestination();\n }, [])\n\n return (\n <LaunchpadButton\n onMouseDown={onDown}\n onMouseUp={\n () => setIsActive(false)\n }\n // don't store the active state if mouse is dragged outside\n onMouseLeave={() => setIsActive(false)}\n onTouchStart={onDown}\n isActive={isActive}\n onTouchEnd={e => {\n e.preventDefault()\n setIsActive(false)\n }}>\n {name} ({keyboard})\n </LaunchpadButton>\n )\n}", "handleAudioPaused() {\n const { activeTrackIndex } = this.props;\n if(activeTrackIndex !== undefined) this.props.actions.togglePlaying(false);\n }", "function updateSound() {\n let sound = id('sound');\n let path = \"img/ionic-ios-musical-notes\";\n if (isMuted) {\n path += \"-muted\"; // use the muted version\n }\n if (isDarkMode) {\n path += \"-dark\"; // use the dark mode version\n }\n sound.src = path + \".png\";\n }", "function playSound () {\n if (displaySettings.getValue('soundsPlay') && audioElements[currentStatus]) {\n audioElements[currentStatus].play();\n }\n }", "function preload()\n{\n voiceOverA = loadSound('assets/voiceover_a.mp3');\n voiceOverB = loadSound('assets/voiceover_b.mp3');\n voiceOverC = loadSound('assets/voiceover_c.mp3');\n voiceOverD = loadSound('assets/voiceover_d.mp3');\n voiceOverE = loadSound('assets/voiceover_e.mp3');\n voiceOverF = loadSound('assets/voiceover_f.mp3');\n voiceOverG = loadSound('assets/voiceover_g.mp3');\n}", "function pacSound(){\n //const move = new Audio('pacman_chomp.wav')\n //move.play()\n }", "function makeSounds(){\n\t// all timecodes are in seconds format... converted to milliseconds at runtime (onPlay event)\n\t\n\t//quiz sfx:\n\tmakeSound('sfx_biscuits', 116.056104, 117.029715);\n\tmakeSound('sfx_splat', 117.308417, 118.419256);\n\tmakeSound('sfx_pie', 118.502263, 119.312165);\n\tmakeSound('sfx_lazer', 119.481508, 121.524669);\n\tmakeSound('sfx_wrong', 122.087919, 123.427938);\n\n\n\t//question-specific audio:\n console.log(\"making sounds\");\n\tmakeSound('q_q0', 0.495087, 3.701368);\n\tmakeSound('q_qscene', 0.495087, 3.701368);\n\tmakeSound('q_qconveyer', 0.495087, 3.701368);\n\tmakeSound('q_qfootball', 0.495087, 3.701368);\n\tmakeSound('q_qfootball1', 19.685622, 23.599171);\n\tmakeSound('q_qfootball2', 30.719000, 35.174788);\n\tmakeSound('q_qskywheel', 30.719000, 35.174788);\n\tmakeSound('q_q6', 38.027435, 40.078511);\n\tmakeSound('q_q7', 41.469472, 45.170840);\n\tmakeSound('q_q9', 46.278893, 47.787731);\n\tmakeSound('q_qblocklink', 0.495087, 3.701368, [\"请\", \"连\", \"线\"], [0.495087, 1.1, 2.2]);\n\tmakeSound('q_qpiglink', 0.495087, 3.701368, [\"请\", \"连\", \"线\"], [0.495087, 1.1, 2.2]);\n\tmakeSound('q_qpresenta', 0.495087, 3.701368, [\"If \", \"you want to measure the weight of something you use a \"], [0.495087, 1.1]);\n\tmakeSound('q_qpresentb', 0.495087, 3.701368, [\"If \", \"you want to measure the weight of something you use a \"], [0.495087, 1.1]);\n\tmakeSound('q_qblock', 4.856573, 8.793697);\n\tmakeSound('q_qfruit', 4.856573, 8.793697);\n\tmakeSound('q_qcard', 4.856573, 8.793697);\n\tmakeSound('q_qstadium', 4.856573, 8.793697);\n\tmakeSound('q_qscale', 4.856573, 8.793697);\n\tmakeSound('q_qanimal', 4.856573, 8.793697);\n\tmakeSound('q_qanimal1', 4.856573, 8.793697);\n\tmakeSound('q_qanimal2', 30.719000, 35.174788);\n\tmakeSound('q_qanimal3', 4.856573, 8.793697);\n\tmakeSound('q_qanimal4', 4.856573, 8.793697);\n makeSound('q_qblock1', 4.856573, 8.793697);\n makeSound('q_qblock2', 30.719000, 35.174788);\n makeSound('q_qblock3', 4.856573, 8.793697);\n makeSound('q_qblock4', 4.856573, 8.793697);\n\tmakeSound('q_qsupermarket', 4.856573, 8.793697);\n\tmakeSound('q_qsupermarket1', 4.856573, 8.793697);\n\tmakeSound('q_qsupermarket2', 30.719000, 35.174788);\n\tmakeSound('q_qsupermarket3', 4.856573, 8.793697);\n\tmakeSound('q_qsupermarket4', 4.856573, 8.793697);\n\tmakeSound('q_qpresent1', 4.856573, 8.793697);\n\tmakeSound('q_qpresent2', 30.719000, 35.174788);\n\tmakeSound('q_qpresent3', 4.856573, 8.793697);\n\tmakeSound('q_qpresent4', 4.856573, 8.793697);\n\tmakeSound('q_qtrain', 0.495087, 3.701368, [\"If \", \"you want to measure the weight of something you use a \"], [0.495087, 1.1]);\n\tmakeSound('q_qtrain1', 4.856573, 8.793697);\n makeSound('q_qtrain2', 4.856573, 8.793697);\n makeSound('q_qtrain3', 4.856573, 8.793697);\n makeSound('q_qtrain4', 4.856573, 8.793697);\n\tmakeSound('q_qstadium1', 4.856573, 8.793697);\n makeSound('q_qstadium2', 4.856573, 8.793697);\n makeSound('q_qstadium3', 4.856573, 8.793697);\n makeSound('q_qstadium4', 4.856573, 8.793697);\n\tmakeSound('q_qcard1', 4.856573, 8.793697);\n makeSound('q_qcard2', 4.856573, 8.793697);\n makeSound('q_qcard3', 4.856573, 8.793697);\n makeSound('q_qcard4', 4.856573, 8.793697);\n\tmakeSound('q_qfruit1', 4.856573, 8.793697);\n makeSound('q_qfruit2', 4.856573, 8.793697);\n makeSound('q_qfruit3', 4.856573, 8.793697);\n makeSound('q_qfruit4', 4.856573, 8.793697);\n\tmakeSound('q_q2', 4.856573, 8.793697);\n\tmakeSound('q_q21', 4.856573, 8.793697);\n\tmakeSound('q_q22', 4.856573, 8.793697);\n\tmakeSound('q_q3', 10.161081, 12.730821);\n\tmakeSound('q_q4', 14.239659, 17.516667);\n\tmakeSound('q_q8', 19.685622, 23.599171);\n\tmakeSound('q_q5', 25.579521, 29.139435);\n\tmakeSound('q_q10', 30.719000, 35.174788);\n\tmakeSound('q_q11', 30.719000, 35.174788);\n\tmakeSound('q_q6', 38.027435, 40.078511);\n\tmakeSound('q_q7', 41.469472, 45.170840);\n\tmakeSound('q_q9', 46.278893, 47.787731);\n\tmakeSound('q_q13',0.44444,0.55555);\n\tmakeSound('q_qfishing',0.44444,0.55555);\n\n\n\tmakeSound('determine it', 49.555901, 50.593227);\n\tmakeSound('apply it', 51.347646, 52.432123);\n\tmakeSound('stopwatch', 53.775932, 54.907561);\n\tmakeSound('construct it', 55.567677, 56.652155);\n\tmakeSound('sweep it', 57.642330, 58.608929);\n\tmakeSound('ruler', 59.764133, 60.494977);\n\tmakeSound('divide it', 61.650181, 62.593205);\n\tmakeSound('comfort it', 63.347624, 64.267072);\n\tmakeSound('measure', 64.832886, 65.360961);\n\tmakeSound('scale', 66.011666, 66.695058);\n\tmakeSound('weight', 67.025416, 67.584555);\n\tmakeSound('水星', 67.025416, 67.584555);\n\tmakeSound('金星', 67.025416, 67.584555);\n\tmakeSound('火星', 67.025416, 67.584555);\n\tmakeSound('短', 68.109894, 68.675708);\n\tmakeSound('中', 69.194371, 69.939889);\n\tmakeSound('长', 70.184546, 70.942490);\n\tmakeSound('train_whistle', 70.184546, 70.942490);\n\tmakeSound('length ', 68.109894, 68.675708);\n\tmakeSound('height', 69.194371, 69.939889);\n\tmakeSound('speed', 70.184546, 70.942490);\n\tmakeSound('distance', 71.304387, 72.348112);\n\tmakeSound('temperature', 72.506742, 73.252260);\n\tmakeSound('estimate', 73.544068, 74.115405);\n\tmakeSound('compare', 115.797153,116.481301);\n\tmakeSound('f_q0', 75.630509, 78.512319);\n\tmakeSound('f_qpresenta', 75.630509, 78.512319);\n\tmakeSound('f_qpresentb', 75.630509, 78.512319);\n\tmakeSound('f_q2', 78.872153, 81.887586);\n\tmakeSound('f_q21', 78.872153, 81.887586);\n\tmakeSound('f_q22', 78.872153, 81.887586);\n\tmakeSound('f_q3', 82.408492, 85.906000);\n\tmakeSound('f_q4', 86.227739, 89.547433);\n\tmakeSound('f_q5', 89.988046, 92.651904);\n\tmakeSound('f_q6', 92.946783, 95.153372);\n\tmakeSound('f_q7', 95.386857, 97.760293);\n\tmakeSound('f_q8', 98.027324, 101.659857);\n\tmakeSound('f_q9', 102.082326, 103.851766);\n\tmakeSound('f_q10', 104.145191, 107.206568);\n\tmakeSound('f_q11', 104.145191, 107.206568);\n\tmakeSound('f_qrope', 104.145191, 107.206568);\n\t\n\t//required for quiz question outocomes:\n\tmakeSound('empty', 4.5,4.6);\n\tmakeSound('quizmo', 107.410411, 108.640050);\n\tmakeSound('correct_1', 109.011801, 110.198546);\n\tmakeSound('correct_2', 110.355825, 111.560707);\n\tmakeSound('incorrect_1', 111.927255, 113.158259);\n\tmakeSound('incorrect_2', 113.887464, 115.196398);\t\n}", "function readArrayOfSounds(indice,arraySounds)\n{\n // alert(arrayTextToSpeak[indice]+\" indice: \"+indice);\n if(indice<arraySounds.length)\n {\n stopAllSounds();//detenemos todos los sonidos\n soundManager.createSound({\n id:'a'+indice,\n url:arraySounds[indice]\n });\n \n soundManager.play('a'+indice,{\n multiShotEvents:true,\n onfinish:function(){\n // soundManager.destroySound('a'+indice);\n stopAllSounds();\n if((indice+1)<arraySounds.length)\n readArrayOfSounds(indice+1,arraySounds);\n }//onfinish\n\n });//play\n\n }//if indice limits\n}", "constructor () {\n /**\n * Holds the Sound instances\n * @type {Object}\n * @private\n */\n this.__collection = {}\n /**\n * Determines if the Sounds are enabled\n * @type {Boolean=false}\n * @private\n */\n this.__enabled = false\n }", "function preload()\n{\n tile_sound = loadSound(\"Sounds/CodingPower.mp3\");\n light_sound = loadSound(\"Sounds/SciFi.mp3\");\n //\"Sounds/Input-02.mp3\");\n}", "playSound() {\n if (this.sound) {\n this._soundID = this.sound.play(this.playheadSoundOffsetMS + this.cropSoundOffsetMS, this.soundVolume);\n }\n }", "function playSoundX(s) {\n if (Settings.sounds) top.soundWrapX(s);\n}", "function preload() {\n popSFX = loadSound(`assets/sounds/pop.wav`);\n}", "makeAudio() {\n sfx.absorb = this.sound.add('absorb');\n sfx.bullet = this.sound.add('bullet');\n sfx.extend = this.sound.add('extend');\n sfx.gameover = this.sound.add('gameover');\n sfx.levelup = this.sound.add('levelup');\n sfx.laser = this.sound.add('laser');\n sfx.lose = this.sound.add('lose');\n sfx.move = this.sound.add('move');\n sfx.ready = this.sound.add('ready');\n }", "meow(sound) {\n console.log(sound);\n }", "function playSound() {\n // play the source now\n soundSource.noteOn(context.currentTime);\n }", "constructor(sound) {\n this._sound = sound;\n }", "function playConsume(){\t\t\t\n let audio = new Audio('sounds/eat.mp3');\n audio.play();\t\t\t\n}", "function soundAdder(scene) {\n scene.sound_gameover = scene.sound.add('gameover');\n scene.sound_brick = scene.sound.add('brick');\n scene.sound_ballplayer = scene.sound.add('ballplayer');\n scene.sound_ballwalls = scene.sound.add('ballwalls');\n scene.sound_bullet = scene.sound.add('bullet');\n scene.sound_gamewin = scene.sound.add('gamewin');\n scene.sound_sword = scene.sound.add('sword');\n scene.sound_life = scene.sound.add('life');\n\n scene.sound_gameover.config.volume = 0.5;\n scene.sound_brick.config.volume = 2;\n scene.sound_ballplayer.config.volume = 10;\n scene.sound_ballwalls.config.volume = 10;\n scene.sound_bullet.config.volume = 0.5;\n scene.sound_gamewin.config.volume = 0.5;\n scene.sound_sword.config.volume = 1;\n scene.sound_life.config.volume = 4;\n}", "function actionOnClickFact() {\n confirm_sound.play()\n this.state.start('Fact_dif')\n}", "enterSoundSOUND(ctx) {\n\t}", "function playSound(pressed_button) {\n var audio_for_button = new Audio(\"sounds/\" + pressed_button + \".mp3\");\n audio_for_button.play();\n}", "playAllClips() {\n if (this.clips && this.clips.length) {\n this.clips.forEach((clip) => {\n this.state.actionStates[clip.name] = true;\n var action = this.mixer.clipAction(clip);\n action.setEffectiveTimeScale(1);\n action.reset();\n console.log(\"playing clip: \" + clip.name);\n action.play();\n });\n }\n }", "function PlayHitSound() { \n \n hitSound.play()\n console.log(\"play\")\n}", "enterSettingsSoundsFolder(ctx) {\n\t}", "componentDidMount() {\n document.addEventListener(\"keydown\", (e) => {\n const sound = document.querySelector(`#${e.key.toUpperCase()}`);\n sound && sound.play();\n sound && this.props.setMessage(e.key.toUpperCase());\n });\n}", "function playSound(event) {\n let btn = $(this).data().type;\n switch (btn) {\n case \"planets\":\n planetsWav.play();\n planetsWav.currentTime=0;\n break;\n\n case \"people\":\n peopleWav.play();\n peopleWav.currentTime=0;\n break;\n\n case \"starships\":\n starshipsWav.play();\n starshipsWav.currentTime=0;\n break;\n\n case \"species\":\n speciesWav.play();\n speciesWav.currentTime=0;\n break; \n\n case \"films\":\n filmsWav.play();\n filmsWav.currentTime=0;\n break; \n default:\n break;\n };\n}", "function sounds() {\n return src(source + 'sounds/*.mp3')\n .pipe(dest(destination + 'sounds'));\n}", "playSound(soundID) { return null; }", "function preload(){\n soundFile = loadSound(\"assets/CowMoo.mp3\");\n}", "playIncorrectSound() {\n this.incorrectSound.play();\n }", "function playSound(sound) {\n sounds[sound].currentTime = 0;\n sounds[sound].play();\n}", "function playStartSound() {\n const tmpStartSound = new Audio(\"sounds/Big-Hit-15-_reverb_.wav\");\n tmpStartSound.play();\n}", "function playTypeSound() {\n if (sound) {\n typeSound.play();\n }\n }", "function playSound(name) {\n let audio = new Audio(\"sounds/\" + name + \".mp3\");\n audio.play();\n}", "function sound(pressed)\r\n{\r\n \r\n \r\n \r\n switch (pressed) {\r\n case \"w\":\r\n {\r\n var audio = new Audio(\"sounds/tom-1.mp3\");\r\n audio.play();\r\n }\r\n \r\n break;\r\n \r\n case \"a\":\r\n {\r\n var audio = new Audio(\"sounds/tom-2.mp3\");\r\n audio.play();\r\n }\r\n \r\n break;\r\n \r\n case \"s\":\r\n {\r\n var audio = new Audio(\"sounds/crash.mp3\");\r\n audio.play();\r\n }\r\n \r\n break;\r\n \r\n case \"d\": \r\n {\r\n var audio = new Audio(\"sounds/snare.mp3\");\r\n audio.play();\r\n }\r\n \r\n break;\r\n \r\n case \"j\":\r\n {\r\n var audio = new Audio('sounds/kick-bass.mp3');\r\n audio.play();\r\n }\r\n \r\n break;\r\n \r\n case \"k\":\r\n {\r\n var audio = new Audio('sounds/tom-3.mp3');\r\n audio.play();\r\n } \r\n \r\n break;\r\n \r\n case \"l\":\r\n {\r\n var audio = new Audio('sounds/tom-4.mp3');\r\n audio.play();\r\n } \r\n \r\n \r\n break;\r\n \r\n default:console.log(button_pressed);\r\n }\r\n \r\n \r\n \r\n }", "function playSound(name) {\r\n let audio = new Audio(\"sounds/\" + name + \".mp3\");\r\n audio.play();\r\n }", "waveGeneratorButtonSound( pressed ) {\n\n // no-op\n }", "function playSound() {\n\tvar soundIndex = Math.floor(Math.random() * shovelSounds.sounds.length);\n\tshovelSounds.sounds[soundIndex].play();\n}", "function playSound(name) {\n sounds[name].currentTime = 0;\n sounds[name].play();\n sounds[name].onended = function () {\n playSound(name);\n };\n } //end playSound", "function playBtnSound(button) {\n switch (button) {\n case 0:\n yellowBtnSound.play();\n break;\n case 1:\n redBtnSound.play();\n break;\n case 2:\n greenBtnSound.play();\n break;\n case 3:\n blueBtnSound.play();\n break;\n }\n }", "playClip() {\n // console.log('playClip triggered');\n this.state.clip.play(); // play the audio elem currently stored in state.clip\n }", "function playSound(key) {\n var audio = new Audio(`sounds/${key}.mp3`);\n audio.play();\n}", "function PlaySoundNotification()\n{\n if(widget.preferences['enableSound'] == 'on')\n {\n // Init Audio-Object if necessary\n if(!AudioObject) AudioObject = new Audio;\n \n // Set Source and play\n AudioObject.src = \"/sound/\" + widget.preferences['soundfile'];\n AudioObject.play();\n \n DebugMessage(\"Notification '\" + widget.preferences['soundfile'] + \"' is played\");\n }\n}", "function preload(){\n soundtrack = loadSound(\"soundtrack.mp3\");\n pointSound = loadSound(\"pointSound.mp3\");\n racketSound = loadSound(\"racketSound.mp3\");\n}", "playWinSound() {\n this.winSound.play();\n }", "function preload() {\n // load your sound files here\n}", "function Sound(name, extension, sliderDefault, volumeDefault) { // utilizes decodeAudioData for audio assets that are responsive and interative (for looping seemlessly)\r\n this.name = name;\r\n this.extension = extension;\r\n this.filepath = `./audio/sounds/${name}.${extension}`;\r\n this.buffer = '';\r\n this.sliderDefault = sliderDefault;\r\n this.volumeDefault = volumeDefault;\r\n this.fetchAudio = function() {\r\n fetch(`https://elijah-dungan.github.io/ogg/${this.name}.${this.extension}`) // TODO: change to this.filepath for final deployment\r\n .then(response => response.arrayBuffer()) // takes response stream and reads it to completion\r\n .then(arrayBuffer => audioContext.decodeAudioData(arrayBuffer)) // asynchronously decodes completely read audio stream\r\n .then(audioBuffer => { // represents audio asset\r\n this.buffer = audioBuffer;\r\n });\r\n };\r\n allSounds.push(this);\r\n}", "AddPlaying(sound) {\n if(!this.IsPlaying(sound.name)) this.playingSounds.push(sound);\n }" ]
[ "0.7028121", "0.6894463", "0.66668814", "0.66233325", "0.6544734", "0.643667", "0.6420641", "0.6401536", "0.6377672", "0.6365446", "0.63530886", "0.63278306", "0.6322497", "0.6277754", "0.6257085", "0.6210725", "0.6206442", "0.61829025", "0.6148332", "0.61385065", "0.6084578", "0.6060771", "0.6057383", "0.6050072", "0.60331607", "0.6020709", "0.5996736", "0.59725994", "0.595925", "0.5943256", "0.593154", "0.5920117", "0.5916617", "0.59100026", "0.58833665", "0.58718246", "0.5863085", "0.5862006", "0.58501667", "0.5849752", "0.5848371", "0.5843323", "0.58364433", "0.5834807", "0.5833563", "0.5831626", "0.58274037", "0.58257633", "0.58183146", "0.5815778", "0.5809633", "0.58037525", "0.5802581", "0.5800059", "0.57945", "0.5792144", "0.57892656", "0.5783132", "0.5774768", "0.5763182", "0.57510895", "0.57426405", "0.57352936", "0.5734794", "0.57345", "0.5734073", "0.57302237", "0.5730053", "0.5726128", "0.5725852", "0.5716511", "0.5709707", "0.5708261", "0.5703309", "0.5700627", "0.5699256", "0.5695789", "0.56902105", "0.5684059", "0.56801766", "0.5673847", "0.56692785", "0.5663251", "0.5662176", "0.5657767", "0.56454563", "0.56449497", "0.56436837", "0.56398124", "0.5632687", "0.5629739", "0.56259567", "0.56138587", "0.5612072", "0.5607229", "0.560633", "0.5599037", "0.5598489", "0.5597851", "0.5596822" ]
0.76544875
0
/////// Render Function /////////
renderScreen(status) { let path, onPress, accLabel; switch (status) { case 'intro': path=require('../resources/screens/intro.png') onPress=(() => this.setState({ gameStatus: 'started', stageIdx: 0, currentCommands: [] })) accLabel = "Hello, I am Cody. Today, let's play a game that would teach us the basics of computer science. I look forward to it. Would you like to touch the screen to start?" break case 'fail': this.playSound('fail') path=require('../resources/screens/failed.jpg') onPress=(() => this.setState({ gameStatus: 'started', currentCommands: [] })) accLabel = "Touch the screen to try again." break case 'success': this.playSound('success') path=require('../resources/screens/success.jpg') onPress=(() => { this.setState({ gameStatus: 'started', stageIdx: this.state.stageIdx+1, currentCommands: [] })}) accLabel = "Good job, touch the screen to move to the next stage" break; case 'finished': // reset the game this.playSound('success') path=require('../resources/screens/final.jpg') onPress=(() => this.setState({gameStatus: 'intro'})) accLabel = "You finished all the stage." break; default: throw ("Unrecognizable game status: " + this.gameStatus) } return ( <TouchableHighlight style={styles.wholeWrapper} onPress={onPress} accesible={true} accessibilityLabel={accLabel}> <Image style={styles.screenWrapper} source={path}/> </TouchableHighlight> ) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function render() {\n\n\t\t\t}", "function render() {\n\t\t\n\t}", "function render() {\n\t\t\t}", "function render() {\n\t}", "render() {}", "render() {}", "render() {}", "_render() {}", "function render() {\r\n\r\n}", "function render() {\r\n\r\n}", "render() {\n\n\t}", "render() {\n\n\t}", "render() { }", "render(){}", "render(){}", "render() {\n // Subclasses should override\n }", "static rendered () {}", "static rendered () {}", "render() {\n\n }", "render(){\r\n\r\n\t}", "render() {\n }", "render() {\n\n }", "render() {\n\n }", "render() {\n\n }", "render( ) {\n return null;\n }", "render() {\n }", "render() {\n }", "render() {\n\t\tthis.a1.render(this.context);\n\t\tthis.b1.render(this.context);\n\t\tthis.c1.render(this.context);\n\t\tthis.c2.render(this.context);\n\t\tthis.d1.render(this.context);\n\t\tthis.e1.render(this.context);\n\t\tthis.f1.render(this.context);\n\t\tthis.g1.render(this.context);\n\t\tthis.a1s.render(this.context);\n\t\tthis.c1s.render(this.context);\n\t\tthis.d1s.render(this.context);\n\t\tthis.f1s.render(this.context);\n\t\tthis.g1s.render(this.context);\n\n\t}", "render() { return super.render(); }", "render() {\n // background box.\n this.renderBackground();\n this.renderName();\n this.renderTimeLine();\n this.renderWave();\n }", "render() {\n return super.render();\n }", "render() {\n\t\treturn (\n\t\t\tnull\n\t\t)\n\t}", "render() {\n\t\treturn null;\n\t}", "render() {\n return (\n\n\n\n\n\n )\n }", "function TextRenderer(){}// no need for block level renderers", "render() {\n return super.render();\n }", "render() {\n return super.render();\n }", "render() {\n\n return (\n <div>\n {this.renderContent()}\n </div>\n );\n \n }", "_render()\n {\n if (this.isDisabled())\n return;\n\n this._setContentSizeCss();\n this._setDirection();\n const paragraph = html`<p>${this.text}</p>`;\n let anchor = \"\";\n let action = \"\";\n if (this.link && this.linkText)\n anchor = html`<a href=\"${this.link}\" target=\"_blank\">${this.linkText}</a>`;\n if (this.action && this.actionText)\n action = html`${anchor ? \" | \" : \"\"}<a href=\"javascript:void(0)\" @click=${this.action}>${this.actionText}</a>`;\n let heading = \"\";\n if (this.heading)\n heading = html`<h4>${this.heading}</h4>`;\n\n render(html`${heading}${paragraph}<div id=\"links\">${anchor}${action}</div>`, this.tooltipElem);\n }", "onRender()/*: void*/ {\n this.render();\n }", "function render() {\n renderLives();\n renderTimeRemaining();\n }", "function general_render(obj) {\n obj.render();\n }", "render() {\n\t\treturn <div>{this.renderContent()}</div>;\n\t}", "renderHTML() {\n \n }", "render() {\n return this.renderContent();\n }", "function render() {\n renderRegistry();\n renderDirectory();\n renderOverride();\n}", "function render() {\n renderCards();\n renderValue();\n}", "render() {\n return this.renderContent()\n }", "function Render() {\n ClearScreen();\n RenderEnergeticDroplets();\n ResetRenderingConditions();\n}", "function render() {\n\n\t\t\tisRendered = true;\n\n\t\t\trenderSource();\n\n\t\t}", "render(){return html``}", "render()\n {\n return super.render();\n }", "function render() {\n\n // Call the Character instance's renderAt() method, passing along its current\n // left and top position\n _character.renderAt(_character.left, _character.top);\n }", "function render() {\r\n // Dessine une frame\r\n drawFrame();\r\n\r\n // Affiche le niveau\r\n drawLevel();\r\n\r\n //Dessine l'angle de la souris\r\n renderMouseAngle();\r\n\r\n // Dessine le player\r\n drawPlayer();\r\n\r\n }", "render() {\n return \"\";\n }", "function RenderEvent() {}", "render() {\n return super.render();\n }", "render() {\n return super.render();\n }", "render() {\n return super.render();\n }", "render() {\n return super.render();\n }", "render() {\n return null;\n }", "render() {\n return null;\n }", "onRender () {\n\n }", "render() {\n return html ``;\n }", "function render() { \t\n\t// renderMenu(); // dropdown menu to let user switch between years manually\n\trenderDatatext();\n\tif (state.world && state.countries.length > 0) renderMap();\n\trenderKey(); // map legend\n\trenderMapyear();\n\trenderLinechart(\".chart-1\", config.countryGroups.heighincome, \"normal\"); // where to place, what data to use\n\trenderLinechart(\".chart-2\", config.countryGroups.brics, \"normal\");\n\trenderLinechart(\".chart-3\", config.countryGroups.arab, \"large\");\n\trenderLinechart(\".chart-4\", config.countryGroups.mostrising, \"normal\");\n\trenderLinechart(\".chart-5\", config.countryGroups.northamerica, \"normal\");\n\trenderLinechart(\".chart-6\", config.countryGroups.warridden, \"normal\");\n\trenderLinechart(\".chart-7\", config.countryGroups.soviet, \"normal\");\n\trenderLinechart(\".chart-8\", config.countryGroups.mensworld,\"normal\");\n\trenderLinechart(\".chart-9\", state.userselected,\"normal\");\n\trenderUserinput();\n}", "render(){if(this.renderer){this.renderer.call(this.owner,this.content,this.owner,this.model)}}", "function TextRenderer() {} // no need for block level renderers", "function TextRenderer() {} // no need for block level renderers", "Render(){\n throw new Error(\"Render() method must be implemented in child!\");\n }", "function render() {\n\n isRendered = true;\n\n renderSource();\n\n }", "function render() {\n\tclearCanvas();\n\tRenderer.draw();\n\t\n\t\t\n}", "function render() {\n let html = generateHeader();\n\n if (store.error) {\n generateError();\n }\n\n // check if form displayed\n if (store.adding) {\n html += generateBookmarkForm();\n }\n\n html += generateAllBookmarkCards();\n\n $('main').html(html);\n }", "function render(){\n\tvar src = \"\"\n\tfor(i in TodoList.items) src += ItemTemplate(TodoList.items[i]);\n\tel.innerHTML = src;\n}", "render() {\n return '';\n }", "function render() {\n let bigString;\n console.log('render fxn ran')\n if (store.view === 'landing') {\n bigString = generateTitleTemplate(store);\n\n }\n else if (store.view === 'question') {\n bigString = generateQuestionTemplate(store);\n\n }\n else if (store.view === 'feedback') {\n bigString = generateFeedbackTemplate(store)\n\n }\n else if (store.view === 'results') {\n bigString = generateResultsTemplate(store);\n\n }\n $('main').html(bigString);\n\n //attach event listeners\n\n\n}", "render(){\n // use the getCharcters method and the player sprite index to determine which character to draw\n ctx.drawImage(Resources.get(this.getCharacters()[this.sprite]), this.x, this.y);\n }", "render() {\n return <div>{this.toRender()}</div>;\n }", "_render() {\n\t\tif (this.ctx) {\n\t\t\tthis.ctx.fillStyle = this._settings.append_to.css('color');\n\t\t\tthis.ctx.beginPath();\n\t\t\tthis.ctx.arc(this.coordinates.x, this.coordinates.y, this.size, 0, 2 * Math.PI);\n\t\t\tthis.ctx.closePath();\n\t\t\tthis.ctx.fill()\n\t\t} else if (this.$element) {\n\t\t\t// TODO: look into rendering to a canvas\n\t\t\tthis.$element.css({\n\t\t\t\t'top': 0,\n\t\t\t\t'left': 0,\n\t\t\t\t'transform': 'translate(' + (this.coordinates.x - (this.height / 2)) + 'px, ' + (this.coordinates.y - (this.width / 2)) + 'px)',\n\t\t\t\t'width': this.width + 'px',\n\t\t\t\t'height': this.height + 'px'\n\t\t\t});\n\t\t\t\n\t\t}\n\t}", "render() {\n if (this.renderer) {\n this.renderer.call(this.owner, this.content, this.owner, this.model);\n }\n }", "render() {\n this.renderComponents() // dial + outputs, algedonode, brass pads, strips, lights\n this.renderLabels()\n }", "function render() {\n\t\t//Drawing background\n drawBackground();\n\t\t//Drawing player paddles\n\t\tdrawPaddles();\n\t\t//Drawing ball\n\t\tdrawBall();\n\n\t\t//If the game is running\n\t\tif(!started)\n\t\t{\n\t\t\tdrawInfo(); //Drawing information (Move your paddle...)\n\t\t\tdocument.getElementById('lifeActivity').style.opacity = 0;\n\t\t\tdocument.getElementById('universityActivity').style.opacity = 0;\n\t\t\tif(result != \"\")\n\t\t\t{\n\t\t\t\tfor(i = 0; i < universityHidden.length; i++) universityHidden[i] = false;\n\t\t\t\tfor(i = 0; i < lifeHidden.length; i++) lifeHidden[i] = false;\n\t\t\t\tdrawResult(); //Drawing result , who won\n\t\t\t}\n\t\t}\n}", "function render (game){\n\t \t}", "render(){return renderNotImplemented;}", "render() {\r\n return;\r\n }", "function render() {\n if (STORE.view === 'start') {\n renderStartQuiz();\n $('.intro').show();\n $('.quiz').hide();\n $('.result').hide();\n $('.quizStatus').hide();\n } else if (STORE.view === 'quiz') {\n renderQuestionText();\n renderQuizStatusBar();\n $('.intro').hide();\n $('.quiz').show();\n $('.result').hide();\n $('.quizStatus').show();\n } else if (STORE.view === 'questionResult') {\n renderQuestionResult();\n renderQuizStatusBar();\n $('.intro').hide();\n $('.quiz').hide();\n $('.result').show();\n $('.quizStatus').show();\n } else if (STORE.view === 'finalResult') {\n renderFinalResult();\n $('.intro').hide();\n $('.quiz').hide();\n $('.result').show();\n $('.quizStatus').hide();\n }\n }", "render() {\n\t\treturn(\n\t\t\t<div className=\"border red\">\n\t\t\t\t{this.renderContent()}\n\t\t\t</div>\n\t\t);\n\t}", "renderScreenContent(){}", "function render() {\n for (let i = 0; i < storedCreatedObj.length; i++) {\n storedCreatedObj[i].render_for_body();\n }\n storedCreatedObj[0].render_for_head();\n storedCreatedObj[0].render_for_foot();\n}", "renderPage() {}", "function render() {\n // Create board with buttons for each of the spaces\n for (var i = 0; i < board.length; i++) {\n var p = document.createElement(\"p\");\n for (var j = 0; j < board[i].length; j++) {\n p.appendChild(createSpaceButton(board[i][j], i, j));\n }\n boardElm.appendChild(p);\n }\n // Update current player\n gameStatusElm.innerHTML = \"Current player: \" + players[currPlayerIndex];\n}", "render() {\n return (\n <div className=\"border red\">\n {this.renderContent()}\n </div>\n );\n \n }", "render() {\n return renderNotImplemented;\n }", "render() {\n return renderNotImplemented;\n }", "renderPrep() {\n }", "function render() {\n var i;\n // Clear the screen\n ctx.fillStyle = '#fff';\n ctx.fillRect(0, 0, canvas.width, canvas.height);\n\n // Render the blocks\n blocks.forEach(function(block) {\n block.render();\n });\n\n // Render the lives\n for(i = 0; i < allLives.length; i ++) {\n var heart = allLives[i];\n heart.opacity = i >= lives ? 0.4 : 1;\n heart.render();\n }\n\n renderScore();\n renderLevel();\n\n renderCollectibles();\n renderEntities();\n\n if (menu) {\n menu.render();\n }\n\n if (Resources.isGameOver()) {\n renderGameOver();\n }\n }", "function render(){ \n console.log('`render function` ran');\n const createdHtml = generateHtml(STORE); \n $('main').html(createdHtml);\n}", "function render() {\n $insert.html(template(bandObject)); //inserts into template, in {{#each this}} it is THIS\n }", "function _render(){\n\t\tinfo = {\n\t\t\t\tpublishers_array: publishers_array\n\t\t}\n\t\t$element.html(Mustache.render(template, info))\n\t}", "render() { this.screen.render() }", "renderBasedOnType() {\r\n switch (this.type) {\r\n case 'audio':\r\n return this.renderAudioCard();\r\n default:\r\n return this.renderBase();\r\n }\r\n }", "render(map)\n\t{\n\t\tthrow new Error(\"Not implemented\");\n\t}" ]
[ "0.856444", "0.85036945", "0.84957767", "0.832847", "0.8283171", "0.8283171", "0.8283171", "0.80956876", "0.8049319", "0.8049319", "0.8036819", "0.8036819", "0.8010243", "0.778271", "0.778271", "0.77696085", "0.7707004", "0.7707004", "0.7696035", "0.76866335", "0.76533616", "0.75348705", "0.75348705", "0.75348705", "0.7366715", "0.73281056", "0.73281056", "0.7294815", "0.729122", "0.721475", "0.71668476", "0.7153006", "0.71493816", "0.71058965", "0.7088984", "0.7086365", "0.7086365", "0.708432", "0.7077937", "0.70668274", "0.70614463", "0.7060395", "0.7059981", "0.705178", "0.70489985", "0.70293874", "0.6952033", "0.69325775", "0.6923041", "0.6876476", "0.6875373", "0.6871139", "0.68484586", "0.6845047", "0.6819669", "0.6818996", "0.6774239", "0.6774239", "0.6774239", "0.6774239", "0.67725515", "0.67725515", "0.67699337", "0.6766509", "0.6763341", "0.67570657", "0.67212397", "0.67212397", "0.6709337", "0.6702564", "0.67020035", "0.67013794", "0.66905296", "0.66669196", "0.66605973", "0.6644605", "0.6632317", "0.6627858", "0.6625084", "0.66197973", "0.66196865", "0.6614998", "0.6613345", "0.66069853", "0.6594014", "0.65800077", "0.6569803", "0.6569361", "0.6566761", "0.6556023", "0.6545646", "0.65434855", "0.65434855", "0.65421987", "0.654109", "0.653811", "0.6533285", "0.65299165", "0.6520716", "0.6519159", "0.6514443" ]
0.0
-1
fungsi untuk menghapus suffix seperti ku, mu, kah, dsb
function Del_Inflection_Suffixes(kata,selesai){ var kataAsal = kata; if(kata.match(/([km]u|nya|[kl]ah|pun)$/i)){ // Cek Inflection Suffixes var __kata = kata.replace(/([km]u|nya|[kl]ah|pun)$/i,''); selesai(__kata); }else{ selesai(kataAsal); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function Del_Derivation_Suffixes(kata,selesai){\n\tvar kataAsal = kata;\n\tvar sam=kata\n\tif(kata.match(/(i|an)$/i)){ // Cek Suffixes\n\t\n\tvar __kata = sam.replace(/(i|an)$/i,'');\n\t\tcekKamus(__kata,function(bool){\n\t\t\tif(bool){\n\t\t\t\t\n\t\t\t\tselesai(__kata)\t\n\t\t\t}else if(kata.match(/(kan)$/i)){\n\t\t\t__kata=sam.replace(/(kan)$/i,'')\n\t\t\tcekKamus(__kata,function(kan){\n\n\t\t\t\t\tif(kan){\n\t\t\t\t\t\t\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t\t}else{\n\t\t\t\t\t\t\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}else{\n\t\t\t\t\n\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t})\n\t}else{\n\t\t\n\t\t\tselesai(kataAsal)\n\t}\n\t\n}", "function suffix() {\n return containsSuffix() ? name.split('+')[1] : undefined;\n }", "function sc_suffix(s) {\n var i = s.lastIndexOf(\".\");\n return i ? s.substring(i+1,i.length) : s;\n}", "function suffix(num) {\n\ts = num.toString();\n\tnum_end = parseInt(s.slice(s.length-2));\n\n\tif (num_end % 10 === 1 && num_end != 11) {\n\t\treturn \"st\";\n\t} else if (num_end % 10 === 2 && num_end != 12) {\n\t\treturn \"nd\";\n\t} else if (num_end % 10 === 3 && num_end != 13) {\n\t\treturn \"rd\";\n\t} else {\n\t\treturn \"th\";\n\t}\n}", "cleanSuffix(suffix) {\n if (!suffix) {\n return this;\n }\n this.input = this.input.replace(new RegExp(`[-_]?${suffix}$`, 'i'), '');\n return this;\n }", "function Del_Derivation_Prefix(kata,selesai){\n\tvar kataAsal = kata;\nvar __kata,__kata__=\"\"\n\t/* —— Tentukan Tipe Awalan ————*/\nif(kata.match(/^(di|[ks]e)/)){ // Jika di-,ke-,se-\n __kata = kata.replace(/^(di|[ks]e)/,'');\n \n cekKamus(__kata,function(data){\n\t if(data){\n\t\tselesai(__kata)\n\t }else{\n\t \t\n\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\n\t\t\t\n cekKamus(__kata__,function(data){\n\t if(data){\n\t\t selesai(__kata__)\n\t }else if(kata.match(/^(diper)/)){ //diper-\n\t\t\n\t\t\t__kata = kata.replace(/^(diper)/,'');\n\t\t\t Del_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\tselesai(__kata__)\t\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t \t\n\t\t\t });\n\t\t\n\t\t\t\n\t\t\t\n\t\t}else if(kata.match(/^(ke[bt]er)/)){ //keber- dan keter-\n\t\t __kata = kata.replace(/^(ke[bt]er)/,'');\n\t\t\t Del_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\t\n\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t});\n\t\t\n\t\t\t\n\t\t\t\n\t\t} else{\n\t\t\tselesai(kata.replace(/^(di|[ks]e)/,''))\n\t\t}\n })\n }) \t\n\t }\n })\t\t\n\t\t\n\t}else if(kata.match(/^([bt]e)/)){ //Jika awalannya adalah \"te-\",\"ter-\", \"be-\",\"ber-\"\n\t\t\n\t\t __kata = kata.replace(/^([bt]e)/,'');\n\t\t\n\t\tcekKamus(__kata,function(data){\n\t\t\tif(data){\n\t\t\t\tselesai(__kata)\n\t\t\t}else{\n\t\t__kata = kata.replace(/^([bt]e[lr])/,'');\t\n\t\t\n\t\tcekKamus(__kata,function(data){\n\t\t\tif(data){\n\t\t\t\tselesai(__kata)\n\t\t\t}else{\n\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\n\t\tcekKamus(__kata__,function(data){\n\t\t\tif(data){\n\t\t\t\tselesai(__kata__)\n\t\t\t}else{\n\t\t\t\tselesai(kataAsal)\n\t\t\t}\n\t\t})\n\t\t})}\t\n\t\t\t\n\t\t})}\n\t\t});\n\t\t\n\t\t}else if(kata.match(/^([mp]e)/)){\n\t\t__kata = kata.replace(/^([mp]e)/,'');\n\t\t\n\t\tcekKamus(__kata,function(data){\n\t\t\tif(data){\n\t\t\tselesai(__kata)\n\t\t\t}else\n\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\n\t\tcekKamus(__kata__,function(data){\n\t\tif(data){\n\t\t\tselesai(__kata__)\n\t\t}else if(kata.match(/^(memper)/)){\n\t\t\t__kata = kata.replace(/^(memper)/,'');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\n\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t\n\t\t})}\n\t\t\t})\n\t\t\n\t\t\t\n\t\t\t\n\t\t}else if(kata.match(/^([mp]eng)/)){\n\t\t\t__kata = kata.replace(/^([mp]eng)/,'');\n\t\tcekKamus(__kata,function(data1){\n\t\t\tif(data1){\n\t\t\t\tselesai(__kata)\n\t\t\t}else{\n\t\t\tDel_Derivation_Suffixes(__kata,function(data2){\n\t\t\t__kata__=data2\n\t\t\tcekKamus(__kata__,function(data3){\n\t\t\t\tif(data3){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t__kata = kata.replace(/^([mp]eng)/,'k');\n\t\t\tcekKamus(__kata,function(data4){\n\t\t\t\tif(data4){\n\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data5){\n\t\t\t__kata__ =data5\n\t\t\tcekKamus(__kata__,function(data6){\n\t\t\t\tif(data6){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\t__kata = kata.replace(/^([mp]enge)/,'');//menge- dan penge-\n\t\t\tcekKamus(__kata,function(data4){\n\t\t\t\tif(data4){\n\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data5){\n\t\t\t__kata__ =data5\n\t\t\tcekKamus(__kata__,function(data6){\n\t\t\t\tif(data6){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t \t\n\t\t\t });\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t})\n\t\t\t\t}\n\t\t\t})\n\t\t\t \t\n\t\t\t });\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t})\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t})\n\t\t\t \t\n\t\t\t });}\n\t\t})\n\t\t\t \n\t\t}else if(kata.match(/^([mp]eny)/)){\n\t\t\t__kata = kata.replace(/^([mp]eny)/,'s');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ =data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\tif(data){\n\t\t\t\tselesai(__kata__)\n\t\t\t}else{\n\t\t\t\tselesai(kataAsal)\n\t\t\t}\n\t\t})\n\t\t\t});}\n\t\t\t})\n\t\t\t\n\t\t\t \n\t\t\n\t\t\t\n\t\t}else if(kata.match(/^([mp]e[lr])/)){\n\t\t\t__kata = kata.replace(/^([mp]e[lr])/,'');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ =data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\tif(data){\n\t\t\t\tselesai(__kata__)\n\t\t\t}else{\n\t\t\t\tselesai(kataAsal)\n\t\t\t}\n\t\t\t})\n\t\t\t \t\n\t\t\t })}\n\t\t\t})\n\t\t\t\n\t\t}else if(kata.match(/^([mp]en)/)){\n\t\t\t__kata = kata.replace(/^([mp]en)/,'t');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ =data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\tselesai(__kata__)\t\n\t\t\t\t}else{\n\t\t\t\t__kata = kata.replace(/^([mp]en)/,'');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\tselesai(__kata)\n\t\t\t\t}else {\n\t\t\t\t\t\n\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ = data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t\t\n\t\t\t});}\n\t\t\t})}\n\t\t\t})\n\t\t\t \t\n\t\t\t });}\n\t\t\t\t\n\t\t\t})\n\t\t\t\n\t\t\n\t\t\t\n\t\t}else if(kata.match(/^([mp]em)/)){\n\t\t\t__kata = kata.replace(/^([mp]em)/,'');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ = data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t__kata = kata.replace(/^([mp]em)/,'p');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ = data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t});}\n\t\t\t})}\n\t\t\t})\n\t\t\t});}\n\t\t\t})\n\t\t\t}\t\n\t\t\n\t\t})\n\t\t \t\n\t\t });\n\t\t})\n\t\t\n\t\t \n\t}else{\n\tselesai(kataAsal)\n\t}\n}", "addSuffix(suffix) {\n if (!suffix) {\n return this;\n }\n this.input = `${this.input}_${suffix}`;\n return this;\n }", "function get_suffix(surffix, charIdx) {\n var arr = surffix.split(\"\");\n arr.splice(charIdx, 1);\n var newSurffix = arr.join(\"\");\n return newSurffix;\n}", "step1b (word, suffixes) {\n let result = word\n\n const match = endsinArr(result, suffixes)\n if (match !== '') {\n const pos = result.length - match.length\n if (pos >= this.r1) {\n // check the character before the matched en/ene AND check for gem\n if (!isVowel(result[pos - 1]) && result.substr(pos - 3, 3) !== 'gem') {\n // delete\n result = removeSuffix(result, match.length)\n // Undouble the ending\n result = undoubleEnding(result)\n }\n }\n }\n if (DEBUG) {\n console.log('step 1b: ' + result)\n }\n return result\n }", "function normalizeSuffix(value, suffix) {\n if (value == null\n /** || value === undefined */\n ) {// do nothing\n } else if (typeof suffix === 'string') {\n value = value + suffix;\n } else if (typeof value === 'object') {\n value = stringify(unwrapSafeValue(value));\n }\n\n return value;\n }", "function testSuffixes (tree, str, t) {\n str += '$0'\n const suffixes = STree.allSuffixes(tree).sort(sortSuffixes)\n t.strictEqual(suffixes.length, str.length - 1)\n suffixes.forEach(function (suff, idx) {\n let correct = str.slice(str.length - idx - 2)\n t.strictEqual(suff, correct, suff + ' vs ' + correct + ' (result vs expected)')\n })\n}", "function sc_prefix(s) {\n var i = s.lastIndexOf(\".\");\n return i ? s.substring(0, i) : s;\n}", "function normalizeSuffix(value, suffix) {\n if (value == null\n /** || value === undefined */\n ) {// do nothing\n } else if (typeof suffix === 'string') {\n value = value + suffix;\n } else if (typeof value === 'object') {\n value = stringify(unwrapSafeValue(value));\n }\n\n return value;\n}", "get suffix() {\n return this._suffix !== undefined ? this._suffix : this._span.suffix;\n }", "function endBeforeStringSuffix(value, suffix) {\n var ends = value.length - suffix.length;\n if (ends <= 0) {\n return;\n }\n if (value.substr(ends) !== suffix) {\n return;\n }\n return ends;\n}", "function getNewBandNames(suffix, bands) {\n //var seq = ee.List.sequence(1, bands.length());\n //return seq.map(function(b) {\n return bands.map(function(band){\n return ee.String(band).cat(suffix);\n });\n // return ee.String(prefix).cat(ee.Number(b).int());\n //});\n}", "function numberSuffix (a){\n\n var array1 = [];\n var array2 = [];\n var array3 = [];\n result = \"\";\n\n for (var i = 20; i <= 100000000; i+=10){\n array1[array1.length] = i + 1; \n }\n\n for (var i = 20; i <= 100000000; i+=10){\n array2[array2.length] = i + 2; \n }\n\n for (var i = 20; i <= 100000000; i+=10){\n array3[array3.length] = i + 3; \n }\n\n if(array1.includes(a)){\n result = a + \"st\";\n \n } else if (array2.includes(a)){\n result = a + \"nd\";\n } else if (array3.includes(a)){\n result = a + \"rd\";\n } else if(a === 1){\n result = a + \"st\";\n } else if(a === 2){\n result = a + \"nd\";\n } else if(a === 3){\n result = a + \"rd\";\n } else if(a > 3){\n result = a + \"th\";\n }\n\n return result;\n}", "function suffix(str, suffixWord) {\n return str ? str + ' ' + suffixWord : '';\n}", "function suffixLabels(arr, suffix) {\n var new_arr = [];\n for (var i = 0; i < arr.length; i++) {\n new_arr[i] = arr[i] + suffix;\n }\n //object = new_obj;\n return new_arr;\n}", "function suffix(stream, c){\n var y=stream.string.length;\n var x=y-stream.pos+1;\n return stream.string.substr(stream.pos,(c&&c<y?c:x));\n}", "function suffix(name) {\n if(_.has(repeatCounter, name)) {\n repeatCounter[name] += 1;\n return \"-\" + repeatCounter[name].toString();\n }\n\n repeatCounter[name] = 1; \n return \"\";\n }", "function commonSuffix(arr) {\n if (arr.length === 0){return\"\";}\n if (arr.length === 1){return arr[0];}\n// find common suffix of the first 2 words and save it in a variable. Use an array variable instead of a string for the ease of cutting this variable later on.\n let currReversedSuffixArr = [];\n let len1 = arr[1].length;\n let len0 = arr[0].length;\n // console.log(\"arr[1].length: \", arr[1].length);\n\n for (let i = len0-1, j = len1-1; i>=0, j>=0; i--, j--){\n if (arr[1][j] === arr[0][i]){\n // console.log(\"i: \", i,\"j: \", j, currReversedSuffixArr);\n currReversedSuffixArr.push(arr[1][j]);\n }\n else if (arr[1][j] !== arr[0][i]){\n break;\n }\n }\n // console.log(\"line 26: \", currReversedSuffixArr);\n\n // iterate through the rest of the array, compare the array value with the saved suffix\n for (let i = 2; i<arr.length; i++) {\n let prevReversedSuffixArr = currReversedSuffixArr;\n let len = arr[i].length;\n let sLen = prevReversedSuffixArr.length;\n currReversedSuffixArr = [];\n for (let j = len-1, k=0; j>=0, k<sLen; j--, k++) {\n if (arr[i][j] === prevReversedSuffixArr[k]){\n currReversedSuffixArr.push(arr[i][j]);\n }\n else if (arr[i][j] !== prevReversedSuffixArr[k]){\n break;\n }\n }\n // console.log(\"line 39: \",prevReversedSuffixArr);\n }\n // iterate thru the reversed suffix array from back to front and make a string from it\n sLen = currReversedSuffixArr.length;\n let suffix = \"\";\n for (let i=sLen-1; i>=0; i--) {\n suffix += currReversedSuffixArr[i];\n }\n return suffix;\n}", "function endsin (str, suffix) {\n if (str.length < suffix.length) return false\n return (str.slice(-suffix.length) === suffix)\n}", "function translate$3(number,withoutSuffix,key){var result=number + ' ';switch(key){case 'ss':if(number === 1){result += 'sekunda';}else if(number === 2 || number === 3 || number === 4){result += 'sekunde';}else {result += 'sekundi';}return result;case 'm':return withoutSuffix?'jedna minuta':'jedne minute';case 'mm':if(number === 1){result += 'minuta';}else if(number === 2 || number === 3 || number === 4){result += 'minute';}else {result += 'minuta';}return result;case 'h':return withoutSuffix?'jedan sat':'jednog sata';case 'hh':if(number === 1){result += 'sat';}else if(number === 2 || number === 3 || number === 4){result += 'sata';}else {result += 'sati';}return result;case 'dd':if(number === 1){result += 'dan';}else {result += 'dana';}return result;case 'MM':if(number === 1){result += 'mjesec';}else if(number === 2 || number === 3 || number === 4){result += 'mjeseca';}else {result += 'mjeseci';}return result;case 'yy':if(number === 1){result += 'godina';}else if(number === 2 || number === 3 || number === 4){result += 'godine';}else {result += 'godina';}return result;}}", "function sortSuffixes (a, b) {\n if (a.length < b.length) {\n return -1\n } else if (a.length > b.length) {\n return 1\n } else {\n return 0\n }\n}", "function normalizeSuffix(value, suffix) {\n if (value == null /** || value === undefined */) {\n // do nothing\n }\n else if (typeof suffix === 'string') {\n value = value + suffix;\n }\n else if (typeof value === 'object') {\n value = stringify(unwrapSafeValue(value));\n }\n return value;\n}", "function normalizeSuffix(value, suffix) {\n if (value == null /** || value === undefined */) {\n // do nothing\n }\n else if (typeof suffix === 'string') {\n value = value + suffix;\n }\n else if (typeof value === 'object') {\n value = stringify(unwrapSafeValue(value));\n }\n return value;\n}", "function normalizeSuffix(value, suffix) {\n if (value == null /** || value === undefined */) {\n // do nothing\n }\n else if (typeof suffix === 'string') {\n value = value + suffix;\n }\n else if (typeof value === 'object') {\n value = stringify(unwrapSafeValue(value));\n }\n return value;\n}", "function normalizeSuffix(value, suffix) {\n if (value == null /** || value === undefined */) {\n // do nothing\n }\n else if (typeof suffix === 'string') {\n value = value + suffix;\n }\n else if (typeof value === 'object') {\n value = stringify(unwrapSafeValue(value));\n }\n return value;\n}", "function normalizeSuffix(value, suffix) {\n if (value == null /** || value === undefined */) {\n // do nothing\n }\n else if (typeof suffix === 'string') {\n value = value + suffix;\n }\n else if (typeof value === 'object') {\n value = stringify(unwrapSafeValue(value));\n }\n return value;\n}", "function normalizeSuffix(value, suffix) {\n if (value == null /** || value === undefined */) {\n // do nothing\n }\n else if (typeof suffix === 'string') {\n value = value + suffix;\n }\n else if (typeof value === 'object') {\n value = stringify(unwrapSafeValue(value));\n }\n return value;\n}", "withoutPrefix(prefix) {\n if (this.formatParts.length < prefix.formatParts.length || this.args.length < prefix.args.length) {\n return undefined;\n }\n let prefixArgCount = 0;\n let firstFormatPart;\n // Walk through the formatParts of prefix to confirm that it's a of this.\n for (let index = 0; index < prefix.formatParts.length; index++) {\n const theirPart = prefix.formatParts[index] || '';\n const ourPart = this.formatParts[index] || '';\n if (ourPart !== theirPart) {\n // We've found a format part that doesn't match. If this is the very last format part check\n // for a string prefix match. If that doesn't match, we're done.\n if (index === prefix.formatParts.length - 1 && ourPart.startsWith(theirPart)) {\n firstFormatPart = ourPart.substring(theirPart.length);\n }\n else {\n return undefined;\n }\n }\n // If the matching format part has an argument, check that too.\n if (theirPart.startsWith('%') && !isNoArgPlaceholder(theirPart[1])) {\n if (this.args[prefixArgCount] !== prefix.args[prefixArgCount]) {\n return undefined; // Argument doesn't match.\n }\n prefixArgCount++;\n }\n }\n // We found a prefix. Prepare the suffix as a result.\n const resultFormatParts = [];\n if (firstFormatPart) {\n resultFormatParts.push(firstFormatPart);\n }\n for (let i = prefix.formatParts.length; i < this.formatParts.length; i++) {\n resultFormatParts.push(this.formatParts[i] || '');\n }\n const resultArgs = [];\n for (let i = prefix.args.length; i < this.args.length; i++) {\n resultArgs.push(this.args[i] || '');\n }\n return this.copy({\n formatParts: resultFormatParts,\n args: resultArgs,\n });\n }", "function eatSuffix(stream, c){\n var x=stream.pos+c;\n var y;\n if(x<=0)\n stream.pos=0;\n else if(x>=(y=stream.string.length-1))\n stream.pos=y;\n else\n stream.pos=x;\n}", "function Cek_Prefix_Disallowed_Sufixes(kata){\n\n\tif(kata.match(/^(be)[a-zA-Z]+(i)/)){ // be- dan -i\n\t\treturn true;\n\t}\n\n\tif(kata.match(/^(se)[a-zA-Z]+(i|kan)/)){ // se- dan -i,-kan\n\t\treturn true;\n\t}\n\t\n\tif(kata.match(/^(di)[a-zA-Z]+(an)/)){ // di- dan -an\n\t\treturn true;\n\t}\n\t\n\tif(kata.match(/^(me)[a-zA-Z]+(an)/)){ // me- dan -an\n\t\treturn true;\n\t}\n\t\n\tif(kata.match(/^(ke)[a-zA-Z]+(i|kan)/)){ // ke- dan -i,-kan\n\t\treturn true;\n\t}\n\treturn false;\n}", "function translate(number,withoutSuffix,key){var result=number + ' ';switch(key){case 'ss':if(number === 1){result += 'sekunda';}else if(number === 2 || number === 3 || number === 4){result += 'sekunde';}else {result += 'sekundi';}return result;case 'm':return withoutSuffix?'jedna minuta':'jedne minute';case 'mm':if(number === 1){result += 'minuta';}else if(number === 2 || number === 3 || number === 4){result += 'minute';}else {result += 'minuta';}return result;case 'h':return withoutSuffix?'jedan sat':'jednog sata';case 'hh':if(number === 1){result += 'sat';}else if(number === 2 || number === 3 || number === 4){result += 'sata';}else {result += 'sati';}return result;case 'dd':if(number === 1){result += 'dan';}else {result += 'dana';}return result;case 'MM':if(number === 1){result += 'mjesec';}else if(number === 2 || number === 3 || number === 4){result += 'mjeseca';}else {result += 'mjeseci';}return result;case 'yy':if(number === 1){result += 'godina';}else if(number === 2 || number === 3 || number === 4){result += 'godine';}else {result += 'godina';}return result;}}", "function translate(number,withoutSuffix,key){var result=number+\" \";switch(key){case\"ss\":return result+=1===number?\"sekunda\":2===number||3===number||4===number?\"sekunde\":\"sekundi\";case\"m\":return withoutSuffix?\"jedna minuta\":\"jedne minute\";case\"mm\":return result+=1===number?\"minuta\":2===number||3===number||4===number?\"minute\":\"minuta\";case\"h\":return withoutSuffix?\"jedan sat\":\"jednog sata\";case\"hh\":return result+=1===number?\"sat\":2===number||3===number||4===number?\"sata\":\"sati\";case\"dd\":return result+=1===number?\"dan\":\"dana\";case\"MM\":return result+=1===number?\"mjesec\":2===number||3===number||4===number?\"mjeseca\":\"mjeseci\";case\"yy\":return result+=1===number?\"godina\":2===number||3===number||4===number?\"godine\":\"godina\"}}", "function translate(number,withoutSuffix,key){var result=number+\" \";switch(key){case\"ss\":return result+=1===number?\"sekunda\":2===number||3===number||4===number?\"sekunde\":\"sekundi\";case\"m\":return withoutSuffix?\"jedna minuta\":\"jedne minute\";case\"mm\":return result+=1===number?\"minuta\":2===number||3===number||4===number?\"minute\":\"minuta\";case\"h\":return withoutSuffix?\"jedan sat\":\"jednog sata\";case\"hh\":return result+=1===number?\"sat\":2===number||3===number||4===number?\"sata\":\"sati\";case\"dd\":return result+=1===number?\"dan\":\"dana\";case\"MM\":return result+=1===number?\"mjesec\":2===number||3===number||4===number?\"mjeseca\":\"mjeseci\";case\"yy\":return result+=1===number?\"godina\":2===number||3===number||4===number?\"godine\":\"godina\"}}", "bindSuffix(fieldnode) {\n fieldnode.addEventListener('field-value-changed', () => {\n this.suffix = fieldnode._value;\n this._setDocumentTitle();\n });\n }", "function translate$7(number,withoutSuffix,key,isFuture){switch(key){case 's':return withoutSuffix?'хэдхэн секунд':'хэдхэн секундын';case 'ss':return number + (withoutSuffix?' секунд':' секундын');case 'm':case 'mm':return number + (withoutSuffix?' минут':' минутын');case 'h':case 'hh':return number + (withoutSuffix?' цаг':' цагийн');case 'd':case 'dd':return number + (withoutSuffix?' өдөр':' өдрийн');case 'M':case 'MM':return number + (withoutSuffix?' сар':' сарын');case 'y':case 'yy':return number + (withoutSuffix?' жил':' жилийн');default:return number;}}", "function stripSuffix(suffix) {\n return function(s) {\n var idx = s.length - suffix.length; // value may be negative\n return s.slice (idx) === suffix ? Just (s.slice (0, idx)) : Nothing;\n };\n }", "function sc_isStringSuffix(cs1, cs2) {\n var tmp = cs2.lastIndexOf(cs1);\n return tmp !== false && tmp >= 0 && tmp === cs2.length - cs1.length;\n}", "function suffix(int) {\n return int % 10 == 1 && int != 11 ? int + \"st\" : int % 10 == 2 && int != 12 ? int + \"nd\" : int % 10 == 3 && int != 13 ? int + \"rd\" : int + \"th\";\n}", "function abbreviationQuickFix(source, post, post2)\n {\n addConversion(source, \"kilo\" + post, \"k\" + post2, 1);\n addConversion(source, \"centi\" + post, \"c\" + post2, 1);\n addConversion(source, \"milli\" + post, \"m\" + post2, 1);\n addConversion(source, \"nano\" + post, \"n\" + post2, 1);\n addConversion(source, \"micro\" + post, \"u\" + post2, 1);\n addConversion(source, \"pico\" + post, \"p\" + post2, 1);\n addConversion(source, \"femto\" + post, \"f\" + post2, 1);\n }", "function translate$3(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function endsinArr (str, suffixes) {\n let i\n let longest = ''\n for (i = 0; i < suffixes.length; i++) {\n if (endsin(str, suffixes[i]) && suffixes[i].length > longest.length) { longest = suffixes[i] }\n }\n\n if (DEBUG && longest !== '') {\n console.log('Matched suffix: ' + longest)\n }\n return longest\n}", "function translate$3(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function addSuffix(v) {\n return v = v + ' hello';\n}", "function translate(number, withoutSuffix, key) {\n\t var result = number + ' ';\n\t switch (key) {\n\t case 'ss':\n\t if (number === 1) {\n\t result += 'sekunda';\n\t } else if (number === 2 || number === 3 || number === 4) {\n\t result += 'sekunde';\n\t } else {\n\t result += 'sekundi';\n\t }\n\t return result;\n\t case 'm':\n\t return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n\t case 'mm':\n\t if (number === 1) {\n\t result += 'minuta';\n\t } else if (number === 2 || number === 3 || number === 4) {\n\t result += 'minute';\n\t } else {\n\t result += 'minuta';\n\t }\n\t return result;\n\t case 'h':\n\t return withoutSuffix ? 'jedan sat' : 'jednog sata';\n\t case 'hh':\n\t if (number === 1) {\n\t result += 'sat';\n\t } else if (number === 2 || number === 3 || number === 4) {\n\t result += 'sata';\n\t } else {\n\t result += 'sati';\n\t }\n\t return result;\n\t case 'dd':\n\t if (number === 1) {\n\t result += 'dan';\n\t } else {\n\t result += 'dana';\n\t }\n\t return result;\n\t case 'MM':\n\t if (number === 1) {\n\t result += 'mjesec';\n\t } else if (number === 2 || number === 3 || number === 4) {\n\t result += 'mjeseca';\n\t } else {\n\t result += 'mjeseci';\n\t }\n\t return result;\n\t case 'yy':\n\t if (number === 1) {\n\t result += 'godina';\n\t } else if (number === 2 || number === 3 || number === 4) {\n\t result += 'godine';\n\t } else {\n\t result += 'godina';\n\t }\n\t return result;\n\t }\n\t }", "function translate(number, withoutSuffix, key) {\n\t var result = number + ' ';\n\t switch (key) {\n\t case 'ss':\n\t if (number === 1) {\n\t result += 'sekunda';\n\t } else if (number === 2 || number === 3 || number === 4) {\n\t result += 'sekunde';\n\t } else {\n\t result += 'sekundi';\n\t }\n\t return result;\n\t case 'm':\n\t return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n\t case 'mm':\n\t if (number === 1) {\n\t result += 'minuta';\n\t } else if (number === 2 || number === 3 || number === 4) {\n\t result += 'minute';\n\t } else {\n\t result += 'minuta';\n\t }\n\t return result;\n\t case 'h':\n\t return withoutSuffix ? 'jedan sat' : 'jednog sata';\n\t case 'hh':\n\t if (number === 1) {\n\t result += 'sat';\n\t } else if (number === 2 || number === 3 || number === 4) {\n\t result += 'sata';\n\t } else {\n\t result += 'sati';\n\t }\n\t return result;\n\t case 'dd':\n\t if (number === 1) {\n\t result += 'dan';\n\t } else {\n\t result += 'dana';\n\t }\n\t return result;\n\t case 'MM':\n\t if (number === 1) {\n\t result += 'mjesec';\n\t } else if (number === 2 || number === 3 || number === 4) {\n\t result += 'mjeseca';\n\t } else {\n\t result += 'mjeseci';\n\t }\n\t return result;\n\t case 'yy':\n\t if (number === 1) {\n\t result += 'godina';\n\t } else if (number === 2 || number === 3 || number === 4) {\n\t result += 'godine';\n\t } else {\n\t result += 'godina';\n\t }\n\t return result;\n\t }\n\t }", "function scaleSuffix(scale) {\n return scale === 1 ? '' : '.x' + String(scale);\n }", "constructor(){\n // length three prefixes\n this.p3 = [\n \"\\u0643\\u0627\\u0644\",\n \"\\u0628\\u0627\\u0644\",\n \"\\u0648\\u0644\\u0644\",\n \"\\u0648\\u0627\\u0644\",\n ]\n\n // length two prefixes\n this.p2 = [\"\\u0627\\u0644\", \"\\u0644\\u0644\"];\n\n // length one prefixes\n this.p1 = [\n \"\\u0644\",\n \"\\u0628\",\n \"\\u0641\",\n \"\\u0633\",\n \"\\u0648\",\n \"\\u064a\",\n \"\\u062a\",\n \"\\u0646\",\n \"\\u0627\",\n ];\n\n // length three suffixes\n this.s3 = [\n \"\\u062a\\u0645\\u0644\",\n \"\\u0647\\u0645\\u0644\",\n \"\\u062a\\u0627\\u0646\",\n \"\\u062a\\u064a\\u0646\",\n \"\\u0643\\u0645\\u0644\",\n ];\n\n // length two suffixes\n this.s2 = [\n \"\\u0648\\u0646\",\n \"\\u0627\\u062a\",\n \"\\u0627\\u0646\",\n \"\\u064a\\u0646\",\n \"\\u062a\\u0646\",\n \"\\u0643\\u0645\",\n \"\\u0647\\u0646\",\n \"\\u0646\\u0627\",\n \"\\u064a\\u0627\",\n \"\\u0647\\u0627\",\n \"\\u062a\\u0645\",\n \"\\u0643\\u0646\",\n \"\\u0646\\u064a\",\n \"\\u0648\\u0627\",\n \"\\u0645\\u0627\",\n \"\\u0647\\u0645\",\n ];\n\n // length one suffixes\n this.s1 = [\"\\u0629\", \"\\u0647\", \"\\u064a\", \"\\u0643\", \"\\u062a\", \"\\u0627\", \"\\u0646\"];\n\n // groups of length four patterns\n this.pr4 = {\n 0: [\"\\u0645\"],\n 1: [\"\\u0627\"],\n 2: [\"\\u0627\", \"\\u0648\", \"\\u064A\"],\n 3: [\"\\u0629\"],\n };\n\n // Groups of length five patterns and length three roots\n this.pr53 = {\n 0: [\"\\u0627\", \"\\u062a\"],\n 1: [\"\\u0627\", \"\\u064a\", \"\\u0648\"],\n 2: [\"\\u0627\", \"\\u062a\", \"\\u0645\"],\n 3: [\"\\u0645\", \"\\u064a\", \"\\u062a\"],\n 4: [\"\\u0645\", \"\\u062a\"],\n 5: [\"\\u0627\", \"\\u0648\"],\n 6: [\"\\u0627\", \"\\u0645\"],\n };\n\n this.re_short_vowels = new RegExp(\"[\\u064B-\\u0652]\");\n this.re_hamza = new RegExp(\"[\\u0621\\u0624\\u0626]\");\n this.re_initial_hamza = new RegExp(\"^[\\u0622\\u0623\\u0625]\");\n\n this.stop_words = [\n \"\\u064a\\u0643\\u0648\\u0646\",\n \"\\u0648\\u0644\\u064a\\u0633\",\n \"\\u0648\\u0643\\u0627\\u0646\",\n \"\\u0643\\u0630\\u0644\\u0643\",\n \"\\u0627\\u0644\\u062a\\u064a\",\n \"\\u0648\\u0628\\u064a\\u0646\",\n \"\\u0639\\u0644\\u064a\\u0647\\u0627\",\n \"\\u0645\\u0633\\u0627\\u0621\",\n \"\\u0627\\u0644\\u0630\\u064a\",\n \"\\u0648\\u0643\\u0627\\u0646\\u062a\",\n \"\\u0648\\u0644\\u0643\\u0646\",\n \"\\u0648\\u0627\\u0644\\u062a\\u064a\",\n \"\\u062a\\u0643\\u0648\\u0646\",\n \"\\u0627\\u0644\\u064a\\u0648\\u0645\",\n \"\\u0627\\u0644\\u0644\\u0630\\u064a\\u0646\",\n \"\\u0639\\u0644\\u064a\\u0647\",\n \"\\u0643\\u0627\\u0646\\u062a\",\n \"\\u0644\\u0630\\u0644\\u0643\",\n \"\\u0623\\u0645\\u0627\\u0645\",\n \"\\u0647\\u0646\\u0627\\u0643\",\n \"\\u0645\\u0646\\u0647\\u0627\",\n \"\\u0645\\u0627\\u0632\\u0627\\u0644\",\n \"\\u0644\\u0627\\u0632\\u0627\\u0644\",\n \"\\u0644\\u0627\\u064a\\u0632\\u0627\\u0644\",\n \"\\u0645\\u0627\\u064a\\u0632\\u0627\\u0644\",\n \"\\u0627\\u0635\\u0628\\u062d\",\n \"\\u0623\\u0635\\u0628\\u062d\",\n \"\\u0623\\u0645\\u0633\\u0649\",\n \"\\u0627\\u0645\\u0633\\u0649\",\n \"\\u0623\\u0636\\u062d\\u0649\",\n \"\\u0627\\u0636\\u062d\\u0649\",\n \"\\u0645\\u0627\\u0628\\u0631\\u062d\",\n \"\\u0645\\u0627\\u0641\\u062a\\u0626\",\n \"\\u0645\\u0627\\u0627\\u0646\\u0641\\u0643\",\n \"\\u0644\\u0627\\u0633\\u064a\\u0645\\u0627\",\n \"\\u0648\\u0644\\u0627\\u064a\\u0632\\u0627\\u0644\",\n \"\\u0627\\u0644\\u062d\\u0627\\u0644\\u064a\",\n \"\\u0627\\u0644\\u064a\\u0647\\u0627\",\n \"\\u0627\\u0644\\u0630\\u064a\\u0646\",\n \"\\u0641\\u0627\\u0646\\u0647\",\n \"\\u0648\\u0627\\u0644\\u0630\\u064a\",\n \"\\u0648\\u0647\\u0630\\u0627\",\n \"\\u0644\\u0647\\u0630\\u0627\",\n \"\\u0641\\u0643\\u0627\\u0646\",\n \"\\u0633\\u062a\\u0643\\u0648\\u0646\",\n \"\\u0627\\u0644\\u064a\\u0647\",\n \"\\u064a\\u0645\\u0643\\u0646\",\n \"\\u0628\\u0647\\u0630\\u0627\",\n \"\\u0627\\u0644\\u0630\\u0649\",\n ];\n }", "function masculineForms(lastChar, inputWord, secondToLastChar) {\n \n if (secondToLastChar === \"c\") {\n newWord = inputWord.slice(0, -2) + \"quito\"; \n dimunutive.innerHTML = newWord;\n } else if (lastChar === \"k\") {\n newWord = inputWord.slice(0, -1) + \"quito\"; \n dimunutive.innerHTML = newWord;\n } else if (secondToLastChar === \"g\") {\n newWord = inputWord.slice(0, -1) + \"uito\"; \n dimunutive.innerHTML = newWord;\n } else if (lastChar === \"z\") {\n newWord = inputWord.slice(0, -1) + \"cecito\"; \n dimunutive.innerHTML = newWord;\n } else if (secondToLastChar === \"u\") {\n newWord = inputWord.slice(0, -2) + \"üito\"; \n dimunutive.innerHTML = newWord;\n } else if (secondToLastChar === \"t\") {\n newWord = \"1: \" + inputWord.slice(0, -1) + \"ito\"; \n dimunutive.innerHTML = newWord;\n \n newWord = \"2: \" + inputWord.slice(0, -1) + \"ico\"; \n specialIco.innerHTML = newWord;\n } else if (lastChar === \"o\") {\n newWord = inputWord.slice(0, -1) + \"ito\"; \n dimunutive.innerHTML = newWord;\n } else if (lastChar === \"l\" || lastChar === \"s\" && secondToLastChar === \"e\") {\n newWord = inputWord + \"ito\";\n dimunutive.innerHTML = newWord;\n } else if (lastChar === \"r\" || lastChar === \"n\" || lastChar === \"e\") {\n newWord = inputWord + \"cito\";\n dimunutive.innerHTML = newWord;\n } else if (lastChar === \"s\") {\n newWord = inputWord.slice(0, -2) + \"itos\"; \n dimunutive.innerHTML = newWord;\n } else {\n newWord = inputWord + \"ito\";\n dimunutive.innerHTML = newWord;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;}\n\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;}\n\n }", "function dateSuffix(day) {\n //set suffix according to date of the month\n if (day % 10 == 1 && day != 11) return 'st';\n else if (day % 10 == 2 && day != 12) return 'nd';\n else if (day % 10 == 3 && day != 13) return 'rd';\n else return 'th';\n}", "function normal_name(d) {\n let inst_name = d.name.replace(/_/g, ' ').split('#')[0];\n if (inst_name.length > params.labels.max_label_char) {\n inst_name = inst_name.substring(0, params.labels.max_label_char) + '..';\n }\n return inst_name;\n }", "function pattern_suffix(identifier) {\n // name shouldn't be the prefix of a longer name\n if ( identifier[identifier.length-1] !== '\"' ) {\n return '\\\\b';\n } else {\n return '';\n }\n }", "function translate(number,withoutSuffix,key,isFuture){switch(key){case\"s\":return withoutSuffix?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return number+(withoutSuffix?\" секунд\":\" секундын\");case\"m\":case\"mm\":return number+(withoutSuffix?\" минут\":\" минутын\");case\"h\":case\"hh\":return number+(withoutSuffix?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return number+(withoutSuffix?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return number+(withoutSuffix?\" сар\":\" сарын\");case\"y\":case\"yy\":return number+(withoutSuffix?\" жил\":\" жилийн\");default:return number}}", "function getDaySuffix(day) {\n var _num = day.toString().split(\"\").pop();\n var _suffix = \"th\";\n\n if (_num === \"1\")\n _suffix = \"st\";\n else if (_num === \"2\")\n _suffix = \"nd\";\n else if (_num === \"3\")\n _suffix = \"rd\";\n \n return _suffix;\n}", "function endBeforeRegExpSuffix(value, suffix) {\n var match = suffix.exec(value);\n if (!match) {\n return;\n }\n var ends = match.index;\n if ((ends + match[0].length) !== value.length) {\n return;\n }\n return ends;\n}", "function commonNumberSuffixes() {\n\t\treturn [\n\t\t\t'th',\t\t// 4th\n\t\t];\n\t}", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function feminineForms(lastChar, inputWord, secondToLastChar) {\n \n if (secondToLastChar === \"c\") {\n newWord = inputWord.slice(0, -2) + \"quita\"; \n dimunutive.innerHTML = newWord;\n } else if (lastChar === \"k\") {\n newWord = inputWord.slice(0, -1) + \"quita\"; \n dimunutive.innerHTML = newWord;\n } else if (secondToLastChar === \"g\") {\n newWord = inputWord.slice(0, -1) + \"uita\"; \n dimunutive.innerHTML = newWord;\n } else if (lastChar === \"z\") {\n newWord = inputWord.slice(0, -1) + \"cecita\"; \n dimunutive.innerHTML = newWord;\n } else if (secondToLastChar === \"u\") {\n newWord = inputWord.slice(0, -2) + \"üita\"; \n dimunutive.innerHTML = newWord;\n } else if (secondToLastChar === \"t\") {\n newWord = \"1: \" + inputWord.slice(0, -1) + \"ita\"; \n dimunutive.innerHTML = newWord;\n \n newWord = \"2: \" + inputWord.slice(0, -1) + \"ica\"; \n specialIco.innerHTML = newWord;\n } else if (lastChar === \"a\") {\n newWord = inputWord.slice(0, -1) + \"ita\"; \n dimunutive.innerHTML = newWord;\n } else if (lastChar === \"l\" || lastChar === \"s\" && secondToLastChar === \"e\") {\n newWord = inputWord + \"ita\";\n dimunutive.innerHTML = newWord;\n } else if (lastChar === \"r\" || lastChar === \"n\" || lastChar === \"e\") {\n newWord = inputWord + \"cita\";\n dimunutive.innerHTML = newWord;\n } else if (lastChar === \"s\") {\n newWord = inputWord.slice(0, -2) + \"itas\"; \n dimunutive.innerHTML = newWord;\n } else {\n newWord = inputWord + \"ita\";\n dimunutive.innerHTML = newWord;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n\n return result;\n\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n\n return result;\n\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n\n return result;\n\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n\n return result;\n\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n\n return result;\n\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n\n return result;\n\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n\n return result;\n\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n\n return result;\n\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n\n return result;\n\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n\n return result;\n\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }", "function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }" ]
[ "0.6774202", "0.63700324", "0.62904674", "0.6241091", "0.6215754", "0.61038715", "0.60492355", "0.6048907", "0.5952882", "0.58750904", "0.58620465", "0.58020526", "0.57999474", "0.5745012", "0.57399106", "0.573591", "0.5735891", "0.567243", "0.5658479", "0.56445414", "0.55860895", "0.55836415", "0.55780566", "0.5577512", "0.5558773", "0.55464137", "0.55464137", "0.55464137", "0.55464137", "0.55464137", "0.55464137", "0.55038965", "0.5478808", "0.54393846", "0.5421642", "0.54101455", "0.54101455", "0.5391492", "0.5388375", "0.5382746", "0.5373457", "0.53717875", "0.53676814", "0.53343135", "0.5325065", "0.531707", "0.53073424", "0.53070325", "0.53070325", "0.5284214", "0.52739036", "0.52610165", "0.5252685", "0.5252685", "0.5248345", "0.5239089", "0.52382064", "0.52301407", "0.52229106", "0.5218546", "0.5217408", "0.5217268", "0.5216333", "0.5193686", "0.5193686", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996", "0.51866996" ]
0.68171924
0
Cek Prefix Disallowed Sufixes (Kombinasi Awalan dan Akhiran yang tidak diizinkan)
function Cek_Prefix_Disallowed_Sufixes(kata){ if(kata.match(/^(be)[a-zA-Z]+(i)/)){ // be- dan -i return true; } if(kata.match(/^(se)[a-zA-Z]+(i|kan)/)){ // se- dan -i,-kan return true; } if(kata.match(/^(di)[a-zA-Z]+(an)/)){ // di- dan -an return true; } if(kata.match(/^(me)[a-zA-Z]+(an)/)){ // me- dan -an return true; } if(kata.match(/^(ke)[a-zA-Z]+(i|kan)/)){ // ke- dan -i,-kan return true; } return false; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "cleanPrefix(prefix) {\n if (!prefix) {\n return this;\n }\n this.input = this.input.replace(new RegExp(`^${prefix}[-_]?`, 'i'), '');\n return this;\n }", "startsWith(c){ return false }", "startsWith(c){ return false }", "getPrefixCode() {\n return \"\";\n }", "function fixNames(rawGlyphs) {\n var countSuffix = /\\-[1-9][0-9]*$/;\n return rawGlyphs.map(function(rawGlyph) {\n var name = rawGlyph.css;\n if (!countSuffix.test(name)) return rawGlyph;\n var noSuffix = name.replace(countSuffix, '');\n var exists = rawGlyphs.some(function(rawGlyph) {\n return rawGlyph.css === noSuffix;\n });\n if (exists) rawGlyph.css = noSuffix;\n return rawGlyph;\n });\n}", "function cleanFunctionName(functionName) {\n var ignoredPrefix = 'non-virtual thunk to ';\n if (functionName.startsWith(ignoredPrefix)) {\n return functionName.substr(ignoredPrefix.length);\n }\n return functionName;\n}", "function removeUnwantedSpecialCharsSepa(value, req)\n{\n if (value != 'undefined' || value != '') {\n value.replace(/^\\s+|\\s+$/g, '');\n if (req != 'undefined' && req == 'account_holder') {\n return value.replace(/[\\/\\\\|\\]\\[|#@,+()`'$~%\":;*?<>!^{}=_]/g, '');\n }else {\n return value.replace(/[\\/\\\\|\\]\\[|#@,+()`'$~%.\":;*?<>!^{}=_-]/g, '');\n }\n }\n}", "function missingLetters() {}", "get inputBlockPattern() {\n return this.props.source === 'domain' ? /[^\\w\\s-.]/gi : /[^\\w\\s-]/gi\n }", "static removePrefix(value) {\n if (value.includes(InitialPrefix) && value.includes(EndPrefix)) {\n return value\n .toString()\n .replace(InitialPrefix, \"\")\n .replace(EndPrefix, \"\");\n }\n return value;\n }", "function Del_Derivation_Prefix(kata,selesai){\n\tvar kataAsal = kata;\nvar __kata,__kata__=\"\"\n\t/* —— Tentukan Tipe Awalan ————*/\nif(kata.match(/^(di|[ks]e)/)){ // Jika di-,ke-,se-\n __kata = kata.replace(/^(di|[ks]e)/,'');\n \n cekKamus(__kata,function(data){\n\t if(data){\n\t\tselesai(__kata)\n\t }else{\n\t \t\n\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\n\t\t\t\n cekKamus(__kata__,function(data){\n\t if(data){\n\t\t selesai(__kata__)\n\t }else if(kata.match(/^(diper)/)){ //diper-\n\t\t\n\t\t\t__kata = kata.replace(/^(diper)/,'');\n\t\t\t Del_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\tselesai(__kata__)\t\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t \t\n\t\t\t });\n\t\t\n\t\t\t\n\t\t\t\n\t\t}else if(kata.match(/^(ke[bt]er)/)){ //keber- dan keter-\n\t\t __kata = kata.replace(/^(ke[bt]er)/,'');\n\t\t\t Del_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\t\n\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t});\n\t\t\n\t\t\t\n\t\t\t\n\t\t} else{\n\t\t\tselesai(kata.replace(/^(di|[ks]e)/,''))\n\t\t}\n })\n }) \t\n\t }\n })\t\t\n\t\t\n\t}else if(kata.match(/^([bt]e)/)){ //Jika awalannya adalah \"te-\",\"ter-\", \"be-\",\"ber-\"\n\t\t\n\t\t __kata = kata.replace(/^([bt]e)/,'');\n\t\t\n\t\tcekKamus(__kata,function(data){\n\t\t\tif(data){\n\t\t\t\tselesai(__kata)\n\t\t\t}else{\n\t\t__kata = kata.replace(/^([bt]e[lr])/,'');\t\n\t\t\n\t\tcekKamus(__kata,function(data){\n\t\t\tif(data){\n\t\t\t\tselesai(__kata)\n\t\t\t}else{\n\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\n\t\tcekKamus(__kata__,function(data){\n\t\t\tif(data){\n\t\t\t\tselesai(__kata__)\n\t\t\t}else{\n\t\t\t\tselesai(kataAsal)\n\t\t\t}\n\t\t})\n\t\t})}\t\n\t\t\t\n\t\t})}\n\t\t});\n\t\t\n\t\t}else if(kata.match(/^([mp]e)/)){\n\t\t__kata = kata.replace(/^([mp]e)/,'');\n\t\t\n\t\tcekKamus(__kata,function(data){\n\t\t\tif(data){\n\t\t\tselesai(__kata)\n\t\t\t}else\n\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\n\t\tcekKamus(__kata__,function(data){\n\t\tif(data){\n\t\t\tselesai(__kata__)\n\t\t}else if(kata.match(/^(memper)/)){\n\t\t\t__kata = kata.replace(/^(memper)/,'');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\n\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t\n\t\t})}\n\t\t\t})\n\t\t\n\t\t\t\n\t\t\t\n\t\t}else if(kata.match(/^([mp]eng)/)){\n\t\t\t__kata = kata.replace(/^([mp]eng)/,'');\n\t\tcekKamus(__kata,function(data1){\n\t\t\tif(data1){\n\t\t\t\tselesai(__kata)\n\t\t\t}else{\n\t\t\tDel_Derivation_Suffixes(__kata,function(data2){\n\t\t\t__kata__=data2\n\t\t\tcekKamus(__kata__,function(data3){\n\t\t\t\tif(data3){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t__kata = kata.replace(/^([mp]eng)/,'k');\n\t\t\tcekKamus(__kata,function(data4){\n\t\t\t\tif(data4){\n\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data5){\n\t\t\t__kata__ =data5\n\t\t\tcekKamus(__kata__,function(data6){\n\t\t\t\tif(data6){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\t__kata = kata.replace(/^([mp]enge)/,'');//menge- dan penge-\n\t\t\tcekKamus(__kata,function(data4){\n\t\t\t\tif(data4){\n\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data5){\n\t\t\t__kata__ =data5\n\t\t\tcekKamus(__kata__,function(data6){\n\t\t\t\tif(data6){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t \t\n\t\t\t });\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t})\n\t\t\t\t}\n\t\t\t})\n\t\t\t \t\n\t\t\t });\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t})\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t})\n\t\t\t \t\n\t\t\t });}\n\t\t})\n\t\t\t \n\t\t}else if(kata.match(/^([mp]eny)/)){\n\t\t\t__kata = kata.replace(/^([mp]eny)/,'s');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ =data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\tif(data){\n\t\t\t\tselesai(__kata__)\n\t\t\t}else{\n\t\t\t\tselesai(kataAsal)\n\t\t\t}\n\t\t})\n\t\t\t});}\n\t\t\t})\n\t\t\t\n\t\t\t \n\t\t\n\t\t\t\n\t\t}else if(kata.match(/^([mp]e[lr])/)){\n\t\t\t__kata = kata.replace(/^([mp]e[lr])/,'');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ =data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\tif(data){\n\t\t\t\tselesai(__kata__)\n\t\t\t}else{\n\t\t\t\tselesai(kataAsal)\n\t\t\t}\n\t\t\t})\n\t\t\t \t\n\t\t\t })}\n\t\t\t})\n\t\t\t\n\t\t}else if(kata.match(/^([mp]en)/)){\n\t\t\t__kata = kata.replace(/^([mp]en)/,'t');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ =data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\tselesai(__kata__)\t\n\t\t\t\t}else{\n\t\t\t\t__kata = kata.replace(/^([mp]en)/,'');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\tselesai(__kata)\n\t\t\t\t}else {\n\t\t\t\t\t\n\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ = data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t\t\n\t\t\t});}\n\t\t\t})}\n\t\t\t})\n\t\t\t \t\n\t\t\t });}\n\t\t\t\t\n\t\t\t})\n\t\t\t\n\t\t\n\t\t\t\n\t\t}else if(kata.match(/^([mp]em)/)){\n\t\t\t__kata = kata.replace(/^([mp]em)/,'');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ = data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t__kata = kata.replace(/^([mp]em)/,'p');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ = data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t});}\n\t\t\t})}\n\t\t\t})\n\t\t\t});}\n\t\t\t})\n\t\t\t}\t\n\t\t\n\t\t})\n\t\t \t\n\t\t });\n\t\t})\n\t\t\n\t\t \n\t}else{\n\tselesai(kataAsal)\n\t}\n}", "function sanitize(myid, prefix) {\n // it is possible for a topic label to not exist\n // replace all non alpha-numeric characters with _\n return (myid) ? prefix + myid.replace( /(\\+|#|-)/g, \"\\\\$1\" ).replace( /\\s/g, \"_\") : \"\";\n}", "function stripNSB (code) {\n return code.replace(nonSpacingRegex, '');\n}", "function prefixIgnored(prefix, stack) {\n for (var i = 0; i < prefix.length; ++i) {\n var match = stack[i].match(stackMatcher);\n if (!match\n || match[1] !== prefix[i].name || match[2] !== prefix[i].module) {\n return false;\n }\n }\n return true;\n }", "function fixStart(str)\n{\n //var firstChar = str.slice(0,1);\n var str1 = str.split(\"\");\n // var re = new RegExp(/(?!^)${firstChar}/,\"g\");\n // var str1 = str.replace(re,'*');\n for (var i = 1; i < str.length; i+=1)\n {\n if (str[i] === str[0])\n {\n str1[i] = '*';\n }\n }\n str1 = str1.join(\"\");\n console.log(str,\" is replaced : \",str1);\n return str1;\n}", "function getBlacklistAscii() {\n\t\tvar blacklist = '!@#$%^&*()+=[]\\\\\\';,/{}|\":<>?~`.-_';\n\t\tblacklist += \" \"; // 'Space' is on the blacklist but can be enabled using the 'allowSpace' config entry\n\t\treturn blacklist;\n\t}", "function blockUnrequired(){\r\n\tset(\"V[z_vaxx_*]\",\"\");\r\n\tset(\"V[z_va01_*]\",\"\");\r\n}", "function strip3(e) {\n\t\tvar Textf=document.getElementById(e);\n\t\tvar repl= /[^0-9a-z.@_]/gi;\n\t\tTextf.value=Textf.value.replace(repl,\"\");\t\n\t\t}", "function fixUrlPrefix(url){\n\tif(url && !url.includes('http:')){\n\t\turl = 'http:'+url;\n\t}\n\treturn url;\n}", "function splitPrefix(name) {\n var prefix, index = name ? name.indexOf('!') : -1;\n if (index > -1) {\n prefix = name.substring(0, index);\n name = name.substring(index + 1, name.length)\n }\n return [\n prefix,\n name\n ]\n }", "function enUsGetPrefixes() {\n var prefixes = [];\n for(var location in enUsCampusPrefix)// https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes\n // istanbul ignore else\n if (enUsCampusPrefix.hasOwnProperty(location)) prefixes.push.apply(prefixes, _toConsumableArray(enUsCampusPrefix[location]));\n return prefixes;\n}", "function splitPrefix(name) {\n var prefix,\n index = name ? name.indexOf('!') : -1;\n if (index > -1) {\n prefix = name.substring(0, index);\n name = name.substring(index + 1, name.length);\n }\n return [prefix, name];\n }", "function splitPrefix(name) {\n var prefix,\n index = name ? name.indexOf('!') : -1;\n if (index > -1) {\n prefix = name.substring(0, index);\n name = name.substring(index + 1, name.length);\n }\n return [prefix, name];\n }", "function updateReserved(value) {\n //replace reserved regex characters\n value = value.replace(/[.]/g, \"[.]\");\n value = value.replace(/([/\\\\])/g, \"[/\\\\\\\\]\");\n\n //convert wildcard to regex\n value = value.replace(/[*]/g, \"[^/\\\\\\\\]*\");\n\n return value;\n }", "function getIgnoreKeywords_onomatopoeia_singleLetter() {\n\t\treturn [\n\t\t\t'a',\n\t\t\t'e',\n\t\t\t'm',\n\t\t\t'o',\n\t\t\t'u',\n\t\t];\n\t}", "function maskify(cc) {\n return cc.replace(/.(?=....)/g, '#');\n }", "function filterize( labelName ) {\n // GMail labels refuse ^ but they accept all other special characters on US keyboard: ~!#$%&*()-_+={}[];'\\,./:\"|<>?|`@\n // When searching for such label, it replaces only some with a dash: label:~!#$%-*---_+=--[];'\\,.-:--<>?-`@\n // Unicode characters (past ASCII) seem to work: ▶✉✦❤➡✖✔✸●■◢◣◤◥◧◨◩◪▲▼▶◀♂♀♪♫☼. Hence allow any unicode (charcode over 255).\n var result= '';\n for( var i=0; i<labelName.length; i++ ) {\n if( labelName.charCodeAt(i) >255 ) {\n result+= labelName[i];\n }\n else {\n result+= labelName[i].replace( /[^a-z0-9~!#$%*\\_+=\\[\\];'\\\\,.:<>\\?`@-]/i, '-' );\n }\n }\n return result;\n}", "function StripPrefixes(ids)\r\n{\r\n\tfor (var i = 0; i < ids.length; i++)\r\n\t{\r\n \tids[i] = StripPrefix(ids[i]);\r\n\t}\r\n}", "function letras(n) {\n\tpermitidos = /[^a-zA-Z]/;\n\tcadena = n.value;\n\tband = false;\n\tfor (i = 0; i < cadena.length; i++) {\n\t\tletra = cadena.substring(i, i + 1);\n\t\tif (permitidos.test(letra)) {\n\t\t\tcadena2 = cadena;\n\t\t\tcadena = cadena2.replace(letra, \"\");\n\t\t\tband = true;\n\t\t}\n\t}\n\tif (band === true) {\n\t\tn.value = cadena;\n\t}\n}", "function MascaraCNPJ(t, mask){\n var i = t.value.length;\n var saida = mask.substring(1,0);\n var texto = mask.substring(i)\n if (texto.substring(0,1) != saida){\n t.value += texto.substring(0,1);\n }\n }", "function removePrefix(str) {\n if(str.charAt(0) === '~') {\n str = str.substring(1);\n }\n return str;\n }", "function notCommande(prefix,message){\n\tif(!message.content.startsWith(prefix)){\n\t\tconsole.log(\"It's not a commande for bot \");\n\t\treturn;\n\t}\n}", "function getIgnoreKeywords_simpleSymbols() {\n\t\treturn [\n\t\t\t'.',\n\t\t\t'!',\n\t\t\t'?',\n\t\t\t'@',\n\t\t\t',',\n\t\t\t':',\n\t\t\t';',\n\t\t\t'#',\n\t\t\t'=',\n\t\t\t'\\'',\n\t\t\t'\"',\n\t\t\t'/',\n\t\t\t'\\\\',\n\t\t\t'&',\n\t\t\t'\\'',\n\t\t\t'*',\n\t\t\t'^',\n\t\t];\n\t}", "parsePrefixString() {\n const matches = this.prefixString.trim().match(this._prefixRegex);\n this.short = matches[1];\n this.long = matches[2].replace(/[<>]/g, \"\");\n this.representations.push(matches[1], matches[2]);\n }", "startsWith(c) { return c=='[' || c=='-' }", "function splitPrefix(name) {\n var prefix,\n index = name ? name.indexOf('!') : -1;\n if (index > -1) {\n prefix = name.substring(0, index);\n name = name.substring(index + 1, name.length);\n }\n return [prefix, name];\n }", "function splitPrefix(name) {\n var prefix,\n index = name ? name.indexOf('!') : -1;\n if (index > -1) {\n prefix = name.substring(0, index);\n name = name.substring(index + 1, name.length);\n }\n return [prefix, name];\n }", "function splitPrefix(name) {\n var prefix,\n index = name ? name.indexOf('!') : -1;\n if (index > -1) {\n prefix = name.substring(0, index);\n name = name.substring(index + 1, name.length);\n }\n return [prefix, name];\n }", "function splitPrefix(name) {\n var prefix,\n index = name ? name.indexOf('!') : -1;\n if (index > -1) {\n prefix = name.substring(0, index);\n name = name.substring(index + 1, name.length);\n }\n return [prefix, name];\n }", "function validateSurnamesInNewTramite( cadena ) {\n var patron = /^[a-zñA-ZÑ\\s]*$/;\n if(cadena.search(patron))\n {\n vm.surnames = cadena.substring(0, cadena.length-1);\n }\n }", "function removeThisIsSA(string: string){\n\n\t\t\t\t\tif (string.includes(' This is SA: ')){\n\t\t\t\t\t\treturn string.replace('This is SA: ', '');\n\t\t\t\t\t}\n\t\t\t\t\tif (string.includes(' This is S.A.:')){\n\t\t\t\t\t\treturn string.replace('This is S.A.: ', '');\n\t\t\t\t\t}\n\n\t\t\t\t\treturn string;\n\t\t\t\t}", "function fixProperNoun(noun) {\n\t// your code goes here\n}", "specialEncode (str) {\n\t\treturn str.replace(/:/g, '***(_colon_)').replace(/\\//g, '***(_slash_)');\n\t}", "function splitPrefix(name) {\n var prefix,\n index = name ? name.indexOf('!') : -1;\n if (index > -1) {\n prefix = name.substring(0, index);\n name = name.substring(index + 1, name.length);\n }\n return [prefix, name];\n }", "stripInvalidFileFolderChars(input, replacer = \"\", onPremise = false) {\r\n if (onPremise) {\r\n return input.replace(UtilityMethod.InvalidFileFolderNameCharsOnPremiseRegex, replacer);\r\n }\r\n else {\r\n return input.replace(UtilityMethod.InvalidFileFolderNameCharsOnlineRegex, replacer);\r\n }\r\n }", "function proverka(input) { \n var value = input.value; \n var rep = /[-\\.;\":'/a-zA-Zа-яА-Я ]/; \n if (rep.test(value)) { \n value = value.replace(rep, ''); \n input.value = value; \n }\n }", "startsWith(c){ return c=='_' || Character.isLetter(c) }", "function checkIfNoIllegalCharacters ( name ) {\n return ( name.indexOf(\".\") === -1 ) &&\n ( name.indexOf(\"/\") === -1 ) &&\n ( name.indexOf(\":\") === -1) &&\n ( name.indexOf(\"*\") === -1 );\n }", "function collectWhitelistPatterns() {\n return [ /popupS-/, /modal-/, /disabled-/ ];\n}", "function splitPrefix(name) {\n var prefix,\n index = name ? name.indexOf('!') : -1;\n if (index > -1) {\n prefix = name.substring(0, index);\n name = name.substring(index + 1, name.length);\n }\n return [prefix,\n name\n ];\n }", "removeStartsWith(prefix) {\n // map api https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\n // for of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\n const keys = this.map.keys();\n /* eslint-disable no-restricted-syntax */\n for (const key of keys) {\n if (_.startsWith(key, prefix)) {\n this.map.delete(key);\n }\n }\n /* eslint-enable no-restricted-syntax */\n }", "function removeForbiddenCharacters(theName) {\n FirstChar=theName.charAt(0);\n if (FirstChar>\"0\" && FirstChar<\"9\") { theName=\"Cam\" + theName };\n theName=theName.replace(/[^a-zA-Z0-9]+/g,\"\"); // remove special characters and spaces\n return(theName);\n}", "function fixbadjs(){\n\ttry{\n\t\tvar uw = typeof unsafeWindow !== \"undefined\"?unsafeWindow:window;\n\t\t// breakbadtoys is injected by jumpbar.js from TheHiveWorks\n\t\t// killbill and bucheck are injected by ks_headbar.js from Keenspot\n\t\tvar badFunctions = [\"breakbadtoys2\", \"killbill\", \"bucheck\"];\n\t\tfor (var i = 0; i < badFunctions.length; i++) {\n\t\t\tvar name = badFunctions[i];\n\t\t\tif (typeof uw[name] !== \"undefined\") {\n\t\t\t\tconsole.log(\"Disabling anti-wcr code\");\n\t\t\t\tuw.removeEventListener(\"load\", uw[name], true);\n\t\t\t\tuw[name] = function() {};\n\t\t\t} else {\n\t\t\t\tObject.defineProperty(uw,name,{get:function(){return function(){}}, configurable: false});\n\t\t\t}\n\t\t}\n\t} catch(e) {\n\t\tconsole.error(\"Failed to disable bad js:\", e);\n\t\t//console.error(e);\n\t}\n}", "function isVisualPrefix( prefix, string ) {\n\t\t// Pre-base vowel signs of Indic languages. A vowel sign is called pre-base if\n\t\t// consonant + vowel becomes [vowel][consonant] when rendered. Eg: ക + െ => കെ\n\t\tvar prebases = 'െേൈൊോൌெேைொோௌେୈୋୌિਿिিেৈোৌෙේෛොෝෞ';\n\t\treturn prebases.indexOf( string[prefix.length] ) <= 0;\n\t}", "function IsBornosoftModifierCharaceter(CUni)\r\n{\r\n\tif(CUni=='হ' || CUni=='`' \r\n\t|| CUni=='~' )\r\n\t\treturn true;\r\n\treturn false;\r\n}", "function regExpPrefix(re) {\n\t var prefix = /^\\^((?:\\\\[^a-zA-Z0-9]|[^\\\\\\[\\]\\^$*+?.()|{}]+)*)/.exec(re.source);\n\t return (prefix != null) ? prefix[1].replace(/\\\\(.)/g, \"$1\") : '';\n\t }", "function regExpPrefix(re) {\n\t var prefix = /^\\^((?:\\\\[^a-zA-Z0-9]|[^\\\\\\[\\]\\^$*+?.()|{}]+)*)/.exec(re.source);\n\t return (prefix != null) ? prefix[1].replace(/\\\\(.)/g, \"$1\") : '';\n\t }", "function _all_string_prefixes() {\n return [\n '', 'FR', 'RF', 'Br', 'BR', 'Fr', 'r', 'B', 'R', 'b', 'bR',\n 'f', 'rb', 'rB', 'F', 'Rf', 'U', 'rF', 'u', 'RB', 'br', 'fR',\n 'fr', 'rf', 'Rb'];\n}", "function buildWildcardClass(prefix) {\n return function (index, css) {\n return (css.match (new RegExp(\"(^|\\\\s)\" + prefix + \"-\\\\S+\", \"g\") ) || []).join(' ');\n }\n}", "function commandPrefix(msg, argument) {\n if (!canManageGuild(msg.member)) return;\n\n if (/[a-zA-Z0-9\\s\\n]/.test(argument)) {\n return msg.channel.sendMessage('Invalid prefix. Can\\'t be a letter, number, or whitespace character.');\n }\n\n writeGuildConfig(msg.guild.id, { prefix: argument });\n\n return msg.channel.sendMessage('\\\\o/');\n}", "defaultDeduplicationTagPattern() {return \" \\\\u200b$\";}", "function usingBadWords(message) {\r\n if (/f[uo]ck|\\bass\\b|assh[o0]le|\\barse|\\bcum\\b|\\bdick|\\bsex\\b|pussy|bitch|porn|\\bfck|nigga|\\bcock\\b|\\bgay|\\bhoe\\b|slut|whore|cunt|clit|pen[i1]s|vag|nigger|8=+d/i.test(message)) {\r\n return true;\r\n }\r\n else return false;\r\n}", "function fixStart(s) {\n var c = s.charAt(0);\n return c + s.slice(1).replace(new RegExp(c, 'g'), '*');\n }", "function regExpPrefix(re) {\n\t\t\tvar prefix = /^\\^((?:\\\\[^a-zA-Z0-9]|[^\\\\\\[\\]\\^$*+?.()|{}]+)*)/.exec(re.source);\n\t\t\treturn (prefix != null) ? prefix[1].replace(/\\\\(.)/g, \"$1\") : '';\n\t\t}", "function checkPrefix(url){\n if(!(/^\\w+:\\/\\//.test(url))){\n return \"http://\" + url;\n } else {\n return url;\n }\n}", "function fixShortcut(name) {\n\t\t\tif(isMac) {\n\t\t\t\tname = name.replace(\"Ctrl\", \"Cmd\");\n\t\t\t} else {\n\t\t\t\tname = name.replace(\"Cmd\", \"Ctrl\");\n\t\t\t}\n\t\t\treturn name;\n\t\t}", "function splitPrefix(name) {\n\t var prefix,\n\t index = name ? name.indexOf('!') : -1;\n\t if (index > -1) {\n\t prefix = name.substring(0, index);\n\t name = name.substring(index + 1, name.length);\n\t }\n\t return [prefix, name];\n\t }", "function splitPrefix(name) {\n\t var prefix,\n\t index = name ? name.indexOf('!') : -1;\n\t if (index > -1) {\n\t prefix = name.substring(0, index);\n\t name = name.substring(index + 1, name.length);\n\t }\n\t return [prefix, name];\n\t }", "function getIgnoreKeywords_dashReplaceSpaces(args) {\n\t\tvar symbols = args.symbols;\n\t\t\n\t\tvar dashreplacedsymbols = [];\n\t\t\n\t\tfor(var i = 0; i < symbols.length; i++) {\n\t\t\tvar symbol = symbols[i];\n\t\t\tvar newsymbol = symbol.replace(/ /g, '-');\n\t\t\t\n\t\t\tif(symbol !== newsymbol) {\n\t\t\t\tdashreplacedsymbols.push(symbol.replace(/ /g, '-'));\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn dashreplacedsymbols;\n\t}", "function setCurrencyPrefixNF(cp)\n{\n\tthis.currencyPrefix = cp;\n}", "function base_css_prefix(ast) {\n return ast.computed === false && ast.object.type == \"Identifier\" && \n ast.object.name == \"Ext\" && ast.property.type == \"Identifier\" && \n ast.property.name == \"baseCSSPrefix\";\n}", "function sc_prefix(s) {\n var i = s.lastIndexOf(\".\");\n return i ? s.substring(0, i) : s;\n}", "get prefix()\n {\n let r = this.config.get('general', 'prefix');\n return r ? r : '!';\n }", "function obfuscate(str) { return str.replace(\"DIESPAMBOTSDIE!!!!\",\"[email protected]\").replace(\"SECONDROUNDHA\", \"ai\") }", "function filterProfanity(txtmsg){\n txtmsg;\n var lowertxtmsg = txtmsg.toLowerCase();\n var profanity = [\"fuck\", \"shit\", \"bitch\", \n \"cunt\", \"fucking\", \"fuckyou\", \"gay\", \"retard\", \"retarted\", \"function\"];\n for(var i=0; i < profanity.length; i++){\n lowertxtmsg = lowertxtmsg.replace(profanity[i], \"####\");\n }\n return lowertxtmsg;\n }", "function prefixer(prefix){\n\tthis.prefix=prefix;\n}", "startsWith(c) { return this.symbol.indexOf(c)<0 }", "startsWith(c) { return this.symbol.indexOf(c)<0 }", "function stripInvalidFileFolderChars(input, replacer, onPremise) {\n if (replacer === void 0) { replacer = \"\"; }\n if (onPremise === void 0) { onPremise = false; }\n if (onPremise) {\n return input.replace(InvalidFileFolderNameCharsOnPremiseRegex, replacer);\n }\n else {\n return input.replace(InvalidFileFolderNameCharsOnlineRegex, replacer);\n }\n}", "strHasPrefix (str, prefix) {\n if (str && prefix && str.indexOf(prefix) === 0) {\n return true;\n }\n\n return false;\n }", "function enUsCheck(tin) {\n return enUsGetPrefixes().indexOf(tin.substr(0, 2)) !== -1;\n}", "function fixShortcut(name) {\n\t\tif(isMac) {\n\t\t\tname = name.replace(\"Ctrl\", \"Cmd\");\n\t\t} else {\n\t\t\tname = name.replace(\"Cmd\", \"Ctrl\");\n\t\t}\n\t\treturn name;\n\t}", "static cleanPhoneNumber(phoneNumberParam, phonePrefix) {\n let phoneNumber = phoneNumberParam;\n if (phoneNumber) {\n phoneNumber = phoneNumber.replace(/\\s/g, '');\n phoneNumber = phoneNumber.replace(/(?:-)(\\d)/g, '$1'); // remove \"-\" char preceding a digit\n phoneNumber = phoneNumber.replace(/(?:\\.)(\\d)/g, '$1'); // remove \".\" char preceding a digit\n phoneNumber = phoneNumber.replace(/(?:\\()(\\d+)(?:\\))/g, '$1'); // remove parenthesis around digits\n\n if (phonePrefix) {\n const alternativePhonePrefix = `00${phonePrefix.replace('+', '')}`;\n if (startsWith(phoneNumber, alternativePhonePrefix)) {\n // check if input value begin with 00${prefix}\n phoneNumber = `+${phonePrefix}${phoneNumber.slice(\n alternativePhonePrefix.length,\n )}`;\n } else if (!startsWith(phoneNumber, `+${phonePrefix}`)) {\n // or not by the phonePrefix\n phoneNumber = `+${phonePrefix}${phoneNumber}`;\n }\n }\n }\n return phoneNumber;\n }", "function getIgnoreKeywords_onomatopoeia_doubleLetter() {\n\t\treturn [\n\t\t\t[\n\t\t\t\t'a',\n\t\t\t\t'h',\n\t\t\t],\n\t\t\t[\n\t\t\t\t'e',\n\t\t\t\t'k',\n\t\t\t],\n\t\t\t[\n\t\t\t\t'e',\n\t\t\t\t'p',\n\t\t\t],\n\t\t\t[\n\t\t\t\t'h',\n\t\t\t\t'm',\n\t\t\t],\n\t\t\t[\n\t\t\t\t'n',\n\t\t\t\t'o',\n\t\t\t],\n\t\t\t[\n\t\t\t\t'o',\n\t\t\t\t'h',\n\t\t\t],\n\t\t\t[\n\t\t\t\t'u',\n\t\t\t\t'h',\n\t\t\t],\n\t\t];\n\t}", "function fixUp(val) {\n return val.replace('·', '*')\n .replace(\"⋅\", '*')\n .replace('\\u2212', '-')\n .replace('\\u0192', 'f')\n .replace('\\xa0', ''); // space\n }", "function enUsCheck(tin) {\n return enUsGetPrefixes().indexOf(tin.substr(0, 2)) !== -1;\n}", "function enUsGetPrefixes() {\n var prefixes = [];\n\n for (var location in enUsCampusPrefix) {\n // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes\n // istanbul ignore else\n if (enUsCampusPrefix.hasOwnProperty(location)) {\n prefixes.push.apply(prefixes, _toConsumableArray(enUsCampusPrefix[location]));\n }\n }\n\n return prefixes;\n}", "function sanitise(name){\n\treturn name.replace(/[^a-zA-Z0-9\\.\\-]/g, '_');\n}", "function splitPrefix(name) {\n var prefix,\n index = name ? name.indexOf('!') : -1;\n if (index > -1) {\n prefix = name.substring(0, index);\n name = name.substring(index + 1, name.length);\n }\n return [prefix, name];\n }", "function splitPrefix(name) {\n var prefix,\n index = name ? name.indexOf('!') : -1;\n if (index > -1) {\n prefix = name.substring(0, index);\n name = name.substring(index + 1, name.length);\n }\n return [prefix, name];\n }", "function splitPrefix(name) {\n var prefix,\n index = name ? name.indexOf('!') : -1;\n if (index > -1) {\n prefix = name.substring(0, index);\n name = name.substring(index + 1, name.length);\n }\n return [prefix, name];\n }", "function splitPrefix(name) {\n var prefix,\n index = name ? name.indexOf('!') : -1;\n if (index > -1) {\n prefix = name.substring(0, index);\n name = name.substring(index + 1, name.length);\n }\n return [prefix, name];\n }", "function splitPrefix(name) {\n var prefix,\n index = name ? name.indexOf('!') : -1;\n if (index > -1) {\n prefix = name.substring(0, index);\n name = name.substring(index + 1, name.length);\n }\n return [prefix, name];\n }", "function splitPrefix(name) {\n var prefix,\n index = name ? name.indexOf('!') : -1;\n if (index > -1) {\n prefix = name.substring(0, index);\n name = name.substring(index + 1, name.length);\n }\n return [prefix, name];\n }", "function splitPrefix(name) {\n var prefix,\n index = name ? name.indexOf('!') : -1;\n if (index > -1) {\n prefix = name.substring(0, index);\n name = name.substring(index + 1, name.length);\n }\n return [prefix, name];\n }", "function splitPrefix(name) {\n var prefix,\n index = name ? name.indexOf('!') : -1;\n if (index > -1) {\n prefix = name.substring(0, index);\n name = name.substring(index + 1, name.length);\n }\n return [prefix, name];\n }", "function splitPrefix(name) {\n var prefix,\n index = name ? name.indexOf('!') : -1;\n if (index > -1) {\n prefix = name.substring(0, index);\n name = name.substring(index + 1, name.length);\n }\n return [prefix, name];\n }", "function splitPrefix(name) {\n var prefix,\n index = name ? name.indexOf('!') : -1;\n if (index > -1) {\n prefix = name.substring(0, index);\n name = name.substring(index + 1, name.length);\n }\n return [prefix, name];\n }", "function splitPrefix(name) {\n var prefix,\n index = name ? name.indexOf('!') : -1;\n if (index > -1) {\n prefix = name.substring(0, index);\n name = name.substring(index + 1, name.length);\n }\n return [prefix, name];\n }", "function splitPrefix(name) {\n var prefix,\n index = name ? name.indexOf('!') : -1;\n if (index > -1) {\n prefix = name.substring(0, index);\n name = name.substring(index + 1, name.length);\n }\n return [prefix, name];\n }" ]
[ "0.62969595", "0.58671004", "0.58671004", "0.57943285", "0.5714892", "0.564559", "0.55580175", "0.5534085", "0.5529474", "0.5527311", "0.5524464", "0.5518711", "0.5513337", "0.55102795", "0.5503454", "0.5497291", "0.5481376", "0.54566014", "0.5450117", "0.5434705", "0.54269487", "0.541877", "0.5417284", "0.5413729", "0.5406111", "0.53922397", "0.538548", "0.53854644", "0.5379259", "0.53732324", "0.53714275", "0.5363545", "0.5336551", "0.53282243", "0.5323002", "0.5308281", "0.5308281", "0.5308281", "0.5308281", "0.5305383", "0.53022057", "0.5301943", "0.5300858", "0.52916735", "0.5289614", "0.5288472", "0.5260394", "0.52589", "0.52554864", "0.52546805", "0.52533275", "0.5247754", "0.52470005", "0.5236754", "0.52366686", "0.52337235", "0.52337235", "0.52331257", "0.52321005", "0.52311134", "0.5229606", "0.52286273", "0.5215587", "0.52146095", "0.52129805", "0.5212712", "0.5210919", "0.5210919", "0.520827", "0.520357", "0.520172", "0.5192361", "0.5189672", "0.51857334", "0.51826674", "0.5178217", "0.51734555", "0.51734555", "0.51725674", "0.5167177", "0.5159822", "0.5158383", "0.51583076", "0.5156097", "0.5153696", "0.5152458", "0.51521057", "0.51498085", "0.5146515", "0.5146515", "0.5146515", "0.5146515", "0.5146515", "0.5146515", "0.5146515", "0.5146515", "0.5146515", "0.5146515", "0.5146515", "0.5146515" ]
0.74927485
0
Hapus Derivation Suffixes ("i", "an" atau "kan")
function Del_Derivation_Suffixes(kata,selesai){ var kataAsal = kata; var sam=kata if(kata.match(/(i|an)$/i)){ // Cek Suffixes var __kata = sam.replace(/(i|an)$/i,''); cekKamus(__kata,function(bool){ if(bool){ selesai(__kata) }else if(kata.match(/(kan)$/i)){ __kata=sam.replace(/(kan)$/i,'') cekKamus(__kata,function(kan){ if(kan){ selesai(__kata) }else{ selesai(kataAsal) } }) }else{ selesai(kataAsal) } }) }else{ selesai(kataAsal) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function Del_Derivation_Prefix(kata,selesai){\n\tvar kataAsal = kata;\nvar __kata,__kata__=\"\"\n\t/* —— Tentukan Tipe Awalan ————*/\nif(kata.match(/^(di|[ks]e)/)){ // Jika di-,ke-,se-\n __kata = kata.replace(/^(di|[ks]e)/,'');\n \n cekKamus(__kata,function(data){\n\t if(data){\n\t\tselesai(__kata)\n\t }else{\n\t \t\n\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\n\t\t\t\n cekKamus(__kata__,function(data){\n\t if(data){\n\t\t selesai(__kata__)\n\t }else if(kata.match(/^(diper)/)){ //diper-\n\t\t\n\t\t\t__kata = kata.replace(/^(diper)/,'');\n\t\t\t Del_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\tselesai(__kata__)\t\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t \t\n\t\t\t });\n\t\t\n\t\t\t\n\t\t\t\n\t\t}else if(kata.match(/^(ke[bt]er)/)){ //keber- dan keter-\n\t\t __kata = kata.replace(/^(ke[bt]er)/,'');\n\t\t\t Del_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\t\n\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t});\n\t\t\n\t\t\t\n\t\t\t\n\t\t} else{\n\t\t\tselesai(kata.replace(/^(di|[ks]e)/,''))\n\t\t}\n })\n }) \t\n\t }\n })\t\t\n\t\t\n\t}else if(kata.match(/^([bt]e)/)){ //Jika awalannya adalah \"te-\",\"ter-\", \"be-\",\"ber-\"\n\t\t\n\t\t __kata = kata.replace(/^([bt]e)/,'');\n\t\t\n\t\tcekKamus(__kata,function(data){\n\t\t\tif(data){\n\t\t\t\tselesai(__kata)\n\t\t\t}else{\n\t\t__kata = kata.replace(/^([bt]e[lr])/,'');\t\n\t\t\n\t\tcekKamus(__kata,function(data){\n\t\t\tif(data){\n\t\t\t\tselesai(__kata)\n\t\t\t}else{\n\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\n\t\tcekKamus(__kata__,function(data){\n\t\t\tif(data){\n\t\t\t\tselesai(__kata__)\n\t\t\t}else{\n\t\t\t\tselesai(kataAsal)\n\t\t\t}\n\t\t})\n\t\t})}\t\n\t\t\t\n\t\t})}\n\t\t});\n\t\t\n\t\t}else if(kata.match(/^([mp]e)/)){\n\t\t__kata = kata.replace(/^([mp]e)/,'');\n\t\t\n\t\tcekKamus(__kata,function(data){\n\t\t\tif(data){\n\t\t\tselesai(__kata)\n\t\t\t}else\n\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\n\t\tcekKamus(__kata__,function(data){\n\t\tif(data){\n\t\t\tselesai(__kata__)\n\t\t}else if(kata.match(/^(memper)/)){\n\t\t\t__kata = kata.replace(/^(memper)/,'');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\n\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t\n\t\t})}\n\t\t\t})\n\t\t\n\t\t\t\n\t\t\t\n\t\t}else if(kata.match(/^([mp]eng)/)){\n\t\t\t__kata = kata.replace(/^([mp]eng)/,'');\n\t\tcekKamus(__kata,function(data1){\n\t\t\tif(data1){\n\t\t\t\tselesai(__kata)\n\t\t\t}else{\n\t\t\tDel_Derivation_Suffixes(__kata,function(data2){\n\t\t\t__kata__=data2\n\t\t\tcekKamus(__kata__,function(data3){\n\t\t\t\tif(data3){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t__kata = kata.replace(/^([mp]eng)/,'k');\n\t\t\tcekKamus(__kata,function(data4){\n\t\t\t\tif(data4){\n\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data5){\n\t\t\t__kata__ =data5\n\t\t\tcekKamus(__kata__,function(data6){\n\t\t\t\tif(data6){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\t__kata = kata.replace(/^([mp]enge)/,'');//menge- dan penge-\n\t\t\tcekKamus(__kata,function(data4){\n\t\t\t\tif(data4){\n\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data5){\n\t\t\t__kata__ =data5\n\t\t\tcekKamus(__kata__,function(data6){\n\t\t\t\tif(data6){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t \t\n\t\t\t });\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t})\n\t\t\t\t}\n\t\t\t})\n\t\t\t \t\n\t\t\t });\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t})\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t})\n\t\t\t \t\n\t\t\t });}\n\t\t})\n\t\t\t \n\t\t}else if(kata.match(/^([mp]eny)/)){\n\t\t\t__kata = kata.replace(/^([mp]eny)/,'s');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ =data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\tif(data){\n\t\t\t\tselesai(__kata__)\n\t\t\t}else{\n\t\t\t\tselesai(kataAsal)\n\t\t\t}\n\t\t})\n\t\t\t});}\n\t\t\t})\n\t\t\t\n\t\t\t \n\t\t\n\t\t\t\n\t\t}else if(kata.match(/^([mp]e[lr])/)){\n\t\t\t__kata = kata.replace(/^([mp]e[lr])/,'');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ =data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\tif(data){\n\t\t\t\tselesai(__kata__)\n\t\t\t}else{\n\t\t\t\tselesai(kataAsal)\n\t\t\t}\n\t\t\t})\n\t\t\t \t\n\t\t\t })}\n\t\t\t})\n\t\t\t\n\t\t}else if(kata.match(/^([mp]en)/)){\n\t\t\t__kata = kata.replace(/^([mp]en)/,'t');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ =data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\tselesai(__kata__)\t\n\t\t\t\t}else{\n\t\t\t\t__kata = kata.replace(/^([mp]en)/,'');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\tselesai(__kata)\n\t\t\t\t}else {\n\t\t\t\t\t\n\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ = data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t\t\n\t\t\t});}\n\t\t\t})}\n\t\t\t})\n\t\t\t \t\n\t\t\t });}\n\t\t\t\t\n\t\t\t})\n\t\t\t\n\t\t\n\t\t\t\n\t\t}else if(kata.match(/^([mp]em)/)){\n\t\t\t__kata = kata.replace(/^([mp]em)/,'');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ = data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t__kata = kata.replace(/^([mp]em)/,'p');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ = data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t});}\n\t\t\t})}\n\t\t\t})\n\t\t\t});}\n\t\t\t})\n\t\t\t}\t\n\t\t\n\t\t})\n\t\t \t\n\t\t });\n\t\t})\n\t\t\n\t\t \n\t}else{\n\tselesai(kataAsal)\n\t}\n}", "function Del_Inflection_Suffixes(kata,selesai){ \n\tvar kataAsal = kata;\n\t\n\tif(kata.match(/([km]u|nya|[kl]ah|pun)$/i)){ // Cek Inflection Suffixes\n\t\tvar __kata = kata.replace(/([km]u|nya|[kl]ah|pun)$/i,'');\n\n\t\tselesai(__kata);\n\t}else{\n\tselesai(kataAsal);\n\t}\n}", "function Bi(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "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)}", "function get_dec_name()\n{\n\treturn \"CAN\";\n}", "function zu(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e.toString(10)}}", "function getDNILetterByParameter (dni) { \r\n dniLetter =\"TRWAGMYFPDXBNJZSQVHLCKET\"; \r\n position = dni % 23; \r\n return dniLetter.substring(position, position+1); \r\n}", "function Iu(e,t,n,i){switch(n){case\"s\":return i||t?\"néhány másodperc\":\"néhány másodperce\";case\"ss\":return e+(i||t?\" másodperc\":\" másodperce\");case\"m\":return\"egy\"+(i||t?\" perc\":\" perce\");case\"mm\":return e+(i||t?\" perc\":\" perce\");case\"h\":return\"egy\"+(i||t?\" óra\":\" órája\");case\"hh\":return e+(i||t?\" óra\":\" órája\");case\"d\":return\"egy\"+(i||t?\" nap\":\" napja\");case\"dd\":return e+(i||t?\" nap\":\" napja\");case\"M\":return\"egy\"+(i||t?\" hónap\":\" hónapja\");case\"MM\":return e+(i||t?\" hónap\":\" hónapja\");case\"y\":return\"egy\"+(i||t?\" év\":\" éve\");case\"yy\":return e+(i||t?\" év\":\" éve\")}return\"\"}", "static scientificName() {\n return 'Suricata suricatta';\n }", "function translate$7(number,withoutSuffix,key,isFuture){switch(key){case 's':return withoutSuffix?'хэдхэн секунд':'хэдхэн секундын';case 'ss':return number + (withoutSuffix?' секунд':' секундын');case 'm':case 'mm':return number + (withoutSuffix?' минут':' минутын');case 'h':case 'hh':return number + (withoutSuffix?' цаг':' цагийн');case 'd':case 'dd':return number + (withoutSuffix?' өдөр':' өдрийн');case 'M':case 'MM':return number + (withoutSuffix?' сар':' сарын');case 'y':case 'yy':return number + (withoutSuffix?' жил':' жилийн');default:return number;}}", "function commonNumberSuffixes() {\n\t\treturn [\n\t\t\t'th',\t\t// 4th\n\t\t];\n\t}", "function decimales(n) {\n\tpermitidos = /[^0-9.-]/;\n\tcadena = n.value;\n\tband = false;\n\tfor (i = 0; i < cadena.length; i++) {\n\t\tletra = cadena.substring(i, i + 1);\n\t\tif (permitidos.test(letra)) {\n\t\t\tcadena2 = cadena;\n\t\t\tcadena = cadena2.replace(letra, \"\");\n\t\t\tband = true;\n\t\t}\n\t}\n\tvar cont = 0;\n\tvar cont2 = 0;\n\tfor (i = 0; i < cadena.length; i++) {\n\t\tletra = cadena.substring(i, i + 1);\n\t\tif (letra === \".\") {\n\t\t\tcont++;\n\t\t\tif (cont > 1) {\n\t\t\t\tcadena2 = cadena;\n\t\t\t\tcadena = cadena2.substring(0, cadena.length - 1);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (letra === \"-\") {\n\t\t\tcont2++;\n\t\t\tif (cont2 > 1) {\n\t\t\t\tcadena2 = cadena;\n\t\t\t\tcadena = cadena2.substring(0, cadena.length - 1);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tn.value = cadena;\n}", "function normal_name(d) {\n let inst_name = d.name.replace(/_/g, ' ').split('#')[0];\n if (inst_name.length > params.labels.max_label_char) {\n inst_name = inst_name.substring(0, params.labels.max_label_char) + '..';\n }\n return inst_name;\n }", "function ud(a,b,c){var d={mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"};return a+\" \"+xd(d[c],a)}", "function ud(a,b,c){var d={mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"};return a+\" \"+xd(d[c],a)}", "function ud(a,b,c){var d={mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"};return a+\" \"+xd(d[c],a)}", "function get_dec_name()\n{\n\treturn \"NMEA 0183\";\n}", "function suffix(num) {\n\ts = num.toString();\n\tnum_end = parseInt(s.slice(s.length-2));\n\n\tif (num_end % 10 === 1 && num_end != 11) {\n\t\treturn \"st\";\n\t} else if (num_end % 10 === 2 && num_end != 12) {\n\t\treturn \"nd\";\n\t} else if (num_end % 10 === 3 && num_end != 13) {\n\t\treturn \"rd\";\n\t} else {\n\t\treturn \"th\";\n\t}\n}", "function ud(a, b, c) {\r\n var d = {\r\n mm: \"munutenn\",\r\n MM: \"miz\",\r\n dd: \"devezh\"\r\n };\r\n return a + \" \" + xd(d[c], a)\r\n }", "function abbreviationQuickFix(source, post, post2)\n {\n addConversion(source, \"kilo\" + post, \"k\" + post2, 1);\n addConversion(source, \"centi\" + post, \"c\" + post2, 1);\n addConversion(source, \"milli\" + post, \"m\" + post2, 1);\n addConversion(source, \"nano\" + post, \"n\" + post2, 1);\n addConversion(source, \"micro\" + post, \"u\" + post2, 1);\n addConversion(source, \"pico\" + post, \"p\" + post2, 1);\n addConversion(source, \"femto\" + post, \"f\" + post2, 1);\n }", "function get_dec_name()\n{\n\treturn \"SSI\";\n}", "noun( num, singular, plutal, append ) {\n append = String( append || '' );\n return String( num +' '+ ( parseFloat( num ) === 1 ? singular : plutal ) +' '+ append ).trim();\n }", "function Kn(e){var t=/(-[a-z])/g,n=function(e){return e[1].toUpperCase()},r={};for(var a in e)r[a]=e[a],r[a.replace(t,n)]=e[a];return r}", "function nounForms() {\n return [...Array(28).keys()].map(i => (plurality[i >= cases.length ? 1 : 0] + \" \" + cases[i % cases.length]));\n}", "function nomen(){\n\tvar vowels = \"aeiouy\";\n\tvar consonants = \"bcdfghjklmnprstvwxyz\";\n\tvar first = \"ABCDEFGHIJKLMNOPRSTUVWXYZ\";\n\tvar special_endings = new Array();\n\tspecial_endings[0] = \"ck\";\n\tspecial_endings[1] = \"rs\";\n\tspecial_endings[2] = \"rz\";\n\tspecial_endings[3] = \"lm\";\n\tspecial_endings[4] = \"lk\";\n\tspecial_endings[5] = \"lp\";\n\tspecial_endings[6] = \"rt\";\n\tspecial_endings[7] = \"ff\";\n\tspecial_endings[8] = \"tz\";\n\tspecial_endings[9] = \"wz\";\n\tspecial_endings[10] = \"sh\"; \n\tspecial_endings[11] = \"qu\";\n\t\n\tvar poke = first.charAt( chaos(24) );\n\tvar nameN = 2 + chaos(5);\n\t\n\t\n\t//we have our first letter!\n\tvar name = poke;\n\tfor(i = 1; i < nameN; i++){\n\t\t//if true get a consonant next else get a vowel\n\t\tif (vowels.search(poke.toLowerCase()) != -1){\n\t\t\tpoke = consonants.charAt( chaos(19) );\n\t\t\tif( i == ( nameN - 1) && ( chaos(100) <= 50 ) ){\n\t\t\t\t//this is also the last letter\n\t\t\t\t//and a 50% chance of a special ending\n\t\t\t\tpoke = special_endings[chaos(12)-1];\n\t\t\t}//end if special ending\n\t\t}else{\n\t\t\tpoke = vowels.charAt( chaos(5) );\n\t\t}//end if vowel else consonant\n\t\t\n\t\tname += poke;\n\t}//end for length of name\n\t\n\treturn name;\n\t\n}//end function nomen", "function getDerivacaoAFND(der, terminal){\n while(der.charAt(0) != \"}\"){\n /**\n * IGUAL AO FND\n */\n var regra = \"([a-zA-Z]|[0-9]|_)\\\\:\\\\[\";\n var reg = new RegExp(regra);\n var letra = der.match(reg);\n if(letra[1] == \"_\") letra[1] = \"\";\n der = der.replace(reg, \"\");\n /**\n * TRATAR COLCHETES\n */\n while(der.charAt(0) != ']'){\n regra = \"([a-z][0-9][0-9]*)\";\n reg = new RegExp(regra);\n var derivacao = der.match(reg);\n der = der.replace(reg, \"\");\n if(der.charAt(0) == ',' || der.charAt(0) == '{') der = der.substring(1 , der.length); \n addTabela(numParaLetra(terminal), (letra[1] + numParaLetra(derivacao[0])));\n }\n der = der.substring(1 , der.length);\n }\n return der;\n}", "function dn(t) {\n switch (t) {\n case 1:\n return \"first\";\n\n case 2:\n return \"second\";\n\n case 3:\n return \"third\";\n\n default:\n return t + \"th\";\n }\n}", "function Hn(t) {\n return lt(zn(t)) + \"|lt:\" + t.an;\n}", "mayuscula(desc) {\n return desc.charAt(0).toUpperCase() + desc.slice(1);\n }", "function e(t,e,n,i){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,n,i){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,n,i){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,n,i){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,n,i){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,n,i){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,n,i){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,n,i){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,n,i){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,n,i){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function doctorize2(name) {\r\n return `Dr. ${name}`;\r\n}", "function e(t,e,i,n){switch(i){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function inferPlural (sing) {\n if (sing.endsWith('na')) { // widna\n return sing.slice(0, -1) + 'iet' // widniet\n } else if (sing.endsWith('i')) { // baħri\n return sing + 'n' // baħrin\n } else if (sing.endsWith('a') || sing.endsWith('u')) { // rota, inkwatru\n return sing.slice(0, -1) + 'i' // roti, inkwatri\n } else if (sing.endsWith('q')) { // triq\n return sing + 'at' // triqat\n } else {\n return sing + 'i'\n }\n}", "function latin_decline (n, key) {\r\n var forms = this[key];\r\n return n + \" \" + forms[n==1?0:1];\r\n}", "function masculineForms(lastChar, inputWord, secondToLastChar) {\n \n if (secondToLastChar === \"c\") {\n newWord = inputWord.slice(0, -2) + \"quito\"; \n dimunutive.innerHTML = newWord;\n } else if (lastChar === \"k\") {\n newWord = inputWord.slice(0, -1) + \"quito\"; \n dimunutive.innerHTML = newWord;\n } else if (secondToLastChar === \"g\") {\n newWord = inputWord.slice(0, -1) + \"uito\"; \n dimunutive.innerHTML = newWord;\n } else if (lastChar === \"z\") {\n newWord = inputWord.slice(0, -1) + \"cecito\"; \n dimunutive.innerHTML = newWord;\n } else if (secondToLastChar === \"u\") {\n newWord = inputWord.slice(0, -2) + \"üito\"; \n dimunutive.innerHTML = newWord;\n } else if (secondToLastChar === \"t\") {\n newWord = \"1: \" + inputWord.slice(0, -1) + \"ito\"; \n dimunutive.innerHTML = newWord;\n \n newWord = \"2: \" + inputWord.slice(0, -1) + \"ico\"; \n specialIco.innerHTML = newWord;\n } else if (lastChar === \"o\") {\n newWord = inputWord.slice(0, -1) + \"ito\"; \n dimunutive.innerHTML = newWord;\n } else if (lastChar === \"l\" || lastChar === \"s\" && secondToLastChar === \"e\") {\n newWord = inputWord + \"ito\";\n dimunutive.innerHTML = newWord;\n } else if (lastChar === \"r\" || lastChar === \"n\" || lastChar === \"e\") {\n newWord = inputWord + \"cito\";\n dimunutive.innerHTML = newWord;\n } else if (lastChar === \"s\") {\n newWord = inputWord.slice(0, -2) + \"itos\"; \n dimunutive.innerHTML = newWord;\n } else {\n newWord = inputWord + \"ito\";\n dimunutive.innerHTML = newWord;\n }\n }", "function Cek_Prefix_Disallowed_Sufixes(kata){\n\n\tif(kata.match(/^(be)[a-zA-Z]+(i)/)){ // be- dan -i\n\t\treturn true;\n\t}\n\n\tif(kata.match(/^(se)[a-zA-Z]+(i|kan)/)){ // se- dan -i,-kan\n\t\treturn true;\n\t}\n\t\n\tif(kata.match(/^(di)[a-zA-Z]+(an)/)){ // di- dan -an\n\t\treturn true;\n\t}\n\t\n\tif(kata.match(/^(me)[a-zA-Z]+(an)/)){ // me- dan -an\n\t\treturn true;\n\t}\n\t\n\tif(kata.match(/^(ke)[a-zA-Z]+(i|kan)/)){ // ke- dan -i,-kan\n\t\treturn true;\n\t}\n\treturn false;\n}", "function feminineForms(lastChar, inputWord, secondToLastChar) {\n \n if (secondToLastChar === \"c\") {\n newWord = inputWord.slice(0, -2) + \"quita\"; \n dimunutive.innerHTML = newWord;\n } else if (lastChar === \"k\") {\n newWord = inputWord.slice(0, -1) + \"quita\"; \n dimunutive.innerHTML = newWord;\n } else if (secondToLastChar === \"g\") {\n newWord = inputWord.slice(0, -1) + \"uita\"; \n dimunutive.innerHTML = newWord;\n } else if (lastChar === \"z\") {\n newWord = inputWord.slice(0, -1) + \"cecita\"; \n dimunutive.innerHTML = newWord;\n } else if (secondToLastChar === \"u\") {\n newWord = inputWord.slice(0, -2) + \"üita\"; \n dimunutive.innerHTML = newWord;\n } else if (secondToLastChar === \"t\") {\n newWord = \"1: \" + inputWord.slice(0, -1) + \"ita\"; \n dimunutive.innerHTML = newWord;\n \n newWord = \"2: \" + inputWord.slice(0, -1) + \"ica\"; \n specialIco.innerHTML = newWord;\n } else if (lastChar === \"a\") {\n newWord = inputWord.slice(0, -1) + \"ita\"; \n dimunutive.innerHTML = newWord;\n } else if (lastChar === \"l\" || lastChar === \"s\" && secondToLastChar === \"e\") {\n newWord = inputWord + \"ita\";\n dimunutive.innerHTML = newWord;\n } else if (lastChar === \"r\" || lastChar === \"n\" || lastChar === \"e\") {\n newWord = inputWord + \"cita\";\n dimunutive.innerHTML = newWord;\n } else if (lastChar === \"s\") {\n newWord = inputWord.slice(0, -2) + \"itas\"; \n dimunutive.innerHTML = newWord;\n } else {\n newWord = inputWord + \"ita\";\n dimunutive.innerHTML = newWord;\n }\n }", "constructor(){\n // length three prefixes\n this.p3 = [\n \"\\u0643\\u0627\\u0644\",\n \"\\u0628\\u0627\\u0644\",\n \"\\u0648\\u0644\\u0644\",\n \"\\u0648\\u0627\\u0644\",\n ]\n\n // length two prefixes\n this.p2 = [\"\\u0627\\u0644\", \"\\u0644\\u0644\"];\n\n // length one prefixes\n this.p1 = [\n \"\\u0644\",\n \"\\u0628\",\n \"\\u0641\",\n \"\\u0633\",\n \"\\u0648\",\n \"\\u064a\",\n \"\\u062a\",\n \"\\u0646\",\n \"\\u0627\",\n ];\n\n // length three suffixes\n this.s3 = [\n \"\\u062a\\u0645\\u0644\",\n \"\\u0647\\u0645\\u0644\",\n \"\\u062a\\u0627\\u0646\",\n \"\\u062a\\u064a\\u0646\",\n \"\\u0643\\u0645\\u0644\",\n ];\n\n // length two suffixes\n this.s2 = [\n \"\\u0648\\u0646\",\n \"\\u0627\\u062a\",\n \"\\u0627\\u0646\",\n \"\\u064a\\u0646\",\n \"\\u062a\\u0646\",\n \"\\u0643\\u0645\",\n \"\\u0647\\u0646\",\n \"\\u0646\\u0627\",\n \"\\u064a\\u0627\",\n \"\\u0647\\u0627\",\n \"\\u062a\\u0645\",\n \"\\u0643\\u0646\",\n \"\\u0646\\u064a\",\n \"\\u0648\\u0627\",\n \"\\u0645\\u0627\",\n \"\\u0647\\u0645\",\n ];\n\n // length one suffixes\n this.s1 = [\"\\u0629\", \"\\u0647\", \"\\u064a\", \"\\u0643\", \"\\u062a\", \"\\u0627\", \"\\u0646\"];\n\n // groups of length four patterns\n this.pr4 = {\n 0: [\"\\u0645\"],\n 1: [\"\\u0627\"],\n 2: [\"\\u0627\", \"\\u0648\", \"\\u064A\"],\n 3: [\"\\u0629\"],\n };\n\n // Groups of length five patterns and length three roots\n this.pr53 = {\n 0: [\"\\u0627\", \"\\u062a\"],\n 1: [\"\\u0627\", \"\\u064a\", \"\\u0648\"],\n 2: [\"\\u0627\", \"\\u062a\", \"\\u0645\"],\n 3: [\"\\u0645\", \"\\u064a\", \"\\u062a\"],\n 4: [\"\\u0645\", \"\\u062a\"],\n 5: [\"\\u0627\", \"\\u0648\"],\n 6: [\"\\u0627\", \"\\u0645\"],\n };\n\n this.re_short_vowels = new RegExp(\"[\\u064B-\\u0652]\");\n this.re_hamza = new RegExp(\"[\\u0621\\u0624\\u0626]\");\n this.re_initial_hamza = new RegExp(\"^[\\u0622\\u0623\\u0625]\");\n\n this.stop_words = [\n \"\\u064a\\u0643\\u0648\\u0646\",\n \"\\u0648\\u0644\\u064a\\u0633\",\n \"\\u0648\\u0643\\u0627\\u0646\",\n \"\\u0643\\u0630\\u0644\\u0643\",\n \"\\u0627\\u0644\\u062a\\u064a\",\n \"\\u0648\\u0628\\u064a\\u0646\",\n \"\\u0639\\u0644\\u064a\\u0647\\u0627\",\n \"\\u0645\\u0633\\u0627\\u0621\",\n \"\\u0627\\u0644\\u0630\\u064a\",\n \"\\u0648\\u0643\\u0627\\u0646\\u062a\",\n \"\\u0648\\u0644\\u0643\\u0646\",\n \"\\u0648\\u0627\\u0644\\u062a\\u064a\",\n \"\\u062a\\u0643\\u0648\\u0646\",\n \"\\u0627\\u0644\\u064a\\u0648\\u0645\",\n \"\\u0627\\u0644\\u0644\\u0630\\u064a\\u0646\",\n \"\\u0639\\u0644\\u064a\\u0647\",\n \"\\u0643\\u0627\\u0646\\u062a\",\n \"\\u0644\\u0630\\u0644\\u0643\",\n \"\\u0623\\u0645\\u0627\\u0645\",\n \"\\u0647\\u0646\\u0627\\u0643\",\n \"\\u0645\\u0646\\u0647\\u0627\",\n \"\\u0645\\u0627\\u0632\\u0627\\u0644\",\n \"\\u0644\\u0627\\u0632\\u0627\\u0644\",\n \"\\u0644\\u0627\\u064a\\u0632\\u0627\\u0644\",\n \"\\u0645\\u0627\\u064a\\u0632\\u0627\\u0644\",\n \"\\u0627\\u0635\\u0628\\u062d\",\n \"\\u0623\\u0635\\u0628\\u062d\",\n \"\\u0623\\u0645\\u0633\\u0649\",\n \"\\u0627\\u0645\\u0633\\u0649\",\n \"\\u0623\\u0636\\u062d\\u0649\",\n \"\\u0627\\u0636\\u062d\\u0649\",\n \"\\u0645\\u0627\\u0628\\u0631\\u062d\",\n \"\\u0645\\u0627\\u0641\\u062a\\u0626\",\n \"\\u0645\\u0627\\u0627\\u0646\\u0641\\u0643\",\n \"\\u0644\\u0627\\u0633\\u064a\\u0645\\u0627\",\n \"\\u0648\\u0644\\u0627\\u064a\\u0632\\u0627\\u0644\",\n \"\\u0627\\u0644\\u062d\\u0627\\u0644\\u064a\",\n \"\\u0627\\u0644\\u064a\\u0647\\u0627\",\n \"\\u0627\\u0644\\u0630\\u064a\\u0646\",\n \"\\u0641\\u0627\\u0646\\u0647\",\n \"\\u0648\\u0627\\u0644\\u0630\\u064a\",\n \"\\u0648\\u0647\\u0630\\u0627\",\n \"\\u0644\\u0647\\u0630\\u0627\",\n \"\\u0641\\u0643\\u0627\\u0646\",\n \"\\u0633\\u062a\\u0643\\u0648\\u0646\",\n \"\\u0627\\u0644\\u064a\\u0647\",\n \"\\u064a\\u0645\\u0643\\u0646\",\n \"\\u0628\\u0647\\u0630\\u0627\",\n \"\\u0627\\u0644\\u0630\\u0649\",\n ];\n }", "function panjang (str) {\n let hasil = ''\n //let b = options.length;\n for(let i=0; i< b; i++) {\n hasil += randomStr(str)[i]\n }\n return hasil;\n }", "function translate_10_Lakh(s){\n\tif(s == \"0000000\"){\n\t\treturn \"\";\n\t}\n\tvar firstDigit = s.substring(0,2);\n\tvar remainingDigits = s.substring(2,7);\n\tvar firstDescription = translate_Tens(firstDigit);\n\tvar remainingDescription = translate_10_Thousands(remainingDigits);\n\tvar output = \"\";\n\tif(firstDescription != \"\"){\n\t\toutput = output + firstDescription + \" \" + \"Lakh\";\n\t\tif(remainingDescription != \"\"){\n\t\t\toutput = output + \" \" + remainingDescription;\n\t\t}\n\t}else{\n\t\tif(remainingDescription != \"\"){\n\t\t\toutput = remainingDescription;\n\t\t}\n\t}\n\treturn output; \t\n}", "function HyderabadTirupati() // extends PhoneticMapper\n{\n var map = [ \n new KeyMap(\"\\u0901\", \"?\", \"z\", true), // Candrabindu\n new KeyMap(\"\\u0902\", \"\\u1E41\", \"M\"), // Anusvara\n new KeyMap(\"\\u0903\", \"\\u1E25\", \"H\"), // Visarga\n new KeyMap(\"\\u1CF2\", \"\\u1E96\", \"Z\"), // jihvamuliya\n new KeyMap(\"\\u1CF2\", \"h\\u032C\", \"V\"), // upadhmaniya\n new KeyMap(\"\\u0905\", \"a\", \"a\"), // a\n new KeyMap(\"\\u0906\", \"\\u0101\", \"A\"), // long a\n new KeyMap(\"\\u093E\", null, \"A\", true), // long a attached\n new KeyMap(\"\\u0907\", \"i\", \"i\"), // i\n new KeyMap(\"\\u093F\", null, \"i\", true), // i attached\n new KeyMap(\"\\u0908\", \"\\u012B\", \"I\"), // long i\n new KeyMap(\"\\u0940\", null, \"I\", true), // long i attached\n new KeyMap(\"\\u0909\", \"u\", \"u\"), // u\n new KeyMap(\"\\u0941\", null, \"u\", true), // u attached\n new KeyMap(\"\\u090A\", \"\\u016B\", \"U\"), // long u\n new KeyMap(\"\\u0942\", null, \"U\", true), // long u attached\n new KeyMap(\"\\u090B\", \"\\u1E5B\", \"q\"), // vocalic r\n new KeyMap(\"\\u0943\", null, \"q\", true), // vocalic r attached\n new KeyMap(\"\\u0960\", \"\\u1E5D\", \"Q\"), // long vocalic r\n new KeyMap(\"\\u0944\", null, \"Q\", true), // long vocalic r attached\n new KeyMap(\"\\u090C\", \"\\u1E37\", \"L\"), // vocalic l\n new KeyMap(\"\\u0962\", null, \"L\", true), // vocalic l attached\n new KeyMap(\"\\u0961\", \"\\u1E39\", \"LY\"), // long vocalic l\n new KeyMap(\"\\u0963\", null, \"LY\", true), // long vocalic l attached\n new KeyMap(\"\\u090F\", \"e\", \"e\"), // e\n new KeyMap(\"\\u0947\", null, \"e\", true), // e attached\n new KeyMap(\"\\u0910\", \"ai\", \"E\"), // ai\n new KeyMap(\"\\u0948\", null, \"E\", true), // ai attached\n new KeyMap(\"\\u0913\", \"o\", \"o\"), // o\n new KeyMap(\"\\u094B\", null, \"o\", true), // o attached\n new KeyMap(\"\\u0914\", \"au\", \"O\"), // au\n new KeyMap(\"\\u094C\", null, \"O\", true), // au attached\n\n // velars\n new KeyMap(\"\\u0915\\u094D\", \"k\", \"k\"), // k\n new KeyMap(\"\\u0916\\u094D\", \"kh\", \"K\"), // kh\n new KeyMap(\"\\u0917\\u094D\", \"g\", \"g\"), // g\n new KeyMap(\"\\u0918\\u094D\", \"gh\", \"G\"), // gh\n new KeyMap(\"\\u0919\\u094D\", \"\\u1E45\", \"f\"), // velar n\n\n // palatals\n new KeyMap(\"\\u091A\\u094D\", \"c\", \"c\"), // c\n new KeyMap(\"\\u091B\\u094D\", \"ch\", \"C\"), // ch\n new KeyMap(\"\\u091C\\u094D\", \"j\", \"j\"), // j\n new KeyMap(\"\\u091D\\u094D\", \"jh\", \"J\"), // jh\n new KeyMap(\"\\u091E\\u094D\", \"\\u00F1\", \"F\"), // palatal n\n\n // retroflex\n new KeyMap(\"\\u091F\\u094D\", \"\\u1E6D\", \"t\"), // retroflex t\n new KeyMap(\"\\u0920\\u094D\", \"\\u1E6Dh\", \"T\"), // retroflex th\n new KeyMap(\"\\u0921\\u094D\", \"\\u1E0D\", \"d\"), // retroflex d\n new KeyMap(\"\\u0922\\u094D\", \"\\u1E0Dh\", \"D\"), // retroflex dh\n new KeyMap(\"\\u0923\\u094D\", \"\\u1E47\", \"N\"), // retroflex n\n new KeyMap(\"\\u0933\\u094D\", \"\\u1E37\", \"lY\"), // retroflex l\n new KeyMap(\"\\u0933\\u094D\\u0939\\u094D\", \"\\u1E37\", \"lYh\"), // retroflex lh\n\n // dental\n new KeyMap(\"\\u0924\\u094D\", \"t\", \"w\"), // dental t\n new KeyMap(\"\\u0925\\u094D\", \"th\", \"W\"), // dental th\n new KeyMap(\"\\u0926\\u094D\", \"d\", \"x\"), // dental d\n new KeyMap(\"\\u0927\\u094D\", \"dh\", \"X\"), // dental dh\n new KeyMap(\"\\u0928\\u094D\", \"n\", \"n\"), // dental n\n\n // labials\n new KeyMap(\"\\u092A\\u094D\", \"p\", \"p\"), // p\n new KeyMap(\"\\u092B\\u094D\", \"ph\", \"P\"), // ph\n new KeyMap(\"\\u092C\\u094D\", \"b\", \"b\"), // b\n new KeyMap(\"\\u092D\\u094D\", \"bh\", \"B\"), // bh\n new KeyMap(\"\\u092E\\u094D\", \"m\", \"m\"), // m\n\n // sibillants\n new KeyMap(\"\\u0936\\u094D\", \"\\u015B\", \"S\"), // palatal s\n new KeyMap(\"\\u0937\\u094D\", \"\\u1E63\", \"R\"), // retroflex s\n new KeyMap(\"\\u0938\\u094D\", \"s\", \"s\"), // dental s\n new KeyMap(\"\\u0939\\u094D\", \"h\", \"h\"), // h\n\n // semivowels\n new KeyMap(\"\\u092F\\u094D\", \"y\", \"y\"), // y\n new KeyMap(\"\\u0930\\u094D\", \"r\", \"r\"), // r\n new KeyMap(\"\\u0932\\u094D\", \"l\", \"l\"), // l\n new KeyMap(\"\\u0935\\u094D\", \"v\", \"v\"), // v\n\n\n // numerals\n new KeyMap(\"\\u0966\", \"0\", \"0\"), // 0\n new KeyMap(\"\\u0967\", \"1\", \"1\"), // 1\n new KeyMap(\"\\u0968\", \"2\", \"2\"), // 2\n new KeyMap(\"\\u0969\", \"3\", \"3\"), // 3\n new KeyMap(\"\\u096A\", \"4\", \"4\"), // 4\n new KeyMap(\"\\u096B\", \"5\", \"5\"), // 5\n new KeyMap(\"\\u096C\", \"6\", \"6\"), // 6\n new KeyMap(\"\\u096D\", \"7\", \"7\"), // 7\n new KeyMap(\"\\u096E\", \"8\", \"8\"), // 8\n new KeyMap(\"\\u096F\", \"9\", \"9\"), // 9\n\n // accents\n new KeyMap(\"\\u0951\", \"|\", \"|\"), // udatta\n new KeyMap(\"\\u0952\", \"_\", \"_\"), // anudatta\n new KeyMap(\"\\u0953\", null, \"//\"), // grave accent\n new KeyMap(\"\\u0954\", null, \"\\\\\"), // acute accent\n\n // miscellaneous\n new KeyMap(\"\\u0933\\u094D\", \"\\u1E37\", \"L\"), // retroflex l\n new KeyMap(\"\\u093D\", \"'\", \"'\"), // avagraha\n new KeyMap(\"\\u0950\", null, \"om\"), // om\n new KeyMap(\"\\u0964\", \".\", \".\") // single danda\n ];\n\n PhoneticMapper.call(this, map);\n}", "function translate(number,withoutSuffix,key,isFuture){switch(key){case\"s\":return withoutSuffix?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return number+(withoutSuffix?\" секунд\":\" секундын\");case\"m\":case\"mm\":return number+(withoutSuffix?\" минут\":\" минутын\");case\"h\":case\"hh\":return number+(withoutSuffix?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return number+(withoutSuffix?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return number+(withoutSuffix?\" сар\":\" сарын\");case\"y\":case\"yy\":return number+(withoutSuffix?\" жил\":\" жилийн\");default:return number}}", "function Ki(a){this.uh=a;this.ui=\"\";this.Eo=new RegExp(this.Eb,\"g\")}", "function t(e,t,n){var g={mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"};return e+\" \"+I(g[n],e)}", "function suffix() {\n return containsSuffix() ? name.split('+')[1] : undefined;\n }", "function d(a,b,c){var d={mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"};return a+\" \"+g(d[c],a)}", "function kalikanDua(angka) {\n return angka * 2;\n}", "function xu(e,t,n,i){var o=\"\";switch(n){case\"s\":return i?\"muutaman sekunnin\":\"muutama sekunti\";case\"ss\":return i?\"sekunnin\":\"sekuntia\";case\"m\":return i?\"minuutin\":\"minuutti\";case\"mm\":o=i?\"minuutin\":\"minuuttia\";break;case\"h\":return i?\"tunnin\":\"tunti\";case\"hh\":o=i?\"tunnin\":\"tuntia\";break;case\"d\":return i?\"päivän\":\"päivä\";case\"dd\":o=i?\"päivän\":\"päivää\";break;case\"M\":return i?\"kuukauden\":\"kuukausi\";case\"MM\":o=i?\"kuukauden\":\"kuukautta\";break;case\"y\":return i?\"vuoden\":\"vuosi\";case\"yy\":o=i?\"vuoden\":\"vuotta\"}return o=function(e,t){return e<10?t?Lu[e]:Su[e]:e}(e,i)+\" \"+o}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function GetSomewhereinPhoneticModifiedCharaceter(CUni)\r\n{\r\n\tvar CMod=CUni;\r\n\r\n\tif(LCUNI=='ক' && CUni=='হ') CMod = 'খ';\r\n\telse if(LCUNI=='গ' && CUni=='হ') CMod = 'ঘ';\r\n\telse if(LCUNI=='চ' && CUni=='হ') CMod = 'চ';\r\n\telse if(LCUNI=='জ' && CUni=='হ') CMod = 'ঝ';\r\n\telse if(LCUNI=='ট' && CUni=='হ') CMod = 'ঠ';\r\n\telse if(LCUNI=='ড' && CUni=='হ') CMod = 'ঢ';\r\n\telse if(LCUNI=='ত' && CUni=='হ') CMod = 'থ';\r\n\telse if(LCUNI=='দ' && CUni=='হ') CMod = 'ধ';\r\n\telse if(LCUNI=='প' && CUni=='হ') CMod = 'ফ';\r\n\telse if(LCUNI=='ব' && CUni=='হ') CMod = 'ভ';\r\n\telse if(LCUNI=='স' && CUni=='হ') CMod = 'শ';\r\n\telse if(LCUNI=='ড়' && CUni=='হ') CMod = 'ঢ়';\r\n\r\n\telse if(LCUNI=='ণ' && CUni=='গ') CMod = 'ঙ';\r\n\telse if(LCUNI=='ন' && CUni=='গ') CMod = 'ং';\r\n\t\r\n\telse if(LCUNI=='ণ' && CUni=='ঘ') CMod = 'ঞ';\r\n\r\n\telse if(LCUNI=='ণ' && CUni=='ণ') CMod = 'ঁ';\r\n\r\n\telse if(LCUNI=='ঃ' && CUni=='ঃ') CMod = 'ঃ';\r\n\t\r\n\telse if(LCUNI=='ট' && CUni=='ট') CMod = 'ৎ';\r\n\t\r\n\telse if(LCUNI=='া' && CUni=='ো') CMod = 'অ';\r\n\telse if(LCUNI=='ি' && CUni=='ি') CMod = 'ী';\r\n\telse if(LCUNI=='ই' && CUni=='ই') CMod = 'ঈ';\r\n\telse if(LCUNI=='ু' && CUni=='ু') CMod = 'ূ';\r\n\telse if(LCUNI=='উ' && CUni=='উ') CMod = 'ঊ';\r\n\telse if(LCUNI=='ও' && CUni=='ই') CMod = 'ঐ';\r\n\telse if(LCUNI=='ো' && CUni=='ি') CMod = 'ৈ';\r\n\telse if(LCUNI=='ও' && CUni=='উ') CMod = 'ঔ';\r\n\telse if(LCUNI=='ো' && CUni=='ু') CMod = 'ৌ';\r\n\telse if(LCUNI=='ৃ' && CUni=='র') CMod = 'ৃ';\r\n\telse if(LCUNI=='ঋ' && CUni=='ড়') CMod = 'ঋ';\r\n\r\n\treturn CMod;\r\n}", "function t(e,t,i,n){switch(i){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function doubleMetaphone(value) {\n var primary = ''\n var secondary = ''\n var index = 0\n var length = value.length\n var last = length - 1\n var isSlavoGermanic\n var isGermanic\n var subvalue\n var next\n var prev\n var nextnext\n var characters\n\n value = String(value).toUpperCase() + ' '\n isSlavoGermanic = slavoGermanic.test(value)\n isGermanic = germanic.test(value)\n characters = value.split('')\n\n // Skip this at beginning of word.\n if (initialExceptions.test(value)) {\n index++\n }\n\n // Initial X is pronounced Z, which maps to S. Such as `Xavier`.\n if (characters[0] === 'X') {\n primary += 'S'\n secondary += 'S'\n index++\n }\n\n while (index < length) {\n prev = characters[index - 1]\n next = characters[index + 1]\n nextnext = characters[index + 2]\n\n switch (characters[index]) {\n case 'A':\n case 'E':\n case 'I':\n case 'O':\n case 'U':\n case 'Y':\n case 'À':\n case 'Ê':\n case 'É':\n if (index === 0) {\n // All initial vowels now map to `A`.\n primary += 'A'\n secondary += 'A'\n }\n\n index++\n\n break\n case 'B':\n primary += 'P'\n secondary += 'P'\n\n if (next === 'B') {\n index++\n }\n\n index++\n\n break\n case 'Ç':\n primary += 'S'\n secondary += 'S'\n index++\n\n break\n case 'C':\n // Various Germanic:\n if (\n prev === 'A' &&\n next === 'H' &&\n nextnext !== 'I' &&\n !vowels.test(characters[index - 2]) &&\n (nextnext !== 'E' ||\n (subvalue =\n value.slice(index - 2, index + 4) &&\n (subvalue === 'BACHER' || subvalue === 'MACHER')))\n ) {\n primary += 'K'\n secondary += 'K'\n index += 2\n\n break\n }\n\n // Special case for `Caesar`.\n if (index === 0 && value.slice(index + 1, index + 6) === 'AESAR') {\n primary += 'S'\n secondary += 'S'\n index += 2\n\n break\n }\n\n // Italian `Chianti`.\n if (value.slice(index + 1, index + 4) === 'HIA') {\n primary += 'K'\n secondary += 'K'\n index += 2\n\n break\n }\n\n if (next === 'H') {\n // Find `Michael`.\n if (index > 0 && nextnext === 'A' && characters[index + 3] === 'E') {\n primary += 'K'\n secondary += 'X'\n index += 2\n\n break\n }\n\n // Greek roots such as `chemistry`, `chorus`.\n if (index === 0 && initialGreekCh.test(value)) {\n primary += 'K'\n secondary += 'K'\n index += 2\n\n break\n }\n\n // Germanic, Greek, or otherwise `CH` for `KH` sound.\n if (\n isGermanic ||\n // Such as 'architect' but not 'arch', orchestra', 'orchid'.\n greekCh.test(value.slice(index - 2, index + 4)) ||\n (nextnext === 'T' || nextnext === 'S') ||\n ((index === 0 ||\n prev === 'A' ||\n prev === 'E' ||\n prev === 'O' ||\n prev === 'U') &&\n // Such as `wachtler`, `weschsler`, but not `tichner`.\n chForKh.test(nextnext))\n ) {\n primary += 'K'\n secondary += 'K'\n } else if (index === 0) {\n primary += 'X'\n secondary += 'X'\n // Such as 'McHugh'.\n } else if (value.slice(0, 2) === 'MC') {\n // Bug? Why matching absolute? what about McHiccup?\n primary += 'K'\n secondary += 'K'\n } else {\n primary += 'X'\n secondary += 'K'\n }\n\n index += 2\n\n break\n }\n\n // Such as `Czerny`.\n if (next === 'Z' && value.slice(index - 2, index) !== 'WI') {\n primary += 'S'\n secondary += 'X'\n index += 2\n\n break\n }\n\n // Such as `Focaccia`.\n if (value.slice(index + 1, index + 4) === 'CIA') {\n primary += 'X'\n secondary += 'X'\n index += 3\n\n break\n }\n\n // Double `C`, but not `McClellan`.\n if (next === 'C' && !(index === 1 && characters[0] === 'M')) {\n // Such as `Bellocchio`, but not `Bacchus`.\n if (\n (nextnext === 'I' || nextnext === 'E' || nextnext === 'H') &&\n value.slice(index + 2, index + 4) !== 'HU'\n ) {\n subvalue = value.slice(index - 1, index + 4)\n\n // Such as `Accident`, `Accede`, `Succeed`.\n if (\n (index === 1 && prev === 'A') ||\n subvalue === 'UCCEE' ||\n subvalue === 'UCCES'\n ) {\n primary += 'KS'\n secondary += 'KS'\n // Such as `Bacci`, `Bertucci`, other Italian.\n } else {\n primary += 'X'\n secondary += 'X'\n }\n\n index += 3\n\n break\n } else {\n // Pierce's rule.\n primary += 'K'\n secondary += 'K'\n index += 2\n\n break\n }\n }\n\n if (next === 'G' || next === 'K' || next === 'Q') {\n primary += 'K'\n secondary += 'K'\n index += 2\n\n break\n }\n\n // Italian.\n if (\n next === 'I' &&\n // Bug: The original algorithm also calls for A (as in CIA), which is\n // already taken care of above.\n (nextnext === 'E' || nextnext === 'O')\n ) {\n primary += 'S'\n secondary += 'X'\n index += 2\n\n break\n }\n\n if (next === 'I' || next === 'E' || next === 'Y') {\n primary += 'S'\n secondary += 'S'\n index += 2\n\n break\n }\n\n primary += 'K'\n secondary += 'K'\n\n // Skip two extra characters ahead in `Mac Caffrey`, `Mac Gregor`.\n if (\n next === ' ' &&\n (nextnext === 'C' || nextnext === 'G' || nextnext === 'Q')\n ) {\n index += 3\n break\n }\n\n // Bug: Already covered above.\n // if (\n // next === 'K' ||\n // next === 'Q' ||\n // (next === 'C' && nextnext !== 'E' && nextnext !== 'I')\n // ) {\n // index++;\n // }\n\n index++\n\n break\n case 'D':\n if (next === 'G') {\n // Such as `edge`.\n if (nextnext === 'E' || nextnext === 'I' || nextnext === 'Y') {\n primary += 'J'\n secondary += 'J'\n index += 3\n // Such as `Edgar`.\n } else {\n primary += 'TK'\n secondary += 'TK'\n index += 2\n }\n\n break\n }\n\n if (next === 'T' || next === 'D') {\n primary += 'T'\n secondary += 'T'\n index += 2\n\n break\n }\n\n primary += 'T'\n secondary += 'T'\n index++\n\n break\n case 'F':\n if (next === 'F') {\n index++\n }\n\n index++\n primary += 'F'\n secondary += 'F'\n\n break\n case 'G':\n if (next === 'H') {\n if (index > 0 && !vowels.test(prev)) {\n primary += 'K'\n secondary += 'K'\n index += 2\n\n break\n }\n\n // Such as `Ghislane`, `Ghiradelli`.\n if (index === 0) {\n if (nextnext === 'I') {\n primary += 'J'\n secondary += 'J'\n } else {\n primary += 'K'\n secondary += 'K'\n }\n\n index += 2\n\n break\n }\n\n // Parker's rule (with some further refinements).\n if (\n // Such as `Hugh`. The comma is not a bug.\n ((subvalue = characters[index - 2]),\n subvalue === 'B' || subvalue === 'H' || subvalue === 'D') ||\n // Such as `bough`. The comma is not a bug.\n ((subvalue = characters[index - 3]),\n subvalue === 'B' || subvalue === 'H' || subvalue === 'D') ||\n // Such as `Broughton`. The comma is not a bug.\n ((subvalue = characters[index - 4]),\n subvalue === 'B' || subvalue === 'H')\n ) {\n index += 2\n\n break\n }\n\n // Such as `laugh`, `McLaughlin`, `cough`, `gough`, `rough`, `tough`.\n if (index > 2 && prev === 'U' && gForF.test(characters[index - 3])) {\n primary += 'F'\n secondary += 'F'\n } else if (index > 0 && prev !== 'I') {\n primary += 'K'\n secondary += 'K'\n }\n\n index += 2\n\n break\n }\n\n if (next === 'N') {\n if (index === 1 && vowels.test(characters[0]) && !isSlavoGermanic) {\n primary += 'KN'\n secondary += 'N'\n // Not like `Cagney`.\n } else if (\n value.slice(index + 2, index + 4) !== 'EY' &&\n value.slice(index + 1) !== 'Y' &&\n !isSlavoGermanic\n ) {\n primary += 'N'\n secondary += 'KN'\n } else {\n primary += 'KN'\n secondary += 'KN'\n }\n\n index += 2\n\n break\n }\n\n // Such as `Tagliaro`.\n if (value.slice(index + 1, index + 3) === 'LI' && !isSlavoGermanic) {\n primary += 'KL'\n secondary += 'L'\n index += 2\n\n break\n }\n\n // -ges-, -gep-, -gel- at beginning.\n if (index === 0 && initialGForKj.test(value.slice(1, 3))) {\n primary += 'K'\n secondary += 'J'\n index += 2\n\n break\n }\n\n // -ger-, -gy-.\n if (\n (value.slice(index + 1, index + 3) === 'ER' &&\n prev !== 'I' &&\n prev !== 'E' &&\n !initialAngerException.test(value.slice(0, 6))) ||\n (next === 'Y' && !gForKj.test(prev))\n ) {\n primary += 'K'\n secondary += 'J'\n index += 2\n\n break\n }\n\n // Italian such as `biaggi`.\n if (\n next === 'E' ||\n next === 'I' ||\n next === 'Y' ||\n ((prev === 'A' || prev === 'O') && next === 'G' && nextnext === 'I')\n ) {\n // Obvious Germanic.\n if (value.slice(index + 1, index + 3) === 'ET' || isGermanic) {\n primary += 'K'\n secondary += 'K'\n } else {\n primary += 'J'\n\n // Always soft if French ending.\n if (value.slice(index + 1, index + 5) === 'IER ') {\n secondary += 'J'\n } else {\n secondary += 'K'\n }\n }\n\n index += 2\n\n break\n }\n\n if (next === 'G') {\n index++\n }\n\n index++\n\n primary += 'K'\n secondary += 'K'\n\n break\n case 'H':\n // Only keep if first & before vowel or btw. 2 vowels.\n if (vowels.test(next) && (index === 0 || vowels.test(prev))) {\n primary += 'H'\n secondary += 'H'\n\n index++\n }\n\n index++\n\n break\n case 'J':\n // Obvious Spanish, `jose`, `San Jacinto`.\n if (\n value.slice(index, index + 4) === 'JOSE' ||\n value.slice(0, 4) === 'SAN '\n ) {\n if (\n value.slice(0, 4) === 'SAN ' ||\n (index === 0 && characters[index + 4] === ' ')\n ) {\n primary += 'H'\n secondary += 'H'\n } else {\n primary += 'J'\n secondary += 'H'\n }\n\n index++\n\n break\n }\n\n if (\n index === 0\n // Bug: unreachable (see previous statement).\n // && value.slice(index, index + 4) !== 'JOSE'.\n ) {\n primary += 'J'\n\n // Such as `Yankelovich` or `Jankelowicz`.\n secondary += 'A'\n // Spanish pron. of such as `bajador`.\n } else if (\n !isSlavoGermanic &&\n (next === 'A' || next === 'O') &&\n vowels.test(prev)\n ) {\n primary += 'J'\n secondary += 'H'\n } else if (index === last) {\n primary += 'J'\n } else if (\n prev !== 'S' &&\n prev !== 'K' &&\n prev !== 'L' &&\n !jForJException.test(next)\n ) {\n primary += 'J'\n secondary += 'J'\n // It could happen.\n } else if (next === 'J') {\n index++\n }\n\n index++\n\n break\n case 'K':\n if (next === 'K') {\n index++\n }\n\n primary += 'K'\n secondary += 'K'\n index++\n\n break\n case 'L':\n if (next === 'L') {\n // Spanish such as `cabrillo`, `gallegos`.\n if (\n (index === length - 3 &&\n ((prev === 'A' && nextnext === 'E') ||\n (prev === 'I' && (nextnext === 'O' || nextnext === 'A')))) ||\n (prev === 'A' &&\n nextnext === 'E' &&\n (characters[last] === 'A' ||\n characters[last] === 'O' ||\n alle.test(value.slice(last - 1, length))))\n ) {\n primary += 'L'\n index += 2\n\n break\n }\n\n index++\n }\n\n primary += 'L'\n secondary += 'L'\n index++\n\n break\n case 'M':\n if (\n next === 'M' ||\n // Such as `dumb`, `thumb`.\n (prev === 'U' &&\n next === 'B' &&\n (index + 1 === last || value.slice(index + 2, index + 4) === 'ER'))\n ) {\n index++\n }\n\n index++\n primary += 'M'\n secondary += 'M'\n\n break\n case 'N':\n if (next === 'N') {\n index++\n }\n\n index++\n primary += 'N'\n secondary += 'N'\n\n break\n case 'Ñ':\n index++\n primary += 'N'\n secondary += 'N'\n\n break\n case 'P':\n if (next === 'H') {\n primary += 'F'\n secondary += 'F'\n index += 2\n\n break\n }\n\n // Also account for `campbell` and `raspberry`.\n subvalue = next\n\n if (subvalue === 'P' || subvalue === 'B') {\n index++\n }\n\n index++\n\n primary += 'P'\n secondary += 'P'\n\n break\n case 'Q':\n if (next === 'Q') {\n index++\n }\n\n index++\n primary += 'K'\n secondary += 'K'\n\n break\n case 'R':\n // French such as `Rogier`, but exclude `Hochmeier`.\n if (\n index === last &&\n !isSlavoGermanic &&\n prev === 'E' &&\n characters[index - 2] === 'I' &&\n characters[index - 4] !== 'M' &&\n (characters[index - 3] !== 'E' && characters[index - 3] !== 'A')\n ) {\n secondary += 'R'\n } else {\n primary += 'R'\n secondary += 'R'\n }\n\n if (next === 'R') {\n index++\n }\n\n index++\n\n break\n case 'S':\n // Special cases `island`, `isle`, `carlisle`, `carlysle`.\n if (next === 'L' && (prev === 'I' || prev === 'Y')) {\n index++\n\n break\n }\n\n // Special case `sugar-`.\n if (index === 0 && value.slice(1, 5) === 'UGAR') {\n primary += 'X'\n secondary += 'S'\n index++\n\n break\n }\n\n if (next === 'H') {\n // Germanic.\n if (hForS.test(value.slice(index + 1, index + 5))) {\n primary += 'S'\n secondary += 'S'\n } else {\n primary += 'X'\n secondary += 'X'\n }\n\n index += 2\n break\n }\n\n if (\n next === 'I' &&\n (nextnext === 'O' || nextnext === 'A')\n // Bug: Already covered by previous branch\n // || value.slice(index, index + 4) === 'SIAN'\n ) {\n if (isSlavoGermanic) {\n primary += 'S'\n secondary += 'S'\n } else {\n primary += 'S'\n secondary += 'X'\n }\n\n index += 3\n\n break\n }\n\n // German & Anglicization's, such as `Smith` match `Schmidt`, `snider`\n // match `Schneider`. Also, -sz- in slavic language although in\n // hungarian it is pronounced `s`.\n if (\n next === 'Z' ||\n (index === 0 &&\n (next === 'L' || next === 'M' || next === 'N' || next === 'W'))\n ) {\n primary += 'S'\n secondary += 'X'\n\n if (next === 'Z') {\n index++\n }\n\n index++\n\n break\n }\n\n if (next === 'C') {\n // Schlesinger's rule.\n if (nextnext === 'H') {\n subvalue = value.slice(index + 3, index + 5)\n\n // Dutch origin, such as `school`, `schooner`.\n if (dutchSch.test(subvalue)) {\n // Such as `schermerhorn`, `schenker`.\n if (subvalue === 'ER' || subvalue === 'EN') {\n primary += 'X'\n secondary += 'SK'\n } else {\n primary += 'SK'\n secondary += 'SK'\n }\n\n index += 3\n\n break\n }\n\n if (\n index === 0 &&\n !vowels.test(characters[3]) &&\n characters[3] !== 'W'\n ) {\n primary += 'X'\n secondary += 'S'\n } else {\n primary += 'X'\n secondary += 'X'\n }\n\n index += 3\n\n break\n }\n\n if (nextnext === 'I' || nextnext === 'E' || nextnext === 'Y') {\n primary += 'S'\n secondary += 'S'\n index += 3\n break\n }\n\n primary += 'SK'\n secondary += 'SK'\n index += 3\n\n break\n }\n\n subvalue = value.slice(index - 2, index)\n\n // French such as `resnais`, `artois`.\n if (index === last && (subvalue === 'AI' || subvalue === 'OI')) {\n secondary += 'S'\n } else {\n primary += 'S'\n secondary += 'S'\n }\n\n if (\n next === 'S'\n // Bug: already taken care of by `German & Anglicization's` above:\n // || next === 'Z'\n ) {\n index++\n }\n\n index++\n\n break\n case 'T':\n if (next === 'I' && nextnext === 'O' && characters[index + 3] === 'N') {\n primary += 'X'\n secondary += 'X'\n index += 3\n\n break\n }\n\n subvalue = value.slice(index + 1, index + 3)\n\n if (\n (next === 'I' && nextnext === 'A') ||\n (next === 'C' && nextnext === 'H')\n ) {\n primary += 'X'\n secondary += 'X'\n index += 3\n\n break\n }\n\n if (next === 'H' || (next === 'T' && nextnext === 'H')) {\n // Special case `Thomas`, `Thames` or Germanic.\n if (\n isGermanic ||\n ((nextnext === 'O' || nextnext === 'A') &&\n characters[index + 3] === 'M')\n ) {\n primary += 'T'\n secondary += 'T'\n } else {\n primary += '0'\n secondary += 'T'\n }\n\n index += 2\n\n break\n }\n\n if (next === 'T' || next === 'D') {\n index++\n }\n\n index++\n primary += 'T'\n secondary += 'T'\n\n break\n case 'V':\n if (next === 'V') {\n index++\n }\n\n primary += 'F'\n secondary += 'F'\n index++\n\n break\n case 'W':\n // Can also be in middle of word (as already taken care of for initial).\n if (next === 'R') {\n primary += 'R'\n secondary += 'R'\n index += 2\n\n break\n }\n\n if (index === 0) {\n // `Wasserman` should match `Vasserman`.\n if (vowels.test(next)) {\n primary += 'A'\n secondary += 'F'\n } else if (next === 'H') {\n // Need `Uomo` to match `Womo`.\n primary += 'A'\n secondary += 'A'\n }\n }\n\n // `Arnow` should match `Arnoff`.\n if (\n ((prev === 'E' || prev === 'O') &&\n next === 'S' &&\n nextnext === 'K' &&\n (characters[index + 3] === 'I' || characters[index + 3] === 'Y')) ||\n // Maybe a bug? Shouldn't this be general Germanic?\n value.slice(0, 3) === 'SCH' ||\n (index === last && vowels.test(prev))\n ) {\n secondary += 'F'\n index++\n\n break\n }\n\n // Polish such as `Filipowicz`.\n if (\n next === 'I' &&\n (nextnext === 'C' || nextnext === 'T') &&\n characters[index + 3] === 'Z'\n ) {\n primary += 'TS'\n secondary += 'FX'\n index += 4\n\n break\n }\n\n index++\n\n break\n case 'X':\n // French such as `breaux`.\n if (\n !(\n index === last &&\n // Bug: IAU and EAU also match by AU\n // (/IAU|EAU/.test(value.slice(index - 3, index))) ||\n (prev === 'U' &&\n (characters[index - 2] === 'A' || characters[index - 2] === 'O'))\n )\n ) {\n primary += 'KS'\n secondary += 'KS'\n }\n\n if (next === 'C' || next === 'X') {\n index++\n }\n\n index++\n\n break\n case 'Z':\n // Chinese pinyin such as `Zhao`.\n if (next === 'H') {\n primary += 'J'\n secondary += 'J'\n index += 2\n\n break\n } else if (\n (next === 'Z' &&\n (nextnext === 'A' || nextnext === 'I' || nextnext === 'O')) ||\n (isSlavoGermanic && index > 0 && prev !== 'T')\n ) {\n primary += 'S'\n secondary += 'TS'\n } else {\n primary += 'S'\n secondary += 'S'\n }\n\n if (next === 'Z') {\n index++\n }\n\n index++\n\n break\n default:\n index++\n }\n }\n\n return [primary, secondary]\n}", "getAltHintFromLine(line, hint, start, end) {\nlet i;\nlet chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789.';\nlet altHint = hint;\nlet ch;\nif ((start > 0) && (line[start - 1] === '.')) {\ni = start - 1;\nwhile ((i > 0) && (chars.indexOf(line[i]) !== -1)) {\nch = line[i--];\naltHint = (ch === '.' ? '~' : ch) + altHint;\n}\n}\nif ((end < line.length) && (line[end] === '.')) {\nlet i = end;\nwhile ((i < line.length) && (chars.indexOf(line[i]) !== -1)) {\nch = line[i++];\naltHint += (ch === '.' ? '~' : ch);\n}\n}\nreturn altHint;\n}", "function NzExtendedMark() { }", "function ddSign(f) {\n return f[1];\n}", "function __doubleMetaphone(value) {\n var primary = '',\n secondary = '',\n index = 0,\n length = value.length,\n last = length - 1,\n isSlavoGermanic = SLAVO_GERMANIC.test(value),\n isGermanic = GERMANIC.test(value),\n characters = value.split(''),\n subvalue,\n next,\n prev,\n nextnext;\n\n value = String(value).toUpperCase() + ' ';\n\n // Skip this at beginning of word.\n if (INITIAL_EXCEPTIONS.test(value))\n index++;\n\n // Initial X is pronounced Z, which maps to S. Such as `Xavier`\n if (characters[0] === 'X') {\n primary += 'S';\n secondary += 'S';\n\n index++;\n }\n\n while (index < length) {\n prev = characters[index - 1];\n next = characters[index + 1];\n nextnext = characters[index + 2];\n\n switch (characters[index]) {\n case 'A':\n case 'E':\n case 'I':\n case 'O':\n case 'U':\n case 'Y':\n case 'À':\n case 'Ê':\n case 'É':\n case 'É':\n if (index === 0) {\n // All initial vowels now map to `A`.\n primary += 'A';\n secondary += 'A';\n }\n\n index++;\n\n break;\n case 'B':\n primary += 'P';\n secondary += 'P';\n\n if (next === 'B')\n index++;\n\n index++;\n\n break;\n case 'Ç':\n primary += 'S';\n secondary += 'S';\n index++;\n\n break;\n case 'C':\n // Various Germanic:\n if (prev === 'A' &&\n next === 'H' &&\n nextnext !== 'I' &&\n !VOWELS.test(characters[index - 2]) &&\n (nextnext !== 'E' || (subvalue = value.slice(index - 2, index + 4) &&\n (subvalue === 'BACHER' || subvalue === 'MACHER')))\n ) {\n primary += 'K';\n secondary += 'K';\n index += 2;\n\n break;\n }\n\n // Special case for `Caesar`.\n if (index === 0 && value.slice(index + 1, index + 6) === 'AESAR') {\n primary += 'S';\n secondary += 'S';\n index += 2;\n\n break;\n }\n\n // Italian `Chianti`.\n if (value.slice(index + 1, index + 4) === 'HIA') {\n primary += 'K';\n secondary += 'K';\n index += 2;\n\n break;\n }\n\n if (next === 'H') {\n // Find `Michael`.\n if (index > 0 && nextnext === 'A' && characters[index + 3] === 'E') {\n primary += 'K';\n secondary += 'X';\n index += 2;\n\n break;\n }\n\n // Greek roots such as `chemistry`, `chorus`.\n if (index === 0 && GREEK_INITIAL_CH.test(value)) {\n primary += 'K';\n secondary += 'K';\n index += 2;\n\n break;\n }\n\n // Germanic, Greek, or otherwise `CH` for `KH` sound.\n if (isGermanic ||\n // Such as 'architect' but not 'arch', orchestra', 'orchid'.\n GREEK_CH.test(value.slice(index - 2, index + 4)) ||\n (nextnext === 'T' || nextnext === 'S') ||\n ((index === 0 ||\n prev === 'A' ||\n prev === 'E' ||\n prev === 'O' ||\n prev === 'U') &&\n // Such as `wachtler`, `weschsler`, but not `tichner`.\n CH_FOR_KH.test(nextnext))\n ) {\n primary += 'K';\n secondary += 'K';\n } else if (index === 0) {\n primary += 'X';\n secondary += 'X';\n } else if (value.slice(0, 2) === 'MC') { // Such as 'McHugh'.\n // Bug? Why matching absolute? what about McHiccup?\n primary += 'K';\n secondary += 'K';\n } else {\n primary += 'X';\n secondary += 'K';\n }\n\n index += 2;\n\n break;\n }\n\n // Such as `Czerny`.\n if (next === 'Z' && value.slice(index - 2, index) !== 'WI') {\n primary += 'S';\n secondary += 'X';\n index += 2;\n\n break;\n }\n\n // Such as `Focaccia`.\n if (value.slice(index + 1, index + 4) === 'CIA') {\n primary += 'X';\n secondary += 'X';\n index += 3;\n\n break;\n }\n\n // Double `C`, but not `McClellan`.\n if (next === 'C' && !(index === 1 && characters[0] === 'M')) {\n // Such as `Bellocchio`, but not `Bacchus`.\n if ((nextnext === 'I' ||\n nextnext === 'E' ||\n nextnext === 'H') &&\n value.slice(index + 2, index + 4) !== 'HU'\n ) {\n subvalue = value.slice(index - 1, index + 4);\n\n // Such as `Accident`, `Accede`, `Succeed`.\n if ((index === 1 && prev === 'A') || subvalue === 'UCCEE' || subvalue === 'UCCES') {\n primary += 'KS';\n secondary += 'KS';\n } else { // Such as `Bacci`, `Bertucci`, other Italian.\n primary += 'X';\n secondary += 'X';\n }\n\n index += 3;\n\n break;\n } else {\n // Pierce's rule.\n primary += 'K';\n secondary += 'K';\n index += 2;\n\n break;\n }\n }\n\n if (next === 'G' || next === 'K' || next === 'Q') {\n primary += 'K';\n secondary += 'K';\n index += 2;\n\n break;\n }\n\n // Italian.\n if (next === 'I' && (nextnext === 'A' || nextnext === 'E' || nextnext === 'O')) {\n primary += 'S';\n secondary += 'X';\n index += 2;\n\n break;\n }\n\n if (next === 'I' || next === 'E' || next === 'Y') {\n primary += 'S';\n secondary += 'S';\n index += 2;\n\n break;\n }\n\n primary += 'K';\n secondary += 'K';\n\n // Skip two extra characters ahead in `Mac Caffrey`, `Mac Gregor`.\n if (next === ' ' && (nextnext === 'C' || nextnext === 'G' || nextnext === 'Q')) {\n index += 3;\n break;\n }\n\n if (next === 'K' || next === 'Q' || (next === 'C' && nextnext !== 'E' && nextnext !== 'I'))\n index++;\n\n index++;\n\n break;\n case 'D':\n if (next === 'G') {\n // Such as `edge`.\n if (nextnext === 'E' || nextnext === 'I' || nextnext === 'Y') {\n primary += 'J';\n secondary += 'J';\n index += 3;\n } else { // Such as `Edgar`.\n primary += 'TK';\n secondary += 'TK';\n index += 2;\n }\n\n break;\n }\n\n if (next === 'T' || next === 'D') {\n primary += 'T';\n secondary += 'T';\n index += 2;\n\n break;\n }\n\n primary += 'T';\n secondary += 'T';\n index++;\n\n break;\n case 'F':\n if (next === 'F')\n index++;\n\n index++;\n primary += 'F';\n secondary += 'F';\n\n break;\n case 'G':\n if (next === 'H') {\n if (index > 0 && !VOWELS.test(prev)) {\n primary += 'K';\n secondary += 'K';\n index += 2;\n\n break;\n }\n\n // Such as `Ghislane`, `Ghiradelli`.\n if (index === 0) {\n if (nextnext === 'I') {\n primary += 'J';\n secondary += 'J';\n } else {\n primary += 'K';\n secondary += 'K';\n }\n index += 2;\n break;\n }\n\n // Parker's rule (with some further refinements).\n if ((// Such as `Hugh`\n subvalue = characters[index - 2],\n subvalue === 'B' ||\n subvalue === 'H' ||\n subvalue === 'D'\n ) ||\n (// Such as `bough`.\n subvalue = characters[index - 3],\n subvalue === 'B' ||\n subvalue === 'H' ||\n subvalue === 'D'\n ) ||\n (// Such as `Broughton`.\n subvalue = characters[index - 4],\n subvalue === 'B' ||\n subvalue === 'H'\n )\n ) {\n index += 2;\n\n break;\n }\n\n // Such as `laugh`, `McLaughlin`, `cough`, `gough`, `rough`, `tough`.\n if (index > 2 && prev === 'U' && G_FOR_F.test(characters[index - 3])) {\n primary += 'F';\n secondary += 'F';\n } else if (index > 0 && prev !== 'I') {\n primary += 'K';\n secondary += 'K';\n }\n\n index += 2;\n\n break;\n }\n\n if (next === 'N') {\n if (index === 1 && VOWELS.test(characters[0]) && !isSlavoGermanic) {\n primary += 'KN';\n secondary += 'N';\n } else if (\n // Not like `Cagney`.\n value.slice(index + 2, index + 4) !== 'EY' &&\n value.slice(index + 1) !== 'Y' &&\n !isSlavoGermanic\n ) {\n primary += 'N';\n secondary += 'KN';\n } else {\n primary += 'KN';\n secondary += 'KN';\n }\n\n index += 2;\n\n break;\n }\n\n //Such as `Tagliaro`.\n if (value.slice(index + 1, index + 3) === 'LI' && !isSlavoGermanic) {\n primary += 'KL';\n secondary += 'L';\n index += 2;\n\n break;\n }\n\n // -ges-, -gep-, -gel- at beginning.\n if (index === 0 && INITIAL_G_FOR_KJ.test(value.slice(1, 3))) {\n primary += 'K';\n secondary += 'J';\n index += 2;\n\n break;\n }\n\n // -ger-, -gy-.\n if ((value.slice(index + 1, index + 3) === 'ER' &&\n prev !== 'I' && prev !== 'E' &&\n !INITIAL_ANGER_EXCEPTION.test(value.slice(0, 6))\n ) ||\n (next === 'Y' && !G_FOR_KJ.test(prev))\n ) {\n primary += 'K';\n secondary += 'J';\n index += 2;\n\n break;\n }\n\n // Italian such as `biaggi`.\n if (next === 'E' || next === 'I' || next === 'Y' || (\n (prev === 'A' || prev === 'O') &&\n next === 'G' && nextnext === 'I'\n )\n ) {\n // Obvious Germanic.\n if (value.slice(index + 1, index + 3) === 'ET' || isGermanic) {\n primary += 'K';\n secondary += 'K';\n } else {\n // Always soft if French ending.\n if (value.slice(index + 1, index + 5) === 'IER ') {\n primary += 'J';\n secondary += 'J';\n } else {\n primary += 'J';\n secondary += 'K';\n }\n }\n\n index += 2;\n\n break;\n }\n\n if (next === 'G')\n index++;\n\n index++;\n\n primary += 'K';\n secondary += 'K';\n\n break;\n case 'H':\n // Only keep if first & before vowel or btw. 2 vowels.\n if (VOWELS.test(next) && (index === 0 || VOWELS.test(prev))) {\n primary += 'H';\n secondary += 'H';\n\n index++;\n }\n\n index++;\n\n break;\n case 'J':\n // Obvious Spanish, `jose`, `San Jacinto`.\n if (value.slice(index, index + 4) === 'JOSE' || value.slice(0, 4) === 'SAN ') {\n if (value.slice(0, 4) === 'SAN ' || (index === 0 && characters[index + 4] === ' ')) {\n primary += 'H';\n secondary += 'H';\n } else {\n primary += 'J';\n secondary += 'H';\n }\n\n index++;\n\n break;\n }\n\n if (index === 0) {\n // Such as `Yankelovich` or `Jankelowicz`.\n primary += 'J';\n secondary += 'A';\n } else if (// Spanish pron. of such as `bajador`.\n !isSlavoGermanic &&\n (next === 'A' || next === 'O') &&\n VOWELS.test(prev)\n ) {\n primary += 'J';\n secondary += 'H';\n } else if (index === last) {\n primary += 'J';\n } else if (prev !== 'S' && prev !== 'K' && prev !== 'L' && !J_FOR_J_EXCEPTION.test(next)) {\n primary += 'J';\n secondary += 'J';\n } else if (next === 'J') {\n index++;\n }\n\n index++;\n\n break;\n case 'K':\n if (next === 'K')\n index++;\n\n primary += 'K';\n secondary += 'K';\n index++;\n\n break;\n case 'L':\n if (next === 'L') {\n // Spanish such as `cabrillo`, `gallegos`.\n if ((index === length - 3 && ((\n prev === 'I' && (\n nextnext === 'O' || nextnext === 'A'\n )\n ) || (\n prev === 'A' && nextnext === 'E'\n )\n )) || (\n prev === 'A' && nextnext === 'E' && ((\n characters[last] === 'A' || characters[last] === 'O'\n ) || ALLE.test(value.slice(last - 1, length))\n )\n )\n ) {\n primary += 'L';\n index += 2;\n\n break;\n }\n\n index++;\n }\n\n primary += 'L';\n secondary += 'L';\n index++;\n\n break;\n case 'M':\n // Such as `dumb`, `thumb`.\n if (next === 'M' || (\n prev === 'U' && next === 'B' && (\n index + 1 === last || value.slice(index + 2, index + 4) === 'ER')\n )\n ) {\n index++;\n }\n\n index++;\n primary += 'M';\n secondary += 'M';\n\n break;\n case 'N':\n if (next === 'N')\n index++;\n\n index++;\n primary += 'N';\n secondary += 'N';\n\n break;\n case 'Ñ':\n index++;\n primary += 'N';\n secondary += 'N';\n\n break;\n case 'P':\n if (next === 'H') {\n primary += 'F';\n secondary += 'F';\n index += 2;\n\n break;\n }\n\n // Also account for `campbell` and `raspberry`.\n subvalue = next;\n\n if (subvalue === 'P' || subvalue === 'B')\n index++;\n\n index++;\n\n primary += 'P';\n secondary += 'P';\n\n break;\n case 'Q':\n if (next === 'Q') {\n index++;\n }\n\n index++;\n primary += 'K';\n secondary += 'K';\n\n break;\n case 'R':\n // French such as `Rogier`, but exclude `Hochmeier`.\n if (index === last &&\n !isSlavoGermanic &&\n prev === 'E' &&\n characters[index - 2] === 'I' &&\n characters[index - 4] !== 'M' && (\n characters[index - 3] !== 'E' &&\n characters[index - 3] !== 'A'\n )\n ) {\n secondary += 'R';\n } else {\n primary += 'R';\n secondary += 'R';\n }\n\n if (next === 'R')\n index++;\n\n index++;\n\n break;\n case 'S':\n // Special cases `island`, `isle`, `carlisle`, `carlysle`.\n if (next === 'L' && (prev === 'I' || prev === 'Y')) {\n index++;\n\n break;\n }\n\n // Special case `sugar-`.\n if (index === 0 && value.slice(1, 5) === 'UGAR') {\n primary += 'X';\n secondary += 'S';\n index++;\n\n break;\n }\n\n if (next === 'H') {\n // Germanic.\n if (H_FOR_S.test(value.slice(index + 1, index + 5))) {\n primary += 'S';\n secondary += 'S';\n } else {\n primary += 'X';\n secondary += 'X';\n }\n\n index += 2;\n break;\n }\n\n if (next === 'I' && (nextnext === 'O' || nextnext === 'A')) {\n if (!isSlavoGermanic) {\n primary += 'S';\n secondary += 'X';\n } else {\n primary += 'S';\n secondary += 'S';\n }\n\n index += 3;\n\n break;\n }\n\n /*\n * German & Anglicization's, such as `Smith` match `Schmidt`,\n * `snider` match `Schneider`. Also, -sz- in slavic language\n * although in hungarian it is pronounced `s`.\n */\n if (next === 'Z' || (\n index === 0 && (\n next === 'L' || next === 'M' || next === 'N' || next === 'W'\n )\n )\n ) {\n primary += 'S';\n secondary += 'X';\n\n if (next === 'Z')\n index++;\n\n index++;\n\n break;\n }\n\n if (next === 'C') {\n // Schlesinger's rule.\n if (nextnext === 'H') {\n subvalue = value.slice(index + 3, index + 5);\n\n // Dutch origin, such as `school`, `schooner`.\n if (DUTCH_SCH.test(subvalue)) {\n // Such as `schermerhorn`, `schenker`.\n if (subvalue === 'ER' || subvalue === 'EN') {\n primary += 'X';\n secondary += 'SK';\n } else {\n primary += 'SK';\n secondary += 'SK';\n }\n\n index += 3;\n\n break;\n }\n\n if (index === 0 && !VOWELS.test(characters[3]) && characters[3] !== 'W') {\n primary += 'X';\n secondary += 'S';\n } else {\n primary += 'X';\n secondary += 'X';\n }\n\n index += 3;\n\n break;\n }\n\n if (nextnext === 'I' || nextnext === 'E' || nextnext === 'Y') {\n primary += 'S';\n secondary += 'S';\n index += 3;\n break;\n }\n\n primary += 'SK';\n secondary += 'SK';\n index += 3;\n\n break;\n }\n\n subvalue = value.slice(index - 2, index);\n\n // French such as `resnais`, `artois`.\n if (index === last && (subvalue === 'AI' || subvalue === 'OI')) {\n secondary += 'S';\n } else {\n primary += 'S';\n secondary += 'S';\n }\n\n if (next === 'S' || next === 'Z')\n index++;\n\n index++;\n\n break;\n case 'T':\n if (next === 'I' && nextnext === 'O' && characters[index + 3] === 'N') {\n primary += 'X';\n secondary += 'X';\n index += 3;\n\n break;\n }\n\n subvalue = value.slice(index + 1, index + 3);\n\n if ((next === 'I' && nextnext === 'A') || (next === 'C' && nextnext === 'H')) {\n primary += 'X';\n secondary += 'X';\n index += 3;\n\n break;\n }\n\n if (next === 'H' || (next === 'T' && nextnext === 'H')) {\n // Special case `Thomas`, `Thames` or Germanic.\n if (isGermanic || ((nextnext === 'O' || nextnext === 'A') && characters[index + 3] === 'M')) {\n primary += 'T';\n secondary += 'T';\n } else {\n primary += '0';\n secondary += 'T';\n }\n\n index += 2;\n\n break;\n }\n\n if (next === 'T' || next === 'D')\n index++;\n\n index++;\n primary += 'T';\n secondary += 'T';\n\n break;\n case 'V':\n if (next === 'V')\n index++;\n\n primary += 'F';\n secondary += 'F';\n index++;\n\n break;\n case 'W':\n // Can also be in middle of word (as already taken care of for initial).\n if (next === 'R') {\n primary += 'R';\n secondary += 'R';\n index += 2;\n\n break;\n }\n\n if (index === 0) {\n // `Wasserman` should match `Vasserman`.\n if (VOWELS.test(next)) {\n primary += 'A';\n secondary += 'F';\n } else if (next === 'H') {\n // Need `Uomo` to match `Womo`.\n primary += 'A';\n secondary += 'A';\n }\n }\n\n // `Arnow` should match `Arnoff`.\n if (((prev === 'E' || prev === 'O') &&\n next === 'S' && nextnext === 'K' && (\n characters[index + 3] === 'I' ||\n characters[index + 3] === 'Y'\n )\n ) || value.slice(0, 3) === 'SCH' || (index === last && VOWELS.test(prev))\n ) {\n secondary += 'F';\n index++;\n\n break;\n }\n\n // Polish such as `Filipowicz`.\n if (next === 'I' && (nextnext === 'C' || nextnext === 'T') && characters[index + 3] === 'Z') {\n primary += 'TS';\n secondary += 'FX';\n index += 4;\n\n break;\n }\n\n index++;\n\n break;\n case 'X':\n // French such as `breaux`.\n if (index === last || (prev === 'U' && (\n characters[index - 2] === 'A' ||\n characters[index - 2] === 'O'\n ))\n ) {\n primary += 'KS';\n secondary += 'KS';\n }\n\n if (next === 'C' || next === 'X')\n index++;\n\n index++;\n\n break;\n case 'Z':\n // Chinese pinyin such as `Zhao`.\n if (next === 'H') {\n primary += 'J';\n secondary += 'J';\n index += 2;\n\n break;\n } else if ((next === 'Z' && (\n nextnext === 'A' || nextnext === 'I' || nextnext === 'O'\n )) || (\n isSlavoGermanic && index > 0 && prev !== 'T'\n )\n ) {\n primary += 'S';\n secondary += 'TS';\n } else {\n primary += 'S';\n secondary += 'S';\n }\n\n if (next === 'Z')\n index++;\n\n index++;\n\n break;\n default:\n index++;\n\n }\n }\n\n return [primary, secondary];\n }", "function GetBornosoftModifiedCharaceter(CUni)\r\n{\r\n\tvar CMod=CUni;\r\n\r\n\tif(LCUNI=='ক' && CUni=='হ') CMod = 'খ';\r\n\telse if(LCUNI=='গ' && CUni=='হ') CMod = 'ঘ';\r\n\telse if(LCUNI=='চ' && CUni=='হ') CMod = 'চ';\r\n\telse if(LCUNI=='জ' && CUni=='হ') CMod = 'ঝ';\r\n\telse if(LCUNI=='ট' && CUni=='হ') CMod = 'ঠ';\r\n\telse if(LCUNI=='ড' && CUni=='হ') CMod = 'ঢ';\r\n\telse if(LCUNI=='ত' && CUni=='হ') CMod = 'থ';\r\n\telse if(LCUNI=='দ' && CUni=='হ') CMod = 'ধ';\r\n\telse if(LCUNI=='প' && CUni=='হ') CMod = 'ফ';\r\n\telse if(LCUNI=='ব' && CUni=='হ') CMod = 'ভ';\r\n\telse if(LCUNI=='স' && CUni=='হ') CMod = 'শ';\r\n\telse if(LCUNI=='ড়' && CUni=='হ') CMod = 'ঢ়';\r\n\r\n\telse if(LCUNI=='ণ' && CUni=='গ') CMod = 'ঙ';\r\n\telse if(LCUNI=='ন' && CUni=='গ') CMod = 'ং';\r\n\t\r\n\telse if(LCUNI=='ণ' && CUni=='ঘ') CMod = 'ঞ';\r\n\r\n\telse if(LCUNI=='ণ' && CUni=='ণ') CMod = 'ঁ';\r\n\r\n\telse if(LCUNI=='ঃ' && CUni=='ঃ') CMod = 'ঃ';\r\n\t\r\n\telse if(LCUNI=='ট' && CUni=='ট') CMod = 'ৎ';\r\n\t\r\n\telse if(LCUNI=='া' && CUni=='ো') CMod = 'অ';\r\n\telse if(LCUNI=='ি' && CUni=='ি') CMod = 'ী';\r\n\telse if(LCUNI=='ই' && CUni=='ই') CMod = 'ঈ';\r\n\telse if(LCUNI=='ু' && CUni=='ু') CMod = 'ূ';\r\n\telse if(LCUNI=='উ' && CUni=='উ') CMod = 'ঊ';\r\n\telse if(LCUNI=='ও' && CUni=='ই') CMod = 'ঐ';\r\n\telse if(LCUNI=='ো' && CUni=='ি') CMod = 'ৈ';\r\n\telse if(LCUNI=='ও' && CUni=='উ') CMod = 'ঔ';\r\n\telse if(LCUNI=='ো' && CUni=='ু') CMod = 'ৌ';\r\n\telse if(LCUNI=='ৃ' && CUni=='র') CMod = 'ৃ';\r\n\telse if(LCUNI=='ঋ' && CUni=='ড়') CMod = 'ঋ';\r\n\r\n\treturn CMod;\r\n}", "function translate$3(number,withoutSuffix,key){var result=number + ' ';switch(key){case 'ss':if(number === 1){result += 'sekunda';}else if(number === 2 || number === 3 || number === 4){result += 'sekunde';}else {result += 'sekundi';}return result;case 'm':return withoutSuffix?'jedna minuta':'jedne minute';case 'mm':if(number === 1){result += 'minuta';}else if(number === 2 || number === 3 || number === 4){result += 'minute';}else {result += 'minuta';}return result;case 'h':return withoutSuffix?'jedan sat':'jednog sata';case 'hh':if(number === 1){result += 'sat';}else if(number === 2 || number === 3 || number === 4){result += 'sata';}else {result += 'sati';}return result;case 'dd':if(number === 1){result += 'dan';}else {result += 'dana';}return result;case 'MM':if(number === 1){result += 'mjesec';}else if(number === 2 || number === 3 || number === 4){result += 'mjeseca';}else {result += 'mjeseci';}return result;case 'yy':if(number === 1){result += 'godina';}else if(number === 2 || number === 3 || number === 4){result += 'godine';}else {result += 'godina';}return result;}}", "function e(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function a(e,a,t,n){switch(t){case\"s\":return a?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(a?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(a?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(a?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(a?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(a?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(a?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n){var i={mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"};return e+\" \"+a(i[n],e)}", "function t(e,t,n){var i={mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"};return e+\" \"+a(i[n],e)}", "function t(e,t,n){var i={mm:\"munutenn\",MM:\"miz\",dd:\"devezh\"};return e+\" \"+a(i[n],e)}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}" ]
[ "0.61835456", "0.6115167", "0.58595675", "0.57735646", "0.5762797", "0.5756832", "0.5739361", "0.57145274", "0.55978703", "0.5582833", "0.553381", "0.55188006", "0.5515095", "0.5513158", "0.5513158", "0.5513158", "0.55076826", "0.55005306", "0.5477976", "0.5473025", "0.54446757", "0.5432182", "0.5394412", "0.5391219", "0.5385259", "0.53755146", "0.5374031", "0.53556484", "0.53553295", "0.53320014", "0.53320014", "0.53320014", "0.53320014", "0.53320014", "0.53320014", "0.53320014", "0.53320014", "0.53320014", "0.53320014", "0.5325528", "0.53154737", "0.53129226", "0.5311018", "0.5306994", "0.5300679", "0.52957046", "0.5292431", "0.5285484", "0.52772117", "0.52608234", "0.5252534", "0.5246065", "0.5243952", "0.52316135", "0.5230023", "0.52252525", "0.5221372", "0.52172434", "0.52172434", "0.52172434", "0.52172434", "0.52172434", "0.52172434", "0.52172434", "0.52172434", "0.52172434", "0.52172434", "0.52172434", "0.52172434", "0.52172434", "0.52172434", "0.52172434", "0.52172434", "0.52172434", "0.52172434", "0.52172434", "0.52172434", "0.5213374", "0.5211873", "0.5208886", "0.5204248", "0.5203328", "0.5188089", "0.51798695", "0.51640975", "0.51398355", "0.5131047", "0.5119931", "0.5115681", "0.5115681", "0.5115681", "0.5112574", "0.5112574", "0.5112574", "0.5112574", "0.5112574", "0.5112574", "0.5112574", "0.5112574", "0.5112574" ]
0.67878103
0
Hapus Derivation Prefix ("di", "ke", "se", "te", "be", "me", atau "pe")
function Del_Derivation_Prefix(kata,selesai){ var kataAsal = kata; var __kata,__kata__="" /* —— Tentukan Tipe Awalan ————*/ if(kata.match(/^(di|[ks]e)/)){ // Jika di-,ke-,se- __kata = kata.replace(/^(di|[ks]e)/,''); cekKamus(__kata,function(data){ if(data){ selesai(__kata) }else{ Del_Derivation_Suffixes(__kata,function(data){ __kata__=data cekKamus(__kata__,function(data){ if(data){ selesai(__kata__) }else if(kata.match(/^(diper)/)){ //diper- __kata = kata.replace(/^(diper)/,''); Del_Derivation_Suffixes(__kata,function(data){ __kata__=data cekKamus(__kata__,function(data){ if(data){ selesai(__kata__) }else{ selesai(kataAsal) } }) }); }else if(kata.match(/^(ke[bt]er)/)){ //keber- dan keter- __kata = kata.replace(/^(ke[bt]er)/,''); Del_Derivation_Suffixes(__kata,function(data){ __kata__=data cekKamus(__kata__,function(data){ if(data){ selesai(__kata__) }else{ selesai(kataAsal) } }) }); } else{ selesai(kata.replace(/^(di|[ks]e)/,'')) } }) }) } }) }else if(kata.match(/^([bt]e)/)){ //Jika awalannya adalah "te-","ter-", "be-","ber-" __kata = kata.replace(/^([bt]e)/,''); cekKamus(__kata,function(data){ if(data){ selesai(__kata) }else{ __kata = kata.replace(/^([bt]e[lr])/,''); cekKamus(__kata,function(data){ if(data){ selesai(__kata) }else{ Del_Derivation_Suffixes(__kata,function(data){ __kata__=data cekKamus(__kata__,function(data){ if(data){ selesai(__kata__) }else{ selesai(kataAsal) } }) })} })} }); }else if(kata.match(/^([mp]e)/)){ __kata = kata.replace(/^([mp]e)/,''); cekKamus(__kata,function(data){ if(data){ selesai(__kata) }else Del_Derivation_Suffixes(__kata,function(data){ __kata__=data cekKamus(__kata__,function(data){ if(data){ selesai(__kata__) }else if(kata.match(/^(memper)/)){ __kata = kata.replace(/^(memper)/,''); cekKamus(__kata,function(data){ if(data){ selesai(__kata) }else{ Del_Derivation_Suffixes(__kata,function(data){ __kata__=data cekKamus(__kata__,function(data){ if(data){ selesai(__kata__) }else{ selesai(kataAsal) } }) })} }) }else if(kata.match(/^([mp]eng)/)){ __kata = kata.replace(/^([mp]eng)/,''); cekKamus(__kata,function(data1){ if(data1){ selesai(__kata) }else{ Del_Derivation_Suffixes(__kata,function(data2){ __kata__=data2 cekKamus(__kata__,function(data3){ if(data3){ selesai(__kata__) }else{ __kata = kata.replace(/^([mp]eng)/,'k'); cekKamus(__kata,function(data4){ if(data4){ selesai(__kata) }else{ Del_Derivation_Suffixes(__kata,function(data5){ __kata__ =data5 cekKamus(__kata__,function(data6){ if(data6){ selesai(__kata__) }else{ __kata = kata.replace(/^([mp]enge)/,'');//menge- dan penge- cekKamus(__kata,function(data4){ if(data4){ selesai(__kata) }else{ Del_Derivation_Suffixes(__kata,function(data5){ __kata__ =data5 cekKamus(__kata__,function(data6){ if(data6){ selesai(__kata__) }else{ selesai(kataAsal) } }) }); } }) } }) }); } }) } }) });} }) }else if(kata.match(/^([mp]eny)/)){ __kata = kata.replace(/^([mp]eny)/,'s'); cekKamus(__kata,function(data){ if(data){ selesai(__kata) }else{ Del_Derivation_Suffixes(__kata,function(data){ __kata__ =data cekKamus(__kata__,function(data){ if(data){ selesai(__kata__) }else{ selesai(kataAsal) } }) });} }) }else if(kata.match(/^([mp]e[lr])/)){ __kata = kata.replace(/^([mp]e[lr])/,''); cekKamus(__kata,function(data){ if(data){ selesai(__kata) }else{ Del_Derivation_Suffixes(__kata,function(data){ __kata__ =data cekKamus(__kata__,function(data){ if(data){ selesai(__kata__) }else{ selesai(kataAsal) } }) })} }) }else if(kata.match(/^([mp]en)/)){ __kata = kata.replace(/^([mp]en)/,'t'); cekKamus(__kata,function(data){ if(data){ selesai(__kata) }else{ Del_Derivation_Suffixes(__kata,function(data){ __kata__ =data cekKamus(__kata__,function(data){ if(data){ selesai(__kata__) }else{ __kata = kata.replace(/^([mp]en)/,''); cekKamus(__kata,function(data){ if(data){ selesai(__kata) }else { Del_Derivation_Suffixes(__kata,function(data){ __kata__ = data cekKamus(__kata__,function(data){ if(data){ selesai(__kata__) }else{ selesai(kataAsal) } }) });} })} }) });} }) }else if(kata.match(/^([mp]em)/)){ __kata = kata.replace(/^([mp]em)/,''); cekKamus(__kata,function(data){ if(data){ selesai(__kata) }else{ Del_Derivation_Suffixes(__kata,function(data){ __kata__ = data cekKamus(__kata__,function(data){ if(data){ selesai(__kata__) }else{ __kata = kata.replace(/^([mp]em)/,'p'); cekKamus(__kata,function(data){ if(data){ selesai(__kata) }else{ Del_Derivation_Suffixes(__kata,function(data){ __kata__ = data cekKamus(__kata__,function(data){ if(data){ selesai(__kata__) }else{ selesai(kataAsal) } }) });} })} }) });} }) } }) }); }) }else{ selesai(kataAsal) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getDerivacaoAFND(der, terminal){\n while(der.charAt(0) != \"}\"){\n /**\n * IGUAL AO FND\n */\n var regra = \"([a-zA-Z]|[0-9]|_)\\\\:\\\\[\";\n var reg = new RegExp(regra);\n var letra = der.match(reg);\n if(letra[1] == \"_\") letra[1] = \"\";\n der = der.replace(reg, \"\");\n /**\n * TRATAR COLCHETES\n */\n while(der.charAt(0) != ']'){\n regra = \"([a-z][0-9][0-9]*)\";\n reg = new RegExp(regra);\n var derivacao = der.match(reg);\n der = der.replace(reg, \"\");\n if(der.charAt(0) == ',' || der.charAt(0) == '{') der = der.substring(1 , der.length); \n addTabela(numParaLetra(terminal), (letra[1] + numParaLetra(derivacao[0])));\n }\n der = der.substring(1 , der.length);\n }\n return der;\n}", "function setCurrencyPrefixNF(cp)\n{\n\tthis.currencyPrefix = cp;\n}", "function get_dec_name()\n{\n\treturn \"NMEA 0183\";\n}", "function getDerivacaoAFD(der, terminal){\n console.log(der);\n while(der.charAt(0) != \"}\"){\n var regra = \"([a-zA-Z]|[0-9])\\\\:(q\\\\d\\\\d*)\";\n var reg = new RegExp(regra);\n \n var derivacao = der.match(reg);\n der = der.replace(reg, \"\");\n \n //ajudar a terminal o laço de repeticao\n if(der.charAt(0) == ',' || der.charAt(0) == '{') der = der.substring(1 , der.length); \n //console.log(\"charAt = \" + der.charAt(0) + \" \" + \"gerDerivacao = \" + der + \" terminal e nao terminal = \" + derivacao[1] + \" \"+ derivacao[2]);\n \n addTabela(numParaLetra(terminal), (derivacao[1] + numParaLetra(derivacao[2])));\n }\n return der;\n}", "function get_dec_name()\n{\n\treturn \"MODBUS\";\n}", "function Del_Derivation_Suffixes(kata,selesai){\n\tvar kataAsal = kata;\n\tvar sam=kata\n\tif(kata.match(/(i|an)$/i)){ // Cek Suffixes\n\t\n\tvar __kata = sam.replace(/(i|an)$/i,'');\n\t\tcekKamus(__kata,function(bool){\n\t\t\tif(bool){\n\t\t\t\t\n\t\t\t\tselesai(__kata)\t\n\t\t\t}else if(kata.match(/(kan)$/i)){\n\t\t\t__kata=sam.replace(/(kan)$/i,'')\n\t\t\tcekKamus(__kata,function(kan){\n\n\t\t\t\t\tif(kan){\n\t\t\t\t\t\t\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t\t}else{\n\t\t\t\t\t\t\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}else{\n\t\t\t\t\n\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t})\n\t}else{\n\t\t\n\t\t\tselesai(kataAsal)\n\t}\n\t\n}", "function GetSomewhereinPhoneticModifiedCharaceter(CUni)\r\n{\r\n\tvar CMod=CUni;\r\n\r\n\tif(LCUNI=='ক' && CUni=='হ') CMod = 'খ';\r\n\telse if(LCUNI=='গ' && CUni=='হ') CMod = 'ঘ';\r\n\telse if(LCUNI=='চ' && CUni=='হ') CMod = 'চ';\r\n\telse if(LCUNI=='জ' && CUni=='হ') CMod = 'ঝ';\r\n\telse if(LCUNI=='ট' && CUni=='হ') CMod = 'ঠ';\r\n\telse if(LCUNI=='ড' && CUni=='হ') CMod = 'ঢ';\r\n\telse if(LCUNI=='ত' && CUni=='হ') CMod = 'থ';\r\n\telse if(LCUNI=='দ' && CUni=='হ') CMod = 'ধ';\r\n\telse if(LCUNI=='প' && CUni=='হ') CMod = 'ফ';\r\n\telse if(LCUNI=='ব' && CUni=='হ') CMod = 'ভ';\r\n\telse if(LCUNI=='স' && CUni=='হ') CMod = 'শ';\r\n\telse if(LCUNI=='ড়' && CUni=='হ') CMod = 'ঢ়';\r\n\r\n\telse if(LCUNI=='ণ' && CUni=='গ') CMod = 'ঙ';\r\n\telse if(LCUNI=='ন' && CUni=='গ') CMod = 'ং';\r\n\t\r\n\telse if(LCUNI=='ণ' && CUni=='ঘ') CMod = 'ঞ';\r\n\r\n\telse if(LCUNI=='ণ' && CUni=='ণ') CMod = 'ঁ';\r\n\r\n\telse if(LCUNI=='ঃ' && CUni=='ঃ') CMod = 'ঃ';\r\n\t\r\n\telse if(LCUNI=='ট' && CUni=='ট') CMod = 'ৎ';\r\n\t\r\n\telse if(LCUNI=='া' && CUni=='ো') CMod = 'অ';\r\n\telse if(LCUNI=='ি' && CUni=='ি') CMod = 'ী';\r\n\telse if(LCUNI=='ই' && CUni=='ই') CMod = 'ঈ';\r\n\telse if(LCUNI=='ু' && CUni=='ু') CMod = 'ূ';\r\n\telse if(LCUNI=='উ' && CUni=='উ') CMod = 'ঊ';\r\n\telse if(LCUNI=='ও' && CUni=='ই') CMod = 'ঐ';\r\n\telse if(LCUNI=='ো' && CUni=='ি') CMod = 'ৈ';\r\n\telse if(LCUNI=='ও' && CUni=='উ') CMod = 'ঔ';\r\n\telse if(LCUNI=='ো' && CUni=='ু') CMod = 'ৌ';\r\n\telse if(LCUNI=='ৃ' && CUni=='র') CMod = 'ৃ';\r\n\telse if(LCUNI=='ঋ' && CUni=='ড়') CMod = 'ঋ';\r\n\r\n\treturn CMod;\r\n}", "function getDistrictCode(prefix) {\n let districtCode;\n switch(prefix.toUpperCase()) {\n case 'S':\n districtCode = 0;\n break;\n case 'A':\n districtCode = 1;\n break;\n case 'B':\n districtCode = 2;\n break;\n case 'C':\n districtCode = 3;\n break;\n case 'D':\n districtCode = 41;\n break;\n case 'E':\n districtCode = 42;\n break;\n case 'F':\n districtCode = 43;\n break;\n case 'F':\n districtCode = 5;\n break;\n case 'G':\n districtCode = 6;\n break;\n default:\n districtCode = -1;\n }\n\n return districtCode;\n }", "constructor(){\n // length three prefixes\n this.p3 = [\n \"\\u0643\\u0627\\u0644\",\n \"\\u0628\\u0627\\u0644\",\n \"\\u0648\\u0644\\u0644\",\n \"\\u0648\\u0627\\u0644\",\n ]\n\n // length two prefixes\n this.p2 = [\"\\u0627\\u0644\", \"\\u0644\\u0644\"];\n\n // length one prefixes\n this.p1 = [\n \"\\u0644\",\n \"\\u0628\",\n \"\\u0641\",\n \"\\u0633\",\n \"\\u0648\",\n \"\\u064a\",\n \"\\u062a\",\n \"\\u0646\",\n \"\\u0627\",\n ];\n\n // length three suffixes\n this.s3 = [\n \"\\u062a\\u0645\\u0644\",\n \"\\u0647\\u0645\\u0644\",\n \"\\u062a\\u0627\\u0646\",\n \"\\u062a\\u064a\\u0646\",\n \"\\u0643\\u0645\\u0644\",\n ];\n\n // length two suffixes\n this.s2 = [\n \"\\u0648\\u0646\",\n \"\\u0627\\u062a\",\n \"\\u0627\\u0646\",\n \"\\u064a\\u0646\",\n \"\\u062a\\u0646\",\n \"\\u0643\\u0645\",\n \"\\u0647\\u0646\",\n \"\\u0646\\u0627\",\n \"\\u064a\\u0627\",\n \"\\u0647\\u0627\",\n \"\\u062a\\u0645\",\n \"\\u0643\\u0646\",\n \"\\u0646\\u064a\",\n \"\\u0648\\u0627\",\n \"\\u0645\\u0627\",\n \"\\u0647\\u0645\",\n ];\n\n // length one suffixes\n this.s1 = [\"\\u0629\", \"\\u0647\", \"\\u064a\", \"\\u0643\", \"\\u062a\", \"\\u0627\", \"\\u0646\"];\n\n // groups of length four patterns\n this.pr4 = {\n 0: [\"\\u0645\"],\n 1: [\"\\u0627\"],\n 2: [\"\\u0627\", \"\\u0648\", \"\\u064A\"],\n 3: [\"\\u0629\"],\n };\n\n // Groups of length five patterns and length three roots\n this.pr53 = {\n 0: [\"\\u0627\", \"\\u062a\"],\n 1: [\"\\u0627\", \"\\u064a\", \"\\u0648\"],\n 2: [\"\\u0627\", \"\\u062a\", \"\\u0645\"],\n 3: [\"\\u0645\", \"\\u064a\", \"\\u062a\"],\n 4: [\"\\u0645\", \"\\u062a\"],\n 5: [\"\\u0627\", \"\\u0648\"],\n 6: [\"\\u0627\", \"\\u0645\"],\n };\n\n this.re_short_vowels = new RegExp(\"[\\u064B-\\u0652]\");\n this.re_hamza = new RegExp(\"[\\u0621\\u0624\\u0626]\");\n this.re_initial_hamza = new RegExp(\"^[\\u0622\\u0623\\u0625]\");\n\n this.stop_words = [\n \"\\u064a\\u0643\\u0648\\u0646\",\n \"\\u0648\\u0644\\u064a\\u0633\",\n \"\\u0648\\u0643\\u0627\\u0646\",\n \"\\u0643\\u0630\\u0644\\u0643\",\n \"\\u0627\\u0644\\u062a\\u064a\",\n \"\\u0648\\u0628\\u064a\\u0646\",\n \"\\u0639\\u0644\\u064a\\u0647\\u0627\",\n \"\\u0645\\u0633\\u0627\\u0621\",\n \"\\u0627\\u0644\\u0630\\u064a\",\n \"\\u0648\\u0643\\u0627\\u0646\\u062a\",\n \"\\u0648\\u0644\\u0643\\u0646\",\n \"\\u0648\\u0627\\u0644\\u062a\\u064a\",\n \"\\u062a\\u0643\\u0648\\u0646\",\n \"\\u0627\\u0644\\u064a\\u0648\\u0645\",\n \"\\u0627\\u0644\\u0644\\u0630\\u064a\\u0646\",\n \"\\u0639\\u0644\\u064a\\u0647\",\n \"\\u0643\\u0627\\u0646\\u062a\",\n \"\\u0644\\u0630\\u0644\\u0643\",\n \"\\u0623\\u0645\\u0627\\u0645\",\n \"\\u0647\\u0646\\u0627\\u0643\",\n \"\\u0645\\u0646\\u0647\\u0627\",\n \"\\u0645\\u0627\\u0632\\u0627\\u0644\",\n \"\\u0644\\u0627\\u0632\\u0627\\u0644\",\n \"\\u0644\\u0627\\u064a\\u0632\\u0627\\u0644\",\n \"\\u0645\\u0627\\u064a\\u0632\\u0627\\u0644\",\n \"\\u0627\\u0635\\u0628\\u062d\",\n \"\\u0623\\u0635\\u0628\\u062d\",\n \"\\u0623\\u0645\\u0633\\u0649\",\n \"\\u0627\\u0645\\u0633\\u0649\",\n \"\\u0623\\u0636\\u062d\\u0649\",\n \"\\u0627\\u0636\\u062d\\u0649\",\n \"\\u0645\\u0627\\u0628\\u0631\\u062d\",\n \"\\u0645\\u0627\\u0641\\u062a\\u0626\",\n \"\\u0645\\u0627\\u0627\\u0646\\u0641\\u0643\",\n \"\\u0644\\u0627\\u0633\\u064a\\u0645\\u0627\",\n \"\\u0648\\u0644\\u0627\\u064a\\u0632\\u0627\\u0644\",\n \"\\u0627\\u0644\\u062d\\u0627\\u0644\\u064a\",\n \"\\u0627\\u0644\\u064a\\u0647\\u0627\",\n \"\\u0627\\u0644\\u0630\\u064a\\u0646\",\n \"\\u0641\\u0627\\u0646\\u0647\",\n \"\\u0648\\u0627\\u0644\\u0630\\u064a\",\n \"\\u0648\\u0647\\u0630\\u0627\",\n \"\\u0644\\u0647\\u0630\\u0627\",\n \"\\u0641\\u0643\\u0627\\u0646\",\n \"\\u0633\\u062a\\u0643\\u0648\\u0646\",\n \"\\u0627\\u0644\\u064a\\u0647\",\n \"\\u064a\\u0645\\u0643\\u0646\",\n \"\\u0628\\u0647\\u0630\\u0627\",\n \"\\u0627\\u0644\\u0630\\u0649\",\n ];\n }", "function get_dec_name()\n{\n\treturn \"CAN\";\n}", "bcdPrefix() {\n return `${this.bcd.base}${this.trailingSlash(this.bcd.base)}v${this.bcd.version}/`;\n }", "function getDNILetterByParameter (dni) { \r\n dniLetter =\"TRWAGMYFPDXBNJZSQVHLCKET\"; \r\n position = dni % 23; \r\n return dniLetter.substring(position, position+1); \r\n}", "function __doubleMetaphone(value) {\n var primary = '',\n secondary = '',\n index = 0,\n length = value.length,\n last = length - 1,\n isSlavoGermanic = SLAVO_GERMANIC.test(value),\n isGermanic = GERMANIC.test(value),\n characters = value.split(''),\n subvalue,\n next,\n prev,\n nextnext;\n\n value = String(value).toUpperCase() + ' ';\n\n // Skip this at beginning of word.\n if (INITIAL_EXCEPTIONS.test(value))\n index++;\n\n // Initial X is pronounced Z, which maps to S. Such as `Xavier`\n if (characters[0] === 'X') {\n primary += 'S';\n secondary += 'S';\n\n index++;\n }\n\n while (index < length) {\n prev = characters[index - 1];\n next = characters[index + 1];\n nextnext = characters[index + 2];\n\n switch (characters[index]) {\n case 'A':\n case 'E':\n case 'I':\n case 'O':\n case 'U':\n case 'Y':\n case 'À':\n case 'Ê':\n case 'É':\n case 'É':\n if (index === 0) {\n // All initial vowels now map to `A`.\n primary += 'A';\n secondary += 'A';\n }\n\n index++;\n\n break;\n case 'B':\n primary += 'P';\n secondary += 'P';\n\n if (next === 'B')\n index++;\n\n index++;\n\n break;\n case 'Ç':\n primary += 'S';\n secondary += 'S';\n index++;\n\n break;\n case 'C':\n // Various Germanic:\n if (prev === 'A' &&\n next === 'H' &&\n nextnext !== 'I' &&\n !VOWELS.test(characters[index - 2]) &&\n (nextnext !== 'E' || (subvalue = value.slice(index - 2, index + 4) &&\n (subvalue === 'BACHER' || subvalue === 'MACHER')))\n ) {\n primary += 'K';\n secondary += 'K';\n index += 2;\n\n break;\n }\n\n // Special case for `Caesar`.\n if (index === 0 && value.slice(index + 1, index + 6) === 'AESAR') {\n primary += 'S';\n secondary += 'S';\n index += 2;\n\n break;\n }\n\n // Italian `Chianti`.\n if (value.slice(index + 1, index + 4) === 'HIA') {\n primary += 'K';\n secondary += 'K';\n index += 2;\n\n break;\n }\n\n if (next === 'H') {\n // Find `Michael`.\n if (index > 0 && nextnext === 'A' && characters[index + 3] === 'E') {\n primary += 'K';\n secondary += 'X';\n index += 2;\n\n break;\n }\n\n // Greek roots such as `chemistry`, `chorus`.\n if (index === 0 && GREEK_INITIAL_CH.test(value)) {\n primary += 'K';\n secondary += 'K';\n index += 2;\n\n break;\n }\n\n // Germanic, Greek, or otherwise `CH` for `KH` sound.\n if (isGermanic ||\n // Such as 'architect' but not 'arch', orchestra', 'orchid'.\n GREEK_CH.test(value.slice(index - 2, index + 4)) ||\n (nextnext === 'T' || nextnext === 'S') ||\n ((index === 0 ||\n prev === 'A' ||\n prev === 'E' ||\n prev === 'O' ||\n prev === 'U') &&\n // Such as `wachtler`, `weschsler`, but not `tichner`.\n CH_FOR_KH.test(nextnext))\n ) {\n primary += 'K';\n secondary += 'K';\n } else if (index === 0) {\n primary += 'X';\n secondary += 'X';\n } else if (value.slice(0, 2) === 'MC') { // Such as 'McHugh'.\n // Bug? Why matching absolute? what about McHiccup?\n primary += 'K';\n secondary += 'K';\n } else {\n primary += 'X';\n secondary += 'K';\n }\n\n index += 2;\n\n break;\n }\n\n // Such as `Czerny`.\n if (next === 'Z' && value.slice(index - 2, index) !== 'WI') {\n primary += 'S';\n secondary += 'X';\n index += 2;\n\n break;\n }\n\n // Such as `Focaccia`.\n if (value.slice(index + 1, index + 4) === 'CIA') {\n primary += 'X';\n secondary += 'X';\n index += 3;\n\n break;\n }\n\n // Double `C`, but not `McClellan`.\n if (next === 'C' && !(index === 1 && characters[0] === 'M')) {\n // Such as `Bellocchio`, but not `Bacchus`.\n if ((nextnext === 'I' ||\n nextnext === 'E' ||\n nextnext === 'H') &&\n value.slice(index + 2, index + 4) !== 'HU'\n ) {\n subvalue = value.slice(index - 1, index + 4);\n\n // Such as `Accident`, `Accede`, `Succeed`.\n if ((index === 1 && prev === 'A') || subvalue === 'UCCEE' || subvalue === 'UCCES') {\n primary += 'KS';\n secondary += 'KS';\n } else { // Such as `Bacci`, `Bertucci`, other Italian.\n primary += 'X';\n secondary += 'X';\n }\n\n index += 3;\n\n break;\n } else {\n // Pierce's rule.\n primary += 'K';\n secondary += 'K';\n index += 2;\n\n break;\n }\n }\n\n if (next === 'G' || next === 'K' || next === 'Q') {\n primary += 'K';\n secondary += 'K';\n index += 2;\n\n break;\n }\n\n // Italian.\n if (next === 'I' && (nextnext === 'A' || nextnext === 'E' || nextnext === 'O')) {\n primary += 'S';\n secondary += 'X';\n index += 2;\n\n break;\n }\n\n if (next === 'I' || next === 'E' || next === 'Y') {\n primary += 'S';\n secondary += 'S';\n index += 2;\n\n break;\n }\n\n primary += 'K';\n secondary += 'K';\n\n // Skip two extra characters ahead in `Mac Caffrey`, `Mac Gregor`.\n if (next === ' ' && (nextnext === 'C' || nextnext === 'G' || nextnext === 'Q')) {\n index += 3;\n break;\n }\n\n if (next === 'K' || next === 'Q' || (next === 'C' && nextnext !== 'E' && nextnext !== 'I'))\n index++;\n\n index++;\n\n break;\n case 'D':\n if (next === 'G') {\n // Such as `edge`.\n if (nextnext === 'E' || nextnext === 'I' || nextnext === 'Y') {\n primary += 'J';\n secondary += 'J';\n index += 3;\n } else { // Such as `Edgar`.\n primary += 'TK';\n secondary += 'TK';\n index += 2;\n }\n\n break;\n }\n\n if (next === 'T' || next === 'D') {\n primary += 'T';\n secondary += 'T';\n index += 2;\n\n break;\n }\n\n primary += 'T';\n secondary += 'T';\n index++;\n\n break;\n case 'F':\n if (next === 'F')\n index++;\n\n index++;\n primary += 'F';\n secondary += 'F';\n\n break;\n case 'G':\n if (next === 'H') {\n if (index > 0 && !VOWELS.test(prev)) {\n primary += 'K';\n secondary += 'K';\n index += 2;\n\n break;\n }\n\n // Such as `Ghislane`, `Ghiradelli`.\n if (index === 0) {\n if (nextnext === 'I') {\n primary += 'J';\n secondary += 'J';\n } else {\n primary += 'K';\n secondary += 'K';\n }\n index += 2;\n break;\n }\n\n // Parker's rule (with some further refinements).\n if ((// Such as `Hugh`\n subvalue = characters[index - 2],\n subvalue === 'B' ||\n subvalue === 'H' ||\n subvalue === 'D'\n ) ||\n (// Such as `bough`.\n subvalue = characters[index - 3],\n subvalue === 'B' ||\n subvalue === 'H' ||\n subvalue === 'D'\n ) ||\n (// Such as `Broughton`.\n subvalue = characters[index - 4],\n subvalue === 'B' ||\n subvalue === 'H'\n )\n ) {\n index += 2;\n\n break;\n }\n\n // Such as `laugh`, `McLaughlin`, `cough`, `gough`, `rough`, `tough`.\n if (index > 2 && prev === 'U' && G_FOR_F.test(characters[index - 3])) {\n primary += 'F';\n secondary += 'F';\n } else if (index > 0 && prev !== 'I') {\n primary += 'K';\n secondary += 'K';\n }\n\n index += 2;\n\n break;\n }\n\n if (next === 'N') {\n if (index === 1 && VOWELS.test(characters[0]) && !isSlavoGermanic) {\n primary += 'KN';\n secondary += 'N';\n } else if (\n // Not like `Cagney`.\n value.slice(index + 2, index + 4) !== 'EY' &&\n value.slice(index + 1) !== 'Y' &&\n !isSlavoGermanic\n ) {\n primary += 'N';\n secondary += 'KN';\n } else {\n primary += 'KN';\n secondary += 'KN';\n }\n\n index += 2;\n\n break;\n }\n\n //Such as `Tagliaro`.\n if (value.slice(index + 1, index + 3) === 'LI' && !isSlavoGermanic) {\n primary += 'KL';\n secondary += 'L';\n index += 2;\n\n break;\n }\n\n // -ges-, -gep-, -gel- at beginning.\n if (index === 0 && INITIAL_G_FOR_KJ.test(value.slice(1, 3))) {\n primary += 'K';\n secondary += 'J';\n index += 2;\n\n break;\n }\n\n // -ger-, -gy-.\n if ((value.slice(index + 1, index + 3) === 'ER' &&\n prev !== 'I' && prev !== 'E' &&\n !INITIAL_ANGER_EXCEPTION.test(value.slice(0, 6))\n ) ||\n (next === 'Y' && !G_FOR_KJ.test(prev))\n ) {\n primary += 'K';\n secondary += 'J';\n index += 2;\n\n break;\n }\n\n // Italian such as `biaggi`.\n if (next === 'E' || next === 'I' || next === 'Y' || (\n (prev === 'A' || prev === 'O') &&\n next === 'G' && nextnext === 'I'\n )\n ) {\n // Obvious Germanic.\n if (value.slice(index + 1, index + 3) === 'ET' || isGermanic) {\n primary += 'K';\n secondary += 'K';\n } else {\n // Always soft if French ending.\n if (value.slice(index + 1, index + 5) === 'IER ') {\n primary += 'J';\n secondary += 'J';\n } else {\n primary += 'J';\n secondary += 'K';\n }\n }\n\n index += 2;\n\n break;\n }\n\n if (next === 'G')\n index++;\n\n index++;\n\n primary += 'K';\n secondary += 'K';\n\n break;\n case 'H':\n // Only keep if first & before vowel or btw. 2 vowels.\n if (VOWELS.test(next) && (index === 0 || VOWELS.test(prev))) {\n primary += 'H';\n secondary += 'H';\n\n index++;\n }\n\n index++;\n\n break;\n case 'J':\n // Obvious Spanish, `jose`, `San Jacinto`.\n if (value.slice(index, index + 4) === 'JOSE' || value.slice(0, 4) === 'SAN ') {\n if (value.slice(0, 4) === 'SAN ' || (index === 0 && characters[index + 4] === ' ')) {\n primary += 'H';\n secondary += 'H';\n } else {\n primary += 'J';\n secondary += 'H';\n }\n\n index++;\n\n break;\n }\n\n if (index === 0) {\n // Such as `Yankelovich` or `Jankelowicz`.\n primary += 'J';\n secondary += 'A';\n } else if (// Spanish pron. of such as `bajador`.\n !isSlavoGermanic &&\n (next === 'A' || next === 'O') &&\n VOWELS.test(prev)\n ) {\n primary += 'J';\n secondary += 'H';\n } else if (index === last) {\n primary += 'J';\n } else if (prev !== 'S' && prev !== 'K' && prev !== 'L' && !J_FOR_J_EXCEPTION.test(next)) {\n primary += 'J';\n secondary += 'J';\n } else if (next === 'J') {\n index++;\n }\n\n index++;\n\n break;\n case 'K':\n if (next === 'K')\n index++;\n\n primary += 'K';\n secondary += 'K';\n index++;\n\n break;\n case 'L':\n if (next === 'L') {\n // Spanish such as `cabrillo`, `gallegos`.\n if ((index === length - 3 && ((\n prev === 'I' && (\n nextnext === 'O' || nextnext === 'A'\n )\n ) || (\n prev === 'A' && nextnext === 'E'\n )\n )) || (\n prev === 'A' && nextnext === 'E' && ((\n characters[last] === 'A' || characters[last] === 'O'\n ) || ALLE.test(value.slice(last - 1, length))\n )\n )\n ) {\n primary += 'L';\n index += 2;\n\n break;\n }\n\n index++;\n }\n\n primary += 'L';\n secondary += 'L';\n index++;\n\n break;\n case 'M':\n // Such as `dumb`, `thumb`.\n if (next === 'M' || (\n prev === 'U' && next === 'B' && (\n index + 1 === last || value.slice(index + 2, index + 4) === 'ER')\n )\n ) {\n index++;\n }\n\n index++;\n primary += 'M';\n secondary += 'M';\n\n break;\n case 'N':\n if (next === 'N')\n index++;\n\n index++;\n primary += 'N';\n secondary += 'N';\n\n break;\n case 'Ñ':\n index++;\n primary += 'N';\n secondary += 'N';\n\n break;\n case 'P':\n if (next === 'H') {\n primary += 'F';\n secondary += 'F';\n index += 2;\n\n break;\n }\n\n // Also account for `campbell` and `raspberry`.\n subvalue = next;\n\n if (subvalue === 'P' || subvalue === 'B')\n index++;\n\n index++;\n\n primary += 'P';\n secondary += 'P';\n\n break;\n case 'Q':\n if (next === 'Q') {\n index++;\n }\n\n index++;\n primary += 'K';\n secondary += 'K';\n\n break;\n case 'R':\n // French such as `Rogier`, but exclude `Hochmeier`.\n if (index === last &&\n !isSlavoGermanic &&\n prev === 'E' &&\n characters[index - 2] === 'I' &&\n characters[index - 4] !== 'M' && (\n characters[index - 3] !== 'E' &&\n characters[index - 3] !== 'A'\n )\n ) {\n secondary += 'R';\n } else {\n primary += 'R';\n secondary += 'R';\n }\n\n if (next === 'R')\n index++;\n\n index++;\n\n break;\n case 'S':\n // Special cases `island`, `isle`, `carlisle`, `carlysle`.\n if (next === 'L' && (prev === 'I' || prev === 'Y')) {\n index++;\n\n break;\n }\n\n // Special case `sugar-`.\n if (index === 0 && value.slice(1, 5) === 'UGAR') {\n primary += 'X';\n secondary += 'S';\n index++;\n\n break;\n }\n\n if (next === 'H') {\n // Germanic.\n if (H_FOR_S.test(value.slice(index + 1, index + 5))) {\n primary += 'S';\n secondary += 'S';\n } else {\n primary += 'X';\n secondary += 'X';\n }\n\n index += 2;\n break;\n }\n\n if (next === 'I' && (nextnext === 'O' || nextnext === 'A')) {\n if (!isSlavoGermanic) {\n primary += 'S';\n secondary += 'X';\n } else {\n primary += 'S';\n secondary += 'S';\n }\n\n index += 3;\n\n break;\n }\n\n /*\n * German & Anglicization's, such as `Smith` match `Schmidt`,\n * `snider` match `Schneider`. Also, -sz- in slavic language\n * although in hungarian it is pronounced `s`.\n */\n if (next === 'Z' || (\n index === 0 && (\n next === 'L' || next === 'M' || next === 'N' || next === 'W'\n )\n )\n ) {\n primary += 'S';\n secondary += 'X';\n\n if (next === 'Z')\n index++;\n\n index++;\n\n break;\n }\n\n if (next === 'C') {\n // Schlesinger's rule.\n if (nextnext === 'H') {\n subvalue = value.slice(index + 3, index + 5);\n\n // Dutch origin, such as `school`, `schooner`.\n if (DUTCH_SCH.test(subvalue)) {\n // Such as `schermerhorn`, `schenker`.\n if (subvalue === 'ER' || subvalue === 'EN') {\n primary += 'X';\n secondary += 'SK';\n } else {\n primary += 'SK';\n secondary += 'SK';\n }\n\n index += 3;\n\n break;\n }\n\n if (index === 0 && !VOWELS.test(characters[3]) && characters[3] !== 'W') {\n primary += 'X';\n secondary += 'S';\n } else {\n primary += 'X';\n secondary += 'X';\n }\n\n index += 3;\n\n break;\n }\n\n if (nextnext === 'I' || nextnext === 'E' || nextnext === 'Y') {\n primary += 'S';\n secondary += 'S';\n index += 3;\n break;\n }\n\n primary += 'SK';\n secondary += 'SK';\n index += 3;\n\n break;\n }\n\n subvalue = value.slice(index - 2, index);\n\n // French such as `resnais`, `artois`.\n if (index === last && (subvalue === 'AI' || subvalue === 'OI')) {\n secondary += 'S';\n } else {\n primary += 'S';\n secondary += 'S';\n }\n\n if (next === 'S' || next === 'Z')\n index++;\n\n index++;\n\n break;\n case 'T':\n if (next === 'I' && nextnext === 'O' && characters[index + 3] === 'N') {\n primary += 'X';\n secondary += 'X';\n index += 3;\n\n break;\n }\n\n subvalue = value.slice(index + 1, index + 3);\n\n if ((next === 'I' && nextnext === 'A') || (next === 'C' && nextnext === 'H')) {\n primary += 'X';\n secondary += 'X';\n index += 3;\n\n break;\n }\n\n if (next === 'H' || (next === 'T' && nextnext === 'H')) {\n // Special case `Thomas`, `Thames` or Germanic.\n if (isGermanic || ((nextnext === 'O' || nextnext === 'A') && characters[index + 3] === 'M')) {\n primary += 'T';\n secondary += 'T';\n } else {\n primary += '0';\n secondary += 'T';\n }\n\n index += 2;\n\n break;\n }\n\n if (next === 'T' || next === 'D')\n index++;\n\n index++;\n primary += 'T';\n secondary += 'T';\n\n break;\n case 'V':\n if (next === 'V')\n index++;\n\n primary += 'F';\n secondary += 'F';\n index++;\n\n break;\n case 'W':\n // Can also be in middle of word (as already taken care of for initial).\n if (next === 'R') {\n primary += 'R';\n secondary += 'R';\n index += 2;\n\n break;\n }\n\n if (index === 0) {\n // `Wasserman` should match `Vasserman`.\n if (VOWELS.test(next)) {\n primary += 'A';\n secondary += 'F';\n } else if (next === 'H') {\n // Need `Uomo` to match `Womo`.\n primary += 'A';\n secondary += 'A';\n }\n }\n\n // `Arnow` should match `Arnoff`.\n if (((prev === 'E' || prev === 'O') &&\n next === 'S' && nextnext === 'K' && (\n characters[index + 3] === 'I' ||\n characters[index + 3] === 'Y'\n )\n ) || value.slice(0, 3) === 'SCH' || (index === last && VOWELS.test(prev))\n ) {\n secondary += 'F';\n index++;\n\n break;\n }\n\n // Polish such as `Filipowicz`.\n if (next === 'I' && (nextnext === 'C' || nextnext === 'T') && characters[index + 3] === 'Z') {\n primary += 'TS';\n secondary += 'FX';\n index += 4;\n\n break;\n }\n\n index++;\n\n break;\n case 'X':\n // French such as `breaux`.\n if (index === last || (prev === 'U' && (\n characters[index - 2] === 'A' ||\n characters[index - 2] === 'O'\n ))\n ) {\n primary += 'KS';\n secondary += 'KS';\n }\n\n if (next === 'C' || next === 'X')\n index++;\n\n index++;\n\n break;\n case 'Z':\n // Chinese pinyin such as `Zhao`.\n if (next === 'H') {\n primary += 'J';\n secondary += 'J';\n index += 2;\n\n break;\n } else if ((next === 'Z' && (\n nextnext === 'A' || nextnext === 'I' || nextnext === 'O'\n )) || (\n isSlavoGermanic && index > 0 && prev !== 'T'\n )\n ) {\n primary += 'S';\n secondary += 'TS';\n } else {\n primary += 'S';\n secondary += 'S';\n }\n\n if (next === 'Z')\n index++;\n\n index++;\n\n break;\n default:\n index++;\n\n }\n }\n\n return [primary, secondary];\n }", "function doubleMetaphone(value) {\n var primary = ''\n var secondary = ''\n var index = 0\n var length = value.length\n var last = length - 1\n var isSlavoGermanic\n var isGermanic\n var subvalue\n var next\n var prev\n var nextnext\n var characters\n\n value = String(value).toUpperCase() + ' '\n isSlavoGermanic = slavoGermanic.test(value)\n isGermanic = germanic.test(value)\n characters = value.split('')\n\n // Skip this at beginning of word.\n if (initialExceptions.test(value)) {\n index++\n }\n\n // Initial X is pronounced Z, which maps to S. Such as `Xavier`.\n if (characters[0] === 'X') {\n primary += 'S'\n secondary += 'S'\n index++\n }\n\n while (index < length) {\n prev = characters[index - 1]\n next = characters[index + 1]\n nextnext = characters[index + 2]\n\n switch (characters[index]) {\n case 'A':\n case 'E':\n case 'I':\n case 'O':\n case 'U':\n case 'Y':\n case 'À':\n case 'Ê':\n case 'É':\n if (index === 0) {\n // All initial vowels now map to `A`.\n primary += 'A'\n secondary += 'A'\n }\n\n index++\n\n break\n case 'B':\n primary += 'P'\n secondary += 'P'\n\n if (next === 'B') {\n index++\n }\n\n index++\n\n break\n case 'Ç':\n primary += 'S'\n secondary += 'S'\n index++\n\n break\n case 'C':\n // Various Germanic:\n if (\n prev === 'A' &&\n next === 'H' &&\n nextnext !== 'I' &&\n !vowels.test(characters[index - 2]) &&\n (nextnext !== 'E' ||\n (subvalue =\n value.slice(index - 2, index + 4) &&\n (subvalue === 'BACHER' || subvalue === 'MACHER')))\n ) {\n primary += 'K'\n secondary += 'K'\n index += 2\n\n break\n }\n\n // Special case for `Caesar`.\n if (index === 0 && value.slice(index + 1, index + 6) === 'AESAR') {\n primary += 'S'\n secondary += 'S'\n index += 2\n\n break\n }\n\n // Italian `Chianti`.\n if (value.slice(index + 1, index + 4) === 'HIA') {\n primary += 'K'\n secondary += 'K'\n index += 2\n\n break\n }\n\n if (next === 'H') {\n // Find `Michael`.\n if (index > 0 && nextnext === 'A' && characters[index + 3] === 'E') {\n primary += 'K'\n secondary += 'X'\n index += 2\n\n break\n }\n\n // Greek roots such as `chemistry`, `chorus`.\n if (index === 0 && initialGreekCh.test(value)) {\n primary += 'K'\n secondary += 'K'\n index += 2\n\n break\n }\n\n // Germanic, Greek, or otherwise `CH` for `KH` sound.\n if (\n isGermanic ||\n // Such as 'architect' but not 'arch', orchestra', 'orchid'.\n greekCh.test(value.slice(index - 2, index + 4)) ||\n (nextnext === 'T' || nextnext === 'S') ||\n ((index === 0 ||\n prev === 'A' ||\n prev === 'E' ||\n prev === 'O' ||\n prev === 'U') &&\n // Such as `wachtler`, `weschsler`, but not `tichner`.\n chForKh.test(nextnext))\n ) {\n primary += 'K'\n secondary += 'K'\n } else if (index === 0) {\n primary += 'X'\n secondary += 'X'\n // Such as 'McHugh'.\n } else if (value.slice(0, 2) === 'MC') {\n // Bug? Why matching absolute? what about McHiccup?\n primary += 'K'\n secondary += 'K'\n } else {\n primary += 'X'\n secondary += 'K'\n }\n\n index += 2\n\n break\n }\n\n // Such as `Czerny`.\n if (next === 'Z' && value.slice(index - 2, index) !== 'WI') {\n primary += 'S'\n secondary += 'X'\n index += 2\n\n break\n }\n\n // Such as `Focaccia`.\n if (value.slice(index + 1, index + 4) === 'CIA') {\n primary += 'X'\n secondary += 'X'\n index += 3\n\n break\n }\n\n // Double `C`, but not `McClellan`.\n if (next === 'C' && !(index === 1 && characters[0] === 'M')) {\n // Such as `Bellocchio`, but not `Bacchus`.\n if (\n (nextnext === 'I' || nextnext === 'E' || nextnext === 'H') &&\n value.slice(index + 2, index + 4) !== 'HU'\n ) {\n subvalue = value.slice(index - 1, index + 4)\n\n // Such as `Accident`, `Accede`, `Succeed`.\n if (\n (index === 1 && prev === 'A') ||\n subvalue === 'UCCEE' ||\n subvalue === 'UCCES'\n ) {\n primary += 'KS'\n secondary += 'KS'\n // Such as `Bacci`, `Bertucci`, other Italian.\n } else {\n primary += 'X'\n secondary += 'X'\n }\n\n index += 3\n\n break\n } else {\n // Pierce's rule.\n primary += 'K'\n secondary += 'K'\n index += 2\n\n break\n }\n }\n\n if (next === 'G' || next === 'K' || next === 'Q') {\n primary += 'K'\n secondary += 'K'\n index += 2\n\n break\n }\n\n // Italian.\n if (\n next === 'I' &&\n // Bug: The original algorithm also calls for A (as in CIA), which is\n // already taken care of above.\n (nextnext === 'E' || nextnext === 'O')\n ) {\n primary += 'S'\n secondary += 'X'\n index += 2\n\n break\n }\n\n if (next === 'I' || next === 'E' || next === 'Y') {\n primary += 'S'\n secondary += 'S'\n index += 2\n\n break\n }\n\n primary += 'K'\n secondary += 'K'\n\n // Skip two extra characters ahead in `Mac Caffrey`, `Mac Gregor`.\n if (\n next === ' ' &&\n (nextnext === 'C' || nextnext === 'G' || nextnext === 'Q')\n ) {\n index += 3\n break\n }\n\n // Bug: Already covered above.\n // if (\n // next === 'K' ||\n // next === 'Q' ||\n // (next === 'C' && nextnext !== 'E' && nextnext !== 'I')\n // ) {\n // index++;\n // }\n\n index++\n\n break\n case 'D':\n if (next === 'G') {\n // Such as `edge`.\n if (nextnext === 'E' || nextnext === 'I' || nextnext === 'Y') {\n primary += 'J'\n secondary += 'J'\n index += 3\n // Such as `Edgar`.\n } else {\n primary += 'TK'\n secondary += 'TK'\n index += 2\n }\n\n break\n }\n\n if (next === 'T' || next === 'D') {\n primary += 'T'\n secondary += 'T'\n index += 2\n\n break\n }\n\n primary += 'T'\n secondary += 'T'\n index++\n\n break\n case 'F':\n if (next === 'F') {\n index++\n }\n\n index++\n primary += 'F'\n secondary += 'F'\n\n break\n case 'G':\n if (next === 'H') {\n if (index > 0 && !vowels.test(prev)) {\n primary += 'K'\n secondary += 'K'\n index += 2\n\n break\n }\n\n // Such as `Ghislane`, `Ghiradelli`.\n if (index === 0) {\n if (nextnext === 'I') {\n primary += 'J'\n secondary += 'J'\n } else {\n primary += 'K'\n secondary += 'K'\n }\n\n index += 2\n\n break\n }\n\n // Parker's rule (with some further refinements).\n if (\n // Such as `Hugh`. The comma is not a bug.\n ((subvalue = characters[index - 2]),\n subvalue === 'B' || subvalue === 'H' || subvalue === 'D') ||\n // Such as `bough`. The comma is not a bug.\n ((subvalue = characters[index - 3]),\n subvalue === 'B' || subvalue === 'H' || subvalue === 'D') ||\n // Such as `Broughton`. The comma is not a bug.\n ((subvalue = characters[index - 4]),\n subvalue === 'B' || subvalue === 'H')\n ) {\n index += 2\n\n break\n }\n\n // Such as `laugh`, `McLaughlin`, `cough`, `gough`, `rough`, `tough`.\n if (index > 2 && prev === 'U' && gForF.test(characters[index - 3])) {\n primary += 'F'\n secondary += 'F'\n } else if (index > 0 && prev !== 'I') {\n primary += 'K'\n secondary += 'K'\n }\n\n index += 2\n\n break\n }\n\n if (next === 'N') {\n if (index === 1 && vowels.test(characters[0]) && !isSlavoGermanic) {\n primary += 'KN'\n secondary += 'N'\n // Not like `Cagney`.\n } else if (\n value.slice(index + 2, index + 4) !== 'EY' &&\n value.slice(index + 1) !== 'Y' &&\n !isSlavoGermanic\n ) {\n primary += 'N'\n secondary += 'KN'\n } else {\n primary += 'KN'\n secondary += 'KN'\n }\n\n index += 2\n\n break\n }\n\n // Such as `Tagliaro`.\n if (value.slice(index + 1, index + 3) === 'LI' && !isSlavoGermanic) {\n primary += 'KL'\n secondary += 'L'\n index += 2\n\n break\n }\n\n // -ges-, -gep-, -gel- at beginning.\n if (index === 0 && initialGForKj.test(value.slice(1, 3))) {\n primary += 'K'\n secondary += 'J'\n index += 2\n\n break\n }\n\n // -ger-, -gy-.\n if (\n (value.slice(index + 1, index + 3) === 'ER' &&\n prev !== 'I' &&\n prev !== 'E' &&\n !initialAngerException.test(value.slice(0, 6))) ||\n (next === 'Y' && !gForKj.test(prev))\n ) {\n primary += 'K'\n secondary += 'J'\n index += 2\n\n break\n }\n\n // Italian such as `biaggi`.\n if (\n next === 'E' ||\n next === 'I' ||\n next === 'Y' ||\n ((prev === 'A' || prev === 'O') && next === 'G' && nextnext === 'I')\n ) {\n // Obvious Germanic.\n if (value.slice(index + 1, index + 3) === 'ET' || isGermanic) {\n primary += 'K'\n secondary += 'K'\n } else {\n primary += 'J'\n\n // Always soft if French ending.\n if (value.slice(index + 1, index + 5) === 'IER ') {\n secondary += 'J'\n } else {\n secondary += 'K'\n }\n }\n\n index += 2\n\n break\n }\n\n if (next === 'G') {\n index++\n }\n\n index++\n\n primary += 'K'\n secondary += 'K'\n\n break\n case 'H':\n // Only keep if first & before vowel or btw. 2 vowels.\n if (vowels.test(next) && (index === 0 || vowels.test(prev))) {\n primary += 'H'\n secondary += 'H'\n\n index++\n }\n\n index++\n\n break\n case 'J':\n // Obvious Spanish, `jose`, `San Jacinto`.\n if (\n value.slice(index, index + 4) === 'JOSE' ||\n value.slice(0, 4) === 'SAN '\n ) {\n if (\n value.slice(0, 4) === 'SAN ' ||\n (index === 0 && characters[index + 4] === ' ')\n ) {\n primary += 'H'\n secondary += 'H'\n } else {\n primary += 'J'\n secondary += 'H'\n }\n\n index++\n\n break\n }\n\n if (\n index === 0\n // Bug: unreachable (see previous statement).\n // && value.slice(index, index + 4) !== 'JOSE'.\n ) {\n primary += 'J'\n\n // Such as `Yankelovich` or `Jankelowicz`.\n secondary += 'A'\n // Spanish pron. of such as `bajador`.\n } else if (\n !isSlavoGermanic &&\n (next === 'A' || next === 'O') &&\n vowels.test(prev)\n ) {\n primary += 'J'\n secondary += 'H'\n } else if (index === last) {\n primary += 'J'\n } else if (\n prev !== 'S' &&\n prev !== 'K' &&\n prev !== 'L' &&\n !jForJException.test(next)\n ) {\n primary += 'J'\n secondary += 'J'\n // It could happen.\n } else if (next === 'J') {\n index++\n }\n\n index++\n\n break\n case 'K':\n if (next === 'K') {\n index++\n }\n\n primary += 'K'\n secondary += 'K'\n index++\n\n break\n case 'L':\n if (next === 'L') {\n // Spanish such as `cabrillo`, `gallegos`.\n if (\n (index === length - 3 &&\n ((prev === 'A' && nextnext === 'E') ||\n (prev === 'I' && (nextnext === 'O' || nextnext === 'A')))) ||\n (prev === 'A' &&\n nextnext === 'E' &&\n (characters[last] === 'A' ||\n characters[last] === 'O' ||\n alle.test(value.slice(last - 1, length))))\n ) {\n primary += 'L'\n index += 2\n\n break\n }\n\n index++\n }\n\n primary += 'L'\n secondary += 'L'\n index++\n\n break\n case 'M':\n if (\n next === 'M' ||\n // Such as `dumb`, `thumb`.\n (prev === 'U' &&\n next === 'B' &&\n (index + 1 === last || value.slice(index + 2, index + 4) === 'ER'))\n ) {\n index++\n }\n\n index++\n primary += 'M'\n secondary += 'M'\n\n break\n case 'N':\n if (next === 'N') {\n index++\n }\n\n index++\n primary += 'N'\n secondary += 'N'\n\n break\n case 'Ñ':\n index++\n primary += 'N'\n secondary += 'N'\n\n break\n case 'P':\n if (next === 'H') {\n primary += 'F'\n secondary += 'F'\n index += 2\n\n break\n }\n\n // Also account for `campbell` and `raspberry`.\n subvalue = next\n\n if (subvalue === 'P' || subvalue === 'B') {\n index++\n }\n\n index++\n\n primary += 'P'\n secondary += 'P'\n\n break\n case 'Q':\n if (next === 'Q') {\n index++\n }\n\n index++\n primary += 'K'\n secondary += 'K'\n\n break\n case 'R':\n // French such as `Rogier`, but exclude `Hochmeier`.\n if (\n index === last &&\n !isSlavoGermanic &&\n prev === 'E' &&\n characters[index - 2] === 'I' &&\n characters[index - 4] !== 'M' &&\n (characters[index - 3] !== 'E' && characters[index - 3] !== 'A')\n ) {\n secondary += 'R'\n } else {\n primary += 'R'\n secondary += 'R'\n }\n\n if (next === 'R') {\n index++\n }\n\n index++\n\n break\n case 'S':\n // Special cases `island`, `isle`, `carlisle`, `carlysle`.\n if (next === 'L' && (prev === 'I' || prev === 'Y')) {\n index++\n\n break\n }\n\n // Special case `sugar-`.\n if (index === 0 && value.slice(1, 5) === 'UGAR') {\n primary += 'X'\n secondary += 'S'\n index++\n\n break\n }\n\n if (next === 'H') {\n // Germanic.\n if (hForS.test(value.slice(index + 1, index + 5))) {\n primary += 'S'\n secondary += 'S'\n } else {\n primary += 'X'\n secondary += 'X'\n }\n\n index += 2\n break\n }\n\n if (\n next === 'I' &&\n (nextnext === 'O' || nextnext === 'A')\n // Bug: Already covered by previous branch\n // || value.slice(index, index + 4) === 'SIAN'\n ) {\n if (isSlavoGermanic) {\n primary += 'S'\n secondary += 'S'\n } else {\n primary += 'S'\n secondary += 'X'\n }\n\n index += 3\n\n break\n }\n\n // German & Anglicization's, such as `Smith` match `Schmidt`, `snider`\n // match `Schneider`. Also, -sz- in slavic language although in\n // hungarian it is pronounced `s`.\n if (\n next === 'Z' ||\n (index === 0 &&\n (next === 'L' || next === 'M' || next === 'N' || next === 'W'))\n ) {\n primary += 'S'\n secondary += 'X'\n\n if (next === 'Z') {\n index++\n }\n\n index++\n\n break\n }\n\n if (next === 'C') {\n // Schlesinger's rule.\n if (nextnext === 'H') {\n subvalue = value.slice(index + 3, index + 5)\n\n // Dutch origin, such as `school`, `schooner`.\n if (dutchSch.test(subvalue)) {\n // Such as `schermerhorn`, `schenker`.\n if (subvalue === 'ER' || subvalue === 'EN') {\n primary += 'X'\n secondary += 'SK'\n } else {\n primary += 'SK'\n secondary += 'SK'\n }\n\n index += 3\n\n break\n }\n\n if (\n index === 0 &&\n !vowels.test(characters[3]) &&\n characters[3] !== 'W'\n ) {\n primary += 'X'\n secondary += 'S'\n } else {\n primary += 'X'\n secondary += 'X'\n }\n\n index += 3\n\n break\n }\n\n if (nextnext === 'I' || nextnext === 'E' || nextnext === 'Y') {\n primary += 'S'\n secondary += 'S'\n index += 3\n break\n }\n\n primary += 'SK'\n secondary += 'SK'\n index += 3\n\n break\n }\n\n subvalue = value.slice(index - 2, index)\n\n // French such as `resnais`, `artois`.\n if (index === last && (subvalue === 'AI' || subvalue === 'OI')) {\n secondary += 'S'\n } else {\n primary += 'S'\n secondary += 'S'\n }\n\n if (\n next === 'S'\n // Bug: already taken care of by `German & Anglicization's` above:\n // || next === 'Z'\n ) {\n index++\n }\n\n index++\n\n break\n case 'T':\n if (next === 'I' && nextnext === 'O' && characters[index + 3] === 'N') {\n primary += 'X'\n secondary += 'X'\n index += 3\n\n break\n }\n\n subvalue = value.slice(index + 1, index + 3)\n\n if (\n (next === 'I' && nextnext === 'A') ||\n (next === 'C' && nextnext === 'H')\n ) {\n primary += 'X'\n secondary += 'X'\n index += 3\n\n break\n }\n\n if (next === 'H' || (next === 'T' && nextnext === 'H')) {\n // Special case `Thomas`, `Thames` or Germanic.\n if (\n isGermanic ||\n ((nextnext === 'O' || nextnext === 'A') &&\n characters[index + 3] === 'M')\n ) {\n primary += 'T'\n secondary += 'T'\n } else {\n primary += '0'\n secondary += 'T'\n }\n\n index += 2\n\n break\n }\n\n if (next === 'T' || next === 'D') {\n index++\n }\n\n index++\n primary += 'T'\n secondary += 'T'\n\n break\n case 'V':\n if (next === 'V') {\n index++\n }\n\n primary += 'F'\n secondary += 'F'\n index++\n\n break\n case 'W':\n // Can also be in middle of word (as already taken care of for initial).\n if (next === 'R') {\n primary += 'R'\n secondary += 'R'\n index += 2\n\n break\n }\n\n if (index === 0) {\n // `Wasserman` should match `Vasserman`.\n if (vowels.test(next)) {\n primary += 'A'\n secondary += 'F'\n } else if (next === 'H') {\n // Need `Uomo` to match `Womo`.\n primary += 'A'\n secondary += 'A'\n }\n }\n\n // `Arnow` should match `Arnoff`.\n if (\n ((prev === 'E' || prev === 'O') &&\n next === 'S' &&\n nextnext === 'K' &&\n (characters[index + 3] === 'I' || characters[index + 3] === 'Y')) ||\n // Maybe a bug? Shouldn't this be general Germanic?\n value.slice(0, 3) === 'SCH' ||\n (index === last && vowels.test(prev))\n ) {\n secondary += 'F'\n index++\n\n break\n }\n\n // Polish such as `Filipowicz`.\n if (\n next === 'I' &&\n (nextnext === 'C' || nextnext === 'T') &&\n characters[index + 3] === 'Z'\n ) {\n primary += 'TS'\n secondary += 'FX'\n index += 4\n\n break\n }\n\n index++\n\n break\n case 'X':\n // French such as `breaux`.\n if (\n !(\n index === last &&\n // Bug: IAU and EAU also match by AU\n // (/IAU|EAU/.test(value.slice(index - 3, index))) ||\n (prev === 'U' &&\n (characters[index - 2] === 'A' || characters[index - 2] === 'O'))\n )\n ) {\n primary += 'KS'\n secondary += 'KS'\n }\n\n if (next === 'C' || next === 'X') {\n index++\n }\n\n index++\n\n break\n case 'Z':\n // Chinese pinyin such as `Zhao`.\n if (next === 'H') {\n primary += 'J'\n secondary += 'J'\n index += 2\n\n break\n } else if (\n (next === 'Z' &&\n (nextnext === 'A' || nextnext === 'I' || nextnext === 'O')) ||\n (isSlavoGermanic && index > 0 && prev !== 'T')\n ) {\n primary += 'S'\n secondary += 'TS'\n } else {\n primary += 'S'\n secondary += 'S'\n }\n\n if (next === 'Z') {\n index++\n }\n\n index++\n\n break\n default:\n index++\n }\n }\n\n return [primary, secondary]\n}", "function formatPrefix(value) {\n var i = 0;\n if (value) {\n if (value < 0) value *= -1;\n i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10);\n i = Math.max(0, Math.min(24, Math.floor((i - 1) / 3) * 3));\n }\n var k = Math.pow(10, i);\n return {\n symbol: formatPrefixes[i / 3],\n scale: function scale(d) {\n return d / k;\n }\n };\n}", "function prefixer(prefix){\n\tthis.prefix=prefix;\n}", "function HyderabadTirupati() // extends PhoneticMapper\n{\n var map = [ \n new KeyMap(\"\\u0901\", \"?\", \"z\", true), // Candrabindu\n new KeyMap(\"\\u0902\", \"\\u1E41\", \"M\"), // Anusvara\n new KeyMap(\"\\u0903\", \"\\u1E25\", \"H\"), // Visarga\n new KeyMap(\"\\u1CF2\", \"\\u1E96\", \"Z\"), // jihvamuliya\n new KeyMap(\"\\u1CF2\", \"h\\u032C\", \"V\"), // upadhmaniya\n new KeyMap(\"\\u0905\", \"a\", \"a\"), // a\n new KeyMap(\"\\u0906\", \"\\u0101\", \"A\"), // long a\n new KeyMap(\"\\u093E\", null, \"A\", true), // long a attached\n new KeyMap(\"\\u0907\", \"i\", \"i\"), // i\n new KeyMap(\"\\u093F\", null, \"i\", true), // i attached\n new KeyMap(\"\\u0908\", \"\\u012B\", \"I\"), // long i\n new KeyMap(\"\\u0940\", null, \"I\", true), // long i attached\n new KeyMap(\"\\u0909\", \"u\", \"u\"), // u\n new KeyMap(\"\\u0941\", null, \"u\", true), // u attached\n new KeyMap(\"\\u090A\", \"\\u016B\", \"U\"), // long u\n new KeyMap(\"\\u0942\", null, \"U\", true), // long u attached\n new KeyMap(\"\\u090B\", \"\\u1E5B\", \"q\"), // vocalic r\n new KeyMap(\"\\u0943\", null, \"q\", true), // vocalic r attached\n new KeyMap(\"\\u0960\", \"\\u1E5D\", \"Q\"), // long vocalic r\n new KeyMap(\"\\u0944\", null, \"Q\", true), // long vocalic r attached\n new KeyMap(\"\\u090C\", \"\\u1E37\", \"L\"), // vocalic l\n new KeyMap(\"\\u0962\", null, \"L\", true), // vocalic l attached\n new KeyMap(\"\\u0961\", \"\\u1E39\", \"LY\"), // long vocalic l\n new KeyMap(\"\\u0963\", null, \"LY\", true), // long vocalic l attached\n new KeyMap(\"\\u090F\", \"e\", \"e\"), // e\n new KeyMap(\"\\u0947\", null, \"e\", true), // e attached\n new KeyMap(\"\\u0910\", \"ai\", \"E\"), // ai\n new KeyMap(\"\\u0948\", null, \"E\", true), // ai attached\n new KeyMap(\"\\u0913\", \"o\", \"o\"), // o\n new KeyMap(\"\\u094B\", null, \"o\", true), // o attached\n new KeyMap(\"\\u0914\", \"au\", \"O\"), // au\n new KeyMap(\"\\u094C\", null, \"O\", true), // au attached\n\n // velars\n new KeyMap(\"\\u0915\\u094D\", \"k\", \"k\"), // k\n new KeyMap(\"\\u0916\\u094D\", \"kh\", \"K\"), // kh\n new KeyMap(\"\\u0917\\u094D\", \"g\", \"g\"), // g\n new KeyMap(\"\\u0918\\u094D\", \"gh\", \"G\"), // gh\n new KeyMap(\"\\u0919\\u094D\", \"\\u1E45\", \"f\"), // velar n\n\n // palatals\n new KeyMap(\"\\u091A\\u094D\", \"c\", \"c\"), // c\n new KeyMap(\"\\u091B\\u094D\", \"ch\", \"C\"), // ch\n new KeyMap(\"\\u091C\\u094D\", \"j\", \"j\"), // j\n new KeyMap(\"\\u091D\\u094D\", \"jh\", \"J\"), // jh\n new KeyMap(\"\\u091E\\u094D\", \"\\u00F1\", \"F\"), // palatal n\n\n // retroflex\n new KeyMap(\"\\u091F\\u094D\", \"\\u1E6D\", \"t\"), // retroflex t\n new KeyMap(\"\\u0920\\u094D\", \"\\u1E6Dh\", \"T\"), // retroflex th\n new KeyMap(\"\\u0921\\u094D\", \"\\u1E0D\", \"d\"), // retroflex d\n new KeyMap(\"\\u0922\\u094D\", \"\\u1E0Dh\", \"D\"), // retroflex dh\n new KeyMap(\"\\u0923\\u094D\", \"\\u1E47\", \"N\"), // retroflex n\n new KeyMap(\"\\u0933\\u094D\", \"\\u1E37\", \"lY\"), // retroflex l\n new KeyMap(\"\\u0933\\u094D\\u0939\\u094D\", \"\\u1E37\", \"lYh\"), // retroflex lh\n\n // dental\n new KeyMap(\"\\u0924\\u094D\", \"t\", \"w\"), // dental t\n new KeyMap(\"\\u0925\\u094D\", \"th\", \"W\"), // dental th\n new KeyMap(\"\\u0926\\u094D\", \"d\", \"x\"), // dental d\n new KeyMap(\"\\u0927\\u094D\", \"dh\", \"X\"), // dental dh\n new KeyMap(\"\\u0928\\u094D\", \"n\", \"n\"), // dental n\n\n // labials\n new KeyMap(\"\\u092A\\u094D\", \"p\", \"p\"), // p\n new KeyMap(\"\\u092B\\u094D\", \"ph\", \"P\"), // ph\n new KeyMap(\"\\u092C\\u094D\", \"b\", \"b\"), // b\n new KeyMap(\"\\u092D\\u094D\", \"bh\", \"B\"), // bh\n new KeyMap(\"\\u092E\\u094D\", \"m\", \"m\"), // m\n\n // sibillants\n new KeyMap(\"\\u0936\\u094D\", \"\\u015B\", \"S\"), // palatal s\n new KeyMap(\"\\u0937\\u094D\", \"\\u1E63\", \"R\"), // retroflex s\n new KeyMap(\"\\u0938\\u094D\", \"s\", \"s\"), // dental s\n new KeyMap(\"\\u0939\\u094D\", \"h\", \"h\"), // h\n\n // semivowels\n new KeyMap(\"\\u092F\\u094D\", \"y\", \"y\"), // y\n new KeyMap(\"\\u0930\\u094D\", \"r\", \"r\"), // r\n new KeyMap(\"\\u0932\\u094D\", \"l\", \"l\"), // l\n new KeyMap(\"\\u0935\\u094D\", \"v\", \"v\"), // v\n\n\n // numerals\n new KeyMap(\"\\u0966\", \"0\", \"0\"), // 0\n new KeyMap(\"\\u0967\", \"1\", \"1\"), // 1\n new KeyMap(\"\\u0968\", \"2\", \"2\"), // 2\n new KeyMap(\"\\u0969\", \"3\", \"3\"), // 3\n new KeyMap(\"\\u096A\", \"4\", \"4\"), // 4\n new KeyMap(\"\\u096B\", \"5\", \"5\"), // 5\n new KeyMap(\"\\u096C\", \"6\", \"6\"), // 6\n new KeyMap(\"\\u096D\", \"7\", \"7\"), // 7\n new KeyMap(\"\\u096E\", \"8\", \"8\"), // 8\n new KeyMap(\"\\u096F\", \"9\", \"9\"), // 9\n\n // accents\n new KeyMap(\"\\u0951\", \"|\", \"|\"), // udatta\n new KeyMap(\"\\u0952\", \"_\", \"_\"), // anudatta\n new KeyMap(\"\\u0953\", null, \"//\"), // grave accent\n new KeyMap(\"\\u0954\", null, \"\\\\\"), // acute accent\n\n // miscellaneous\n new KeyMap(\"\\u0933\\u094D\", \"\\u1E37\", \"L\"), // retroflex l\n new KeyMap(\"\\u093D\", \"'\", \"'\"), // avagraha\n new KeyMap(\"\\u0950\", null, \"om\"), // om\n new KeyMap(\"\\u0964\", \".\", \".\") // single danda\n ];\n\n PhoneticMapper.call(this, map);\n}", "function DNAStrand(dna) {\n return dna.replace(/./g, function(c) {\n return DNAStrand.pairs[c]\n })\n }", "function DNAStrand(dna) {\n return dna.replace(/./g, function(c) {\n return DNAStrand.pairs[c]\n })\n }", "function Ge(e,t,a,s){switch(a){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "getPrefixCode() {\n return \"\";\n }", "function e(t,e,i,n){switch(i){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function BigHippo() {\n this.prefix = 'bighippo_product.';\n}", "function e(t,e,n,i){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,n,i){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,n,i){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,n,i){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,n,i){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,n,i){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,n,i){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,n,i){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,n,i){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,n,i){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function derivationToPopUpFormat(der) {\n var str = \"\";\n for (var i = 0; i < der.length; ++i)\n str += \" \" + nodeToPopUpFormat(der[i]);\n return str; \n}", "function Kn(e){var t=/(-[a-z])/g,n=function(e){return e[1].toUpperCase()},r={};for(var a in e)r[a]=e[a],r[a.replace(t,n)]=e[a];return r}", "function zu(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e.toString(10)}}", "function applyPrefixNum () {\n const pn = State.prefixNum\n State.prefixNum = ''\n return pn\n }", "function e(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,g){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function mkn(cf, tp) {\n let nm = cf;\n switch (tp) {\n case 'n':\n nm = formato_numero(cf, '2', '.', ',');\n break;\n case 'p':\n nm = formato_numero(cf, '1', '.', ',');\n break;\n default:\n }\n return nm;\n}", "get prefix(): string {\n return this.currencySymbol;\n }", "function GetBornosoftModifiedCharaceter(CUni)\r\n{\r\n\tvar CMod=CUni;\r\n\r\n\tif(LCUNI=='ক' && CUni=='হ') CMod = 'খ';\r\n\telse if(LCUNI=='গ' && CUni=='হ') CMod = 'ঘ';\r\n\telse if(LCUNI=='চ' && CUni=='হ') CMod = 'চ';\r\n\telse if(LCUNI=='জ' && CUni=='হ') CMod = 'ঝ';\r\n\telse if(LCUNI=='ট' && CUni=='হ') CMod = 'ঠ';\r\n\telse if(LCUNI=='ড' && CUni=='হ') CMod = 'ঢ';\r\n\telse if(LCUNI=='ত' && CUni=='হ') CMod = 'থ';\r\n\telse if(LCUNI=='দ' && CUni=='হ') CMod = 'ধ';\r\n\telse if(LCUNI=='প' && CUni=='হ') CMod = 'ফ';\r\n\telse if(LCUNI=='ব' && CUni=='হ') CMod = 'ভ';\r\n\telse if(LCUNI=='স' && CUni=='হ') CMod = 'শ';\r\n\telse if(LCUNI=='ড়' && CUni=='হ') CMod = 'ঢ়';\r\n\r\n\telse if(LCUNI=='ণ' && CUni=='গ') CMod = 'ঙ';\r\n\telse if(LCUNI=='ন' && CUni=='গ') CMod = 'ং';\r\n\t\r\n\telse if(LCUNI=='ণ' && CUni=='ঘ') CMod = 'ঞ';\r\n\r\n\telse if(LCUNI=='ণ' && CUni=='ণ') CMod = 'ঁ';\r\n\r\n\telse if(LCUNI=='ঃ' && CUni=='ঃ') CMod = 'ঃ';\r\n\t\r\n\telse if(LCUNI=='ট' && CUni=='ট') CMod = 'ৎ';\r\n\t\r\n\telse if(LCUNI=='া' && CUni=='ো') CMod = 'অ';\r\n\telse if(LCUNI=='ি' && CUni=='ি') CMod = 'ী';\r\n\telse if(LCUNI=='ই' && CUni=='ই') CMod = 'ঈ';\r\n\telse if(LCUNI=='ু' && CUni=='ু') CMod = 'ূ';\r\n\telse if(LCUNI=='উ' && CUni=='উ') CMod = 'ঊ';\r\n\telse if(LCUNI=='ও' && CUni=='ই') CMod = 'ঐ';\r\n\telse if(LCUNI=='ো' && CUni=='ি') CMod = 'ৈ';\r\n\telse if(LCUNI=='ও' && CUni=='উ') CMod = 'ঔ';\r\n\telse if(LCUNI=='ো' && CUni=='ু') CMod = 'ৌ';\r\n\telse if(LCUNI=='ৃ' && CUni=='র') CMod = 'ৃ';\r\n\telse if(LCUNI=='ঋ' && CUni=='ড়') CMod = 'ঋ';\r\n\r\n\treturn CMod;\r\n}", "function Bi(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function goodbyePrefix(id) {\n\treturn \"0x\" + id.toString(16);\n}", "get prefix() {\n return this.currencySymbol;\n }", "function dn(t) {\n switch (t) {\n case 1:\n return \"first\";\n\n case 2:\n return \"second\";\n\n case 3:\n return \"third\";\n\n default:\n return t + \"th\";\n }\n}", "function get_dec_name()\n{\n\treturn \"SSI\";\n}", "function makePrefixer(prefijo){\n return function ponerPrefijo (palabra){\n console.log(prefijo + palabra)\n }\n}", "function t(e,t,i,n){switch(i){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function c(e,c,t,n){switch(t){case\"s\":return c?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(c?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(c?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(c?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(c?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(c?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(c?\" жил\":\" жилийн\");default:return e}}", "function PlcGeral(){\r\n}", "function letraDni(dni) {\n return \"TRWAGMYFPDXBNJZSQVHLCKE\".charAt(dni % 23); //------> nos muestra la posicion del string, tomando el resto del numero de DNI\n}", "function prefix() {\n var prefix = '<span class=\"prior-prompt\">Sensory_5@Coding-Challenge: ~ $ </span>' + input();\n return prefix;\n}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,i){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,n,a){switch(n){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,a,n){switch(a){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "function t(e,t,a,n){switch(a){case\"s\":return t?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return e+(t?\" секунд\":\" секундын\");case\"m\":case\"mm\":return e+(t?\" минут\":\" минутын\");case\"h\":case\"hh\":return e+(t?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return e+(t?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return e+(t?\" сар\":\" сарын\");case\"y\":case\"yy\":return e+(t?\" жил\":\" жилийн\");default:return e}}", "get prefix()\n {\n let r = this.config.get('general', 'prefix');\n return r ? r : '!';\n }", "prefixed(prefix) {\n if (prefix === '-ms-') {\n return ':-ms-input-placeholder'\n }\n return `:${prefix}placeholder-shown`\n }", "function e(t,e,r,n){switch(r){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,r,n){switch(r){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "get derivation () {\n\t\treturn this._derivation;\n\t}", "function generateMnemonic() {\n const mnemonic = bip39.generateMnemonic();\n return mnemonic.split(\" \").slice(0, 3).join(\" \");\n}", "parsePrefixString() {\n const matches = this.prefixString.trim().match(this._prefixRegex);\n this.short = matches[1];\n this.long = matches[2].replace(/[<>]/g, \"\");\n this.representations.push(matches[1], matches[2]);\n }", "function StringTo2KeyDTMF(cad)\r\n{\r\n let aReturn='';\r\n let i=0;\r\n try\r\n {\r\n for (i=0;i<cad.length;i++)\r\n {\r\n aReturn = aReturn+CharTo2KeyDTMF(cad[i].toUpperCase());\r\n }\r\n }\r\n catch(err)\r\n {\r\n DebugLog(err.message.toString());\r\n } \r\n return aReturn;\r\n}", "function e(t,e,n,r){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,n,r){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,n,r){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}", "function e(t,e,n,r){switch(n){case\"s\":return e?\"хэдхэн секунд\":\"хэдхэн секундын\";case\"ss\":return t+(e?\" секунд\":\" секундын\");case\"m\":case\"mm\":return t+(e?\" минут\":\" минутын\");case\"h\":case\"hh\":return t+(e?\" цаг\":\" цагийн\");case\"d\":case\"dd\":return t+(e?\" өдөр\":\" өдрийн\");case\"M\":case\"MM\":return t+(e?\" сар\":\" сарын\");case\"y\":case\"yy\":return t+(e?\" жил\":\" жилийн\");default:return t}}" ]
[ "0.6107145", "0.5719765", "0.5620241", "0.5559519", "0.5518969", "0.55171746", "0.55019695", "0.55002034", "0.54467845", "0.5441924", "0.54122806", "0.54108983", "0.53885466", "0.5377489", "0.5347215", "0.53189534", "0.531698", "0.52942127", "0.52942127", "0.5292685", "0.5285499", "0.5268323", "0.5263678", "0.5246615", "0.5246615", "0.5246615", "0.5246615", "0.5246615", "0.5246615", "0.5246615", "0.5246615", "0.5246615", "0.5246615", "0.52465796", "0.52447253", "0.5238254", "0.5232169", "0.5227728", "0.52254665", "0.52090514", "0.52052027", "0.51863676", "0.5180259", "0.517637", "0.51606935", "0.5160105", "0.5157564", "0.5145998", "0.5131876", "0.5119786", "0.5110642", "0.5103991", "0.5103649", "0.50934696", "0.50934696", "0.50934696", "0.50934696", "0.50934696", "0.50934696", "0.50934696", "0.50934696", "0.50934696", "0.50934696", "0.50934696", "0.50934696", "0.50934696", "0.50934696", "0.50934696", "0.50934696", "0.50934696", "0.50934696", "0.50934696", "0.50934696", "0.5086908", "0.5086908", "0.5086908", "0.5086908", "0.5086908", "0.5086908", "0.5086908", "0.5086908", "0.5086908", "0.5086908", "0.5086908", "0.5086908", "0.5086908", "0.5086037", "0.5086037", "0.5085548", "0.5078427", "0.50707316", "0.50707316", "0.5070478", "0.50523746", "0.50443536", "0.50419265", "0.50372875", "0.50372875", "0.50372875", "0.50372875" ]
0.6622089
0
fungsi pencarian akar kata
function stemming(kata,selesai){ var kataAsal = kata; var sam=kata var cekKata ="" cekKamus(kata,function(data6){ cekKata=data6 if(cekKata == true){ // Cek Kamus selesai(kata); // Jika Ada maka kata tersebut adalah kata dasar }else { //jika tidak ada dalam kamus maka dilakukan stemming Del_Inflection_Suffixes(sam,function(data){ sam = data cekKamus(sam,function(data1){ if(data1){ selesai(sam) }else{ Del_Derivation_Suffixes(sam,function(data2){ sam = data2 cekKamus(sam,function(data3){ if(data3){ selesai(sam) }else{ Del_Derivation_Prefix(sam,function(data4){ sam = data4 cekKamus(sam,function(data5){ if(data5){ selesai(sam) }else{ selesai(kataAsal) } }) });} }) });} }) }); } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function fuctionPanier(){\n\n}", "function cargarpista1 (){\n \n}", "function lalalala() {\n\n}", "function kalkulasi(a, b) {\n return {\n tambah: a + b,\n kurang: a - b,\n kali: a * b,\n bagi: a / b\n }\n}", "function PlcGeral(){\r\n}", "function hitungLuasPersegiPanjang (panjang,lebar){\n //tidak ada nilai balik\n var luas = panjang * lebar\n return luas\n}", "function Komunalne() {}", "function jeden() {\n\n //deklaracja zmiennej zmienna1 - zmienna lokalna dla funkcji jeden\n var zmienna1 = 1;\n\n //Deklaracja funkcji dwa we wnętrzu funkcji jeden. stworzenie nowego zakresu dla funkcji dwa\n function dwa() {\n\n //wypisanie do konsoli zawartości zmiennej jeden - jest to zmienna dostępne z poziomu funkcji dwa\n console.log(zmienna1);\n\n //deklaracja zmienna2 jako zmiennej lokalnej dla zakresu dwa\n var zmienna2 = 3;\n }\n\n //wywołanie funkcji dwa w ramach wykonywania funkcji jeden\n dwa();\n\n //wypisanie do do konsoli zawartosci zmiennej2 - niedostępnej z poziomu funkcji jeden ponieważ jest zadeklarowana jako zmienna lokalna dla funkcji dwa\n console.log(zmienna2)\n}", "function kalikanDua(angka) {\n return angka * 2;\n}", "function tampilkanAngka(angkaPertama, angkaKedua) {\n return angkaPertama + angkaKedua;\n}", "function TinhTien() {\n //Lay loai xe\n var loaiXe = LayloaiXe();\n console.log(loaiXe);\n //Lay thoi gian cho\n var tgCho = getEle('tgCho').value;\n //lay so km\n var soKM = getEle('soKm').value;\n var tongHoaDon = 0;\n //Tinh theo loai xe\n switch (loaiXe) {\n case 'uberX':\n tongHoaDon = TinhTheoLoaiXe(soKM, tgCho, UberX_1, UberX_2, UberX_3, tgCho_UberX);\n break;\n case 'uberSUV':\n tongHoaDon = TinhTheoLoaiXe(soKM, tgCho, UberSUV_1, UberSUV_2, UberSUV_3, tgCho_UberSUV);\n break;\n case 'uberBlack':\n tongHoaDon = TinhTheoLoaiXe(soKM, tgCho, UberBlack_1, UberBlack_2, UberBlack_3, tgCho_UberBlack);\n break;\n default:\n break;\n }\n}", "function cetakPesan(nama, bahasa='id')\n{\n var pesan = 'Selamat datang, ' + nama;\n if(bahasa == 'en')\n {\n pesan = 'Welcome, ' + nama;\n }\n else if(bahasa=='id'){\n console.log(pesan);\n }\n console.log('Mohon maaf bahasa yang diminta belum terdaftar');\n}", "function PerkalianV2 (a, b) {\n //local variabel\n let hasil = a * b\n\n //give return value, spy value dr hasil bisa dipake diluar\n return hasil\n}", "function fun1(){} //toda a função de js retorna alguma coisa", "function sveikinuosi( funkcijosPavadinimas ){\n console.log(\"Labutaitis\");\n if (funkcijosPavadinimas != null && funkcijosPavadinimas != undefined) {\n funkcijosPavadinimas();\n }\n}", "function hitungLuasSegiEmpat(sisi){\n //tidak ada nilai balik\n var luas = sisi * sisi\n return luas\n}", "function miFuncion(){}", "function miFuncion(){}", "function miFuncion(){}", "function Organigrama(){\n}", "function mostrarPalabra(){\n \n}", "function operator(angka, angkalain, perhitungan){\n var hasil = 0\n if(perhitungan=='tambah'){\n hasil=angka+angkalain\n }else if(perhitungan=='kurang'){\n hasil=angka-angkalain\n }else if(perhitungan=='bagi'){\n hasil=angka/angkalain\n }else if(perhitungan=='kali'){\n hasil=angka*angkalain\n }\n return hasil //return untuk apa yg kita pengen\n}", "function bodoAmat(){\r\n console.log(\"Ini result Function Bodo Amat\");\r\n}", "function kaliTerusRekursif(angka) {\r\n // you can only write your code here!\r\n let angkaString = angka.toString();\r\n let hasil = kaliRekursif(angka);\r\n let hasilString = hasil.toString();\r\n if(hasilString.length > 1){\r\n hasil = kaliTerusRekursif(hasil);\r\n }\r\n return hasil;\r\n \r\n}", "function klikni(){\n console.log(\"kliknuto\");\n}", "function afase_pianeta(njd,AR,DE,dist_ps,dist_pt){\n\n // funzione per il calcolo dell'angolo di fase per un pianeta.\n // AR,DE sono le coordinate equatoriali decimali, del pianeta.\n // njd= numero del giorno giuliano.\n // dist_ps=distanza pianeta-sole in UA.\n // dist_pt=distanza pianeta-Terra in UA.\n // by Salvatore Ruiu - gennaio 2013.\n\n var coo_sole=pos_sole(njd); // coordinate equatoriali decimali del Sole.\n var Rs=coo_sole[4]; // distanza Terra-Sole. \n var elongaz=elong(AR,DE,coo_sole[0],coo_sole[1]); // elongazione in gradi dal Sole.\n\n // calcolo dell'angolo di fase in gradi . \n\n var Dpt= dist_pt; // distanza pianeta-terra.\n var Dts= Rs; // distanza terra-sole.\n var Dps= dist_ps; // distanza pianeta-sole.\n\n // risolve il teorema del coseno (noti i 3 lati del triangolo).\n\n var delta_fase=(Dts*Dts+Dps*Dps-Dpt*Dpt)/(2*Dps*Dts);\n delta_fase=Math.acos(delta_fase); \n delta_fase=Rda(delta_fase);\n\n var angolo_fase=180-Math.abs(elongaz)-delta_fase; // risultato: angolo di fase in gradi.\n\nreturn angolo_fase;\n\n}", "function miFuncion (){}", "function anhadir() {\n k.anhadirDatos();\n}", "getResultatCodificat(){ // SI EL MÈTODE NO PASSA ALGUN VALOR, SE LI POSSA this. MÉS EL ATRIBUT CORRESPONENT.\n this.eliminarEspaisBlanc();\n this.senseAccent();\n for (var i = 0; i < this._entrada.length; i++){\n\n // IGUALEM LA LLARGADA DE LA CLAU A LA DE L'ENTRADA\n var y = 0;\n var max_lenght = this._entrada.length;\n while (this._entrada.length != this._clau.length){\n\n this._clau = this._clau + this._clau[y];\n\n if(y >= max_lenght){\n\n y = 0;\n }\n else{\n\n y++;\n }\n }\n\n // BUSQUEM ON ESTAN SITUATS TANT LA LLETRA DE L'ENTRADA COM DE LA CLAU\n var posicio_lletra_entrada = this._alfabet.indexOf(this._entrada[i]);\n var posicio_lletra_clau = this._alfabet.indexOf(this._clau[i]);\n\n // SUMEM LES DUES POSICIONS\n var suma_posicions = posicio_lletra_entrada + posicio_lletra_clau;\n\n // ANEM RESTANT MENTRE QUE EL MOD SIGUI MÉS GRAN QUE EL LENGTH DEL ABECEDARI\n while (suma_posicions >= this._alfabet.length){\n\n suma_posicions = suma_posicions - this._alfabet.length;\n }\n \n // ARA BUSQUEM LA LLETRA AMB LA QUAL SUBSTITUIREM L'ENTRADA\n this._resultat = this._resultat + this._alfabet[suma_posicions];\n }\n\n // RETORNEM EL RESULTAT\n return (document.form.sortida.value = this._resultat);\n }", "function nombreFuncion(parametro){\n return \"regresan algo\"\n}", "function karinaFaarNotifikation() {\n\n\n\n}", "function dwa() {\n \n //wypisanie do konsoli zawartości zmienna1, zdeklarowanej w funkcji nadrzednej, wartośc zostanie pobrana poprzez hoisting\n console.log(zmienna1);\n \n //Deklaracja i przypisanie w funkcji wewnetrznej\n var zmienna2 = 3;\n }", "function trajanjeFn(data) {\n trajanje = data.prijeposlije === \"PRIJE\" ? trajanjeU : trajanjeP;\n return trajanje;\n }", "function munculkanAngkaDua() {\n return 2;\n}", "function pasveikinaKauna() {\n console.log(\"Labas vakaras Kaune!\");\n}", "function kalikan(num1, num2) {\n // Code kamu mulai dari sini\n var kali = num1 * num2;\n\n\n // Tampilkan jawaban dengan cara document.getElementById(\"jawaban2\").innerHTML seperti di CONTOH\n document.getElementById(\"jawaban2\").innerHTML = kali;\n }", "fungsiMakan() {\n return `Blubuk kelas parent di ambil alih blubuk ini`;\n }", "efficacitePompes(){\n\n }", "function fun1( /*parametros opcionais*/ ){ /*retorno opcional*/ }", "function profil(nama, kota, lahir)\n{\n console.log('Nama saya ' + nama + '<br/>');\n console.log('Saya berasal dari kota ' + kota + '<br/>');\n console.log('Lahir pada tahun '+ lahir + '<br/>');\n \n}", "function TinhTheoLoaiXe(sokm, tgcho, giaLoai1, giaLoai2, giaLoai3, tgChoTheoLoai) {\n var tien = 0;\n if (sokm <= 1) {\n tien = sokm * giaLoai1 + tgcho * tgChoTheoLoai;\n // console.log(tien);\n } else if (sokm > 1 && sokm < 21) {\n tien = giaLoai1 + (sokm - 1) * giaLoai2 + tgcho * tgChoTheoLoai;\n // console.log(tien);\n } else if (sokm >= 21) {\n tien = giaLoai1 + 19 * giaLoai2 + (sokm - 20) * giaLoai3 + tgcho * tgChoTheoLoai;\n // console.log(tien);\n }\n return document.getElementById('xuatTien').innerHTML = tien + ' vnđ';\n}", "function Del_Derivation_Prefix(kata,selesai){\n\tvar kataAsal = kata;\nvar __kata,__kata__=\"\"\n\t/* —— Tentukan Tipe Awalan ————*/\nif(kata.match(/^(di|[ks]e)/)){ // Jika di-,ke-,se-\n __kata = kata.replace(/^(di|[ks]e)/,'');\n \n cekKamus(__kata,function(data){\n\t if(data){\n\t\tselesai(__kata)\n\t }else{\n\t \t\n\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\n\t\t\t\n cekKamus(__kata__,function(data){\n\t if(data){\n\t\t selesai(__kata__)\n\t }else if(kata.match(/^(diper)/)){ //diper-\n\t\t\n\t\t\t__kata = kata.replace(/^(diper)/,'');\n\t\t\t Del_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\tselesai(__kata__)\t\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t \t\n\t\t\t });\n\t\t\n\t\t\t\n\t\t\t\n\t\t}else if(kata.match(/^(ke[bt]er)/)){ //keber- dan keter-\n\t\t __kata = kata.replace(/^(ke[bt]er)/,'');\n\t\t\t Del_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\t\n\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t});\n\t\t\n\t\t\t\n\t\t\t\n\t\t} else{\n\t\t\tselesai(kata.replace(/^(di|[ks]e)/,''))\n\t\t}\n })\n }) \t\n\t }\n })\t\t\n\t\t\n\t}else if(kata.match(/^([bt]e)/)){ //Jika awalannya adalah \"te-\",\"ter-\", \"be-\",\"ber-\"\n\t\t\n\t\t __kata = kata.replace(/^([bt]e)/,'');\n\t\t\n\t\tcekKamus(__kata,function(data){\n\t\t\tif(data){\n\t\t\t\tselesai(__kata)\n\t\t\t}else{\n\t\t__kata = kata.replace(/^([bt]e[lr])/,'');\t\n\t\t\n\t\tcekKamus(__kata,function(data){\n\t\t\tif(data){\n\t\t\t\tselesai(__kata)\n\t\t\t}else{\n\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\n\t\tcekKamus(__kata__,function(data){\n\t\t\tif(data){\n\t\t\t\tselesai(__kata__)\n\t\t\t}else{\n\t\t\t\tselesai(kataAsal)\n\t\t\t}\n\t\t})\n\t\t})}\t\n\t\t\t\n\t\t})}\n\t\t});\n\t\t\n\t\t}else if(kata.match(/^([mp]e)/)){\n\t\t__kata = kata.replace(/^([mp]e)/,'');\n\t\t\n\t\tcekKamus(__kata,function(data){\n\t\t\tif(data){\n\t\t\tselesai(__kata)\n\t\t\t}else\n\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\n\t\tcekKamus(__kata__,function(data){\n\t\tif(data){\n\t\t\tselesai(__kata__)\n\t\t}else if(kata.match(/^(memper)/)){\n\t\t\t__kata = kata.replace(/^(memper)/,'');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__=data\n\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t\n\t\t})}\n\t\t\t})\n\t\t\n\t\t\t\n\t\t\t\n\t\t}else if(kata.match(/^([mp]eng)/)){\n\t\t\t__kata = kata.replace(/^([mp]eng)/,'');\n\t\tcekKamus(__kata,function(data1){\n\t\t\tif(data1){\n\t\t\t\tselesai(__kata)\n\t\t\t}else{\n\t\t\tDel_Derivation_Suffixes(__kata,function(data2){\n\t\t\t__kata__=data2\n\t\t\tcekKamus(__kata__,function(data3){\n\t\t\t\tif(data3){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t__kata = kata.replace(/^([mp]eng)/,'k');\n\t\t\tcekKamus(__kata,function(data4){\n\t\t\t\tif(data4){\n\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data5){\n\t\t\t__kata__ =data5\n\t\t\tcekKamus(__kata__,function(data6){\n\t\t\t\tif(data6){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\t__kata = kata.replace(/^([mp]enge)/,'');//menge- dan penge-\n\t\t\tcekKamus(__kata,function(data4){\n\t\t\t\tif(data4){\n\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data5){\n\t\t\t__kata__ =data5\n\t\t\tcekKamus(__kata__,function(data6){\n\t\t\t\tif(data6){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t \t\n\t\t\t });\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t})\n\t\t\t\t}\n\t\t\t})\n\t\t\t \t\n\t\t\t });\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t})\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t})\n\t\t\t \t\n\t\t\t });}\n\t\t})\n\t\t\t \n\t\t}else if(kata.match(/^([mp]eny)/)){\n\t\t\t__kata = kata.replace(/^([mp]eny)/,'s');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ =data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\tif(data){\n\t\t\t\tselesai(__kata__)\n\t\t\t}else{\n\t\t\t\tselesai(kataAsal)\n\t\t\t}\n\t\t})\n\t\t\t});}\n\t\t\t})\n\t\t\t\n\t\t\t \n\t\t\n\t\t\t\n\t\t}else if(kata.match(/^([mp]e[lr])/)){\n\t\t\t__kata = kata.replace(/^([mp]e[lr])/,'');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ =data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\tif(data){\n\t\t\t\tselesai(__kata__)\n\t\t\t}else{\n\t\t\t\tselesai(kataAsal)\n\t\t\t}\n\t\t\t})\n\t\t\t \t\n\t\t\t })}\n\t\t\t})\n\t\t\t\n\t\t}else if(kata.match(/^([mp]en)/)){\n\t\t\t__kata = kata.replace(/^([mp]en)/,'t');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ =data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\tselesai(__kata__)\t\n\t\t\t\t}else{\n\t\t\t\t__kata = kata.replace(/^([mp]en)/,'');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\tselesai(__kata)\n\t\t\t\t}else {\n\t\t\t\t\t\n\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ = data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t\t\n\t\t\t});}\n\t\t\t})}\n\t\t\t})\n\t\t\t \t\n\t\t\t });}\n\t\t\t\t\n\t\t\t})\n\t\t\t\n\t\t\n\t\t\t\n\t\t}else if(kata.match(/^([mp]em)/)){\n\t\t\t__kata = kata.replace(/^([mp]em)/,'');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ = data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t__kata = kata.replace(/^([mp]em)/,'p');\n\t\t\tcekKamus(__kata,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata)\n\t\t\t\t}else{\n\t\t\t\tDel_Derivation_Suffixes(__kata,function(data){\n\t\t\t__kata__ = data\t\n\t\t\tcekKamus(__kata__,function(data){\n\t\t\t\tif(data){\n\t\t\t\t\tselesai(__kata__)\n\t\t\t\t}else{\n\t\t\t\t\tselesai(kataAsal)\n\t\t\t\t}\n\t\t\t})\n\t\t\t});}\n\t\t\t})}\n\t\t\t})\n\t\t\t});}\n\t\t\t})\n\t\t\t}\t\n\t\t\n\t\t})\n\t\t \t\n\t\t });\n\t\t})\n\t\t\n\t\t \n\t}else{\n\tselesai(kataAsal)\n\t}\n}", "function hitungLuasSegitiga(alas,tinggi) {\n var luas = 1/2 * alas * tinggi;\n\n return luas;\n\n}", "function mojaFunkcija(){\n console.log('Zdarvo svete!');\n}", "function teriak() {\n // Tulis Code mulai di sini\n document.getElementById(\"jawaban1\").innerHTML = \"Aku Teriak\"\n // Tampilkan dengan cara document.getElementById(\"jawaban1\").innerHTML seperti di CONTOH.\n }", "function Angkot(supir, trayek, penumpang, kas) {\n // Property dan method yang dibutuhkan\n this.supir = supir;\n this.trayek = trayek;\n this.penumpang = penumpang;\n this.kas = kas; \n\n this.penumpangNaik = function(namaPenumpang) {\n this.penumpang.push(namaPenumpang);\n return this.penumpang;\n }\n\n this.penumpangTurun = function (namaPenumpang, bayar) {\n if( this.penumpang.length === 0 ) {\n alert('Angkot masih kosong!');\n return false;\n }\n\n for( var i = 0; i < this.penumpang.length; i++ ) {\n if( this.penumpang[i] === namaPenumpang ) {\n this.penumpang[i] = undefined;\n this.kas += bayar;\n return this.penumpang;\n }\n }\n }\n}", "function calculateProduksi() {\n var permintaan = document.getElementById('permintaan').value;\n var persediaan = document.getElementById('persediaan').value;\n\n document.write(defuzzyfikasi(permintaan, persediaan));\n }", "function paz(){\n\tDepartamento = new Array('<p>La Paz</p>');\n\tHistoria = new Array('<p class=\"text-justify\">La Paz es un departamento de El Salvador ubicado en la zona oriental del país. Limita al Norte con la república de Honduras; al Sur y al Oeste con el departamento de San Miguel, y al Sur y al Este con el departamento de La Unión. Su cabecera departamental es San Francisco. Morazán comprende un territorio de 1 447 km² y cuenta con una población de 181 285 habitantes.</p>');\n\t/*Declaracion de Variable Interna para recorrer el arreglo de Municipios,\n\tde la Misma manera para recorrer los elementos de otros arreglos*/\n\tvar Municipioss, Municipioss2, rios, lagos, volcanes, centertour, personaje;\n\tMunicipioss = \"\";\n\tMunicipios = new Array('<ol><span class=\"glyphicon glyphicon-home\"></span> La Union</ol>','<ol><span class=\"glyphicon glyphicon-home\"></span> Yucuaiquin</ol>', '<ol><span class=\"glyphicon glyphicon-home\"></span> Intipuca</ol>','<ol><span class=\"glyphicon glyphicon-home\"></span> El Carmen</ol>','<ol><span class=\"glyphicon glyphicon-home\"></span> Bolivar</ol>', '<ol><span class=\"glyphicon glyphicon-home\"></span> Santa Rosa de Lima</ol>', '<ol><span class=\"glyphicon glyphicon-home\"></span> Anamoros</ol>', '<ol><span class=\"glyphicon glyphicon-home\"></span> Concepcion de Oriente</ol>','<ol><span class=\"glyphicon glyphicon-home\"></span> Lislique </ol>');\n\tfor(i = 0; i < Municipios.length; i++){\n\t\tMunicipioss += Municipios[i];\n\t}\n\tMuniciipios2 = new Array('<ol><span class=\"glyphicon glyphicon-home\"></span> San Alejo</ol>','<ol><span class=\"glyphicon glyphicon-home\"></span> Conchagua</ol>', '<ol><span class=\"glyphicon glyphicon-home\"></span> San Jose</ol>','<ol><span class=\"glyphicon glyphicon-home\"></span> Yayantique</ol>','<ol><span class=\"glyphicon glyphicon-home\"></span> Meanguera del Golfo</ol>', '<ol><span class=\"glyphicon glyphicon-home\"></span> Pasaquina</ol>', '<ol><span class=\"glyphicon glyphicon-home\"></span> Nueva Esparta</ol>', '<ol><span class=\"glyphicon glyphicon-home\"></span> Poloros</ol>');\n\tfor(m = 0; m< Municiipios2.length; m++){\n\t\tMunicipioss2 += Municiipios2[m];\n\t}\n\tRios = new Array('<ol class=\"text-center\"><span class=\"glyphicon glyphicon-ok\"></span> PLaya El Jaguey</ol>', '<ol class=\"text-center\"><span class=\"glyphicon glyphicon-ok\"></span> Playa Blanca</ol>');\n\trios = \"\";\n\tfor(j = 0; j < Rios.length; j++){\n\t\trios += Rios[j];\n\t}\n\tVolcanes = new Array('<ol class=\"text-center\"><span class=\"glyphicon glyphicon-ok\"></span> Volcan Conchagua</ol>');\n\tPersonajes = new Array('<ol><span class=\"glyphicon glyphicon-ok\"></span> Antonio Grau Mora</ol>', '<ol><span class=\"glyphicon glyphicon-ok\"></span> Maria Cegarra Salcedo</ol>', '<ol><span class=\"glyphicon glyphicon-ok\"></span> Asensio Saez</ol>');\n\tpersonaje = \"\";\n\tfor(k = 0; k < Personajes.length; k++){\n\t\tpersonaje += Personajes[k];\n\t}\n\tCentroTour = new Array('<ol class=\"text-center\"><span class=\"glyphicon glyphicon-ok\"></span> Parque de la Familia</ol>', '<ol class=\"text-center\"><span class=\"glyphicon glyphicon-ok\"></span> Bosque Conchagua</ol>');\n\tcentertour = \"\";\n\tfor(c = 0; c < CentroTour.length; c++){\n\t\tcentertour += CentroTour[c];\n\t}\n\n\tdocument.getElementById(\"Departament\").innerHTML = Departamento[0];\n\tdocument.getElementById(\"History\").innerHTML = Historia[0];\n\tdocument.getElementById(\"Municipio\").innerHTML = Municipioss;\n\tdocument.getElementById(\"Municipio2\").innerHTML = Municipioss2;\n\tdocument.getElementById(\"centro\").innerHTML = centertour;\n\tdocument.getElementById(\"Persons\").innerHTML = personaje;\n\tdocument.getElementById(\"river\").innerHTML = rios;\n\tdocument.getElementById(\"volca\").innerHTML = Volcanes[0];\n}", "function tukarBesarKecil(kalimat) {\n // INISIALISASI VARIABEL LIBRARY ABJAD DAN INDEKS ABJAD\n var lowAbjad = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];\n\n var upAbjad = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];\n\n var indexAbjad = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26];\n\n var i = 0;\n\n var resultOfTransform = [];\n\n // FUNCTION MENGECEK HURUF LOWERCASE\n function isItLowercase(huruf) {\n for (let i=0; i<lowAbjad.length; i++) {\n if (huruf === lowAbjad[i]) {\n return true;\n }\n }\n }\n\n // FUNCTION MENGECEK HURUF UPPERCASE\n function isItUppercase(huruf) {\n for (let i=0; i<upAbjad.length; i++) {\n if (huruf === upAbjad[i]) {\n return true;\n }\n }\n }\n\n // MENGAMBIL HURUF DARI ARRAY KALIMAT DAN MELAKUKAN PENGECEKAN UP/LOW CASE\n for (i; i<kalimat.length; i++) {\n // find indexAbjad of kalimat[i]\n var character = kalimat[i];\n //console.log(character);\n if (isItUppercase(character) === true) {\n // check indeks abjad\n for (var j=0; j<upAbjad.length; j++) {\n if (character === upAbjad[j]) {\n // transform to lowercase\n resultOfTransform.push(lowAbjad[j]);\n }\n }\n } else if (isItLowercase(character) === true) {\n for (var k=0; k<lowAbjad.length; k++) {\n if (character === lowAbjad[k]) {\n // transform to uppercase\n resultOfTransform.push(upAbjad[k]);\n }\n }\n } else { // mengembalikan nilai kalimat[i] sesuai nilai asal\n resultOfTransform.push(kalimat[i]);\n }\n }\n\n // merubah array resToString ke dalam bentuk STRING\n var resToString = resultOfTransform.toString();\n var finalResult = '';\n\n // membuang setiap tanda koma hasil dari transform array ke string\n for (var m=0; m<resToString.length; m++) {\n if (resToString[m] !== ',') {\n finalResult += resToString[m];\n }\n }\n\n // mengembalikan hasil\n return finalResult;\n}", "function contrari(fantasma){\n var vContrari;\r\n if(fantasma[3] == 1) vContrari = 3;\n if(fantasma[3] == 2) vContrari = 4;\n if(fantasma[3] == 3) vContrari = 1;\n if(fantasma[3] == 4) vContrari = 2;\n return vContrari;\r\n}", "function panggilParameter(idNegara, dataKota) {\n console.log(idNegara);\n console.log(dataKota);\n}", "function calculocompraslocales(cant,costo)\n{\n var ret; \n var pu//preciounitario\n pu=costo/cant;// calculamos el costo unitario \n //if($(\"#nfact_imp\").val()!=\"SF\") //si tiene el texto SF es sin factura \n // ret=pu*glob_factorIVA; //confactura\n //else \n // ret=pu*glob_factorRET+pu; //sinfactura \n // return ret;\n\n}", "function ucapSalam() {\n return \"Selamat Siang\"; //return nilai harus membuat satu variable utk meyimpan nilai yang akan di return\n}", "function naikAngkot(arrPenumpang) {\n rute = ['A', 'B', 'C', 'D', 'E', 'F'];\n //your code here\n if (arrPenumpang.length === 0) {\n \treturn '[]';\n }\n var daftarPenumpang = [];\n for (var i = 0; i < arrPenumpang.length; i++) {\n \tvar dataPenumpang = {};\n \tdataPenumpang.penumpang = arrPenumpang[i][0];\n \tdataPenumpang.naikDari = arrPenumpang[i][1];\n \tdataPenumpang.tujuan = arrPenumpang[i][2];\n \tdataPenumpang.bayar = (rute.indexOf(arrPenumpang[i][2])-rute.indexOf(arrPenumpang[i][1]))*2000;\n \tdaftarPenumpang.push(dataPenumpang);\n }\n return daftarPenumpang;\n}", "function Interfaz(){}", "function fieMetFunctionAlsParameter(eenFunctie){\n console.log(\"zo meteen wordt de doorgegeven function uitgevoerd\");\n eenFunctie();\n}", "function cfasi_lunari(mese,anno,fase){\n\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) Luglio 2010\n // funzione per il calcolo delle fasi lunari.\n // mese= numero del mese da 1 a 12.\n // anno=anno di riferimento.\n // k=0.00 per la luna nuova\n // k=0.25 per il primo quarto.\n // k=0.50 per la luna piena\n // k=0.75 per l'ultimo quarto.\n // fase= valore numerico per la fase 0 - 0.25 - 0.50 - 0.75 sono ammessi solo questi valori.\n \nvar anno_dec=anno+(mese/12);\nvar k=(anno_dec-1900)*12.3685; // calcolo della costante k. (parseInt) tronca la parte decimale\n k=parseInt(k)*1+fase*1;\n \nvar T=k/1236.85;\n\nvar fseno=166.56+132.87*T-0.009173*T*T;\n fseno=fseno/180*Math.PI;\n\nvar njd_fase =2415020.75933+29.53058868*k+0.0001178*T*T-0.000000155*T*T*T+0.00033*Math.sin(fseno);\n\n // calcolo anomalia media del sole.\n\nvar M=359.2242+29.10535608*k-0.0000333*T*T-0.00000347*T*T*T;\n M=gradi_360(M);\n M=M/180*Math.PI;\n\n // calcolo anomalia media della luna.\n\nvar M1=306.0253+385.81691806*k+0.0107306*T*T+0.00001236*T*T*T;\n M1=gradi_360(M1);\n M1=M1/180*Math.PI;\n\n // calcolo dell'argomento della latitudine della luna.\n\nvar F=21.2964+390.67050646*k-0.0016528*T*T-0.00000239*T*T*T;\n F=gradi_360(F);\n F=F/180*Math.PI;\n\n // calcolo correzioni per la luna nuova e piena.\n\nvar correzione1=0;\n\nif (fase==0 || fase==0.50) {\n \n correzione1= (0.1734-0.000393*T)*Math.sin(M)\n +0.0021*Math.sin(2*M)\n -0.4068*Math.sin(M1)\n +0.0161*Math.sin(2*M1)\n -0.0004*Math.sin(3*M1)\n +0.0104*Math.sin(2*F)\n -0.0051*Math.sin(M+M1)\n -0.0074*Math.sin(M-M1)\n +0.0004*Math.sin(2*F+M)\n -0.0004*Math.sin(2*F-M)\n -0.0006*Math.sin(2*F+M1)\n +0.0010*Math.sin(2*F-M1)\n +0.0005*Math.sin(M+2*M1); \n}\n\nelse if (fase==0.25 || fase==0.75) {\n \n correzione1= (0.1721-0.0004*T)*Math.sin(M)\n +0.0021*Math.sin(2*M)\n -0.6280*Math.sin(M1)\n +0.0089*Math.sin(2*M1)\n -0.0004*Math.sin(3*M1)\n +0.0079*Math.sin(2*F)\n -0.0119*Math.sin(M+M1)\n -0.0047*Math.sin(M-M1)\n +0.0003*Math.sin(2*F+M)\n -0.0004*Math.sin(2*F-M)\n -0.0006*Math.sin(2*F+M1)\n +0.0021*Math.sin(2*F-M1)\n +0.0003*Math.sin(M+2*M1)\n +0.0004*Math.sin(M-2*M1)\n -0.0003*Math.sin(2*M+M1); \n}\n\nelse {alert(\"Valore fase \"+fase+\" non valido!\");}\n\nvar njd_fase=njd_fase+correzione1; // per la luna nuova.\n\n // njd_fase= numero dei giorni giuliani.\nreturn njd_fase;\n\n}", "function obliczPunkty(dane)\n{\n var ro = 1.21; // gęstośc czynnika\n var stosunek_et = [0.86, 0.98, 1, 0.966, 0.86]; // stosunek sprawności izentropowych\n\n var mi0 = (1 - (Math.sqrt(Math.sin(dane.beta2 * (Math.PI / 180))) / (Math.pow(dane.z, 0.7)))).toPrecision(3); // współczynnik zmniejszenia mocy wentylatora\n var u2 = ((dane.D2 * Math.PI * dane.n) / 60).toPrecision(3); // prędkość obwodowa wirnika\n var c2u = ((dane.deltapzn * 1000) / (ro * u2 * dane.etazn)).toPrecision(3); // prędkość zależna od ułopatkowania wirnika\n var fi2r = ((c2u * Math.tan(dane.alfa2 * Math.PI / 180)) / u2).toPrecision(3); // wskaźnik prędkości koła wirnikowego\n var fi2r0 = ((mi0 * fi2r) / (mi0 - (c2u / u2))).toPrecision(3); // wartośc wskaznika prędkości koła wirnikowego dla wartości zerowej charakterystyki koła wirnikowego\n var Qmax = (dane.Qzn * (fi2r0 / fi2r)).toPrecision(3); // przepływ maksymalny\n\n var krok = 0.6;\n\n var daneDoWykresu = {};\n daneDoWykresu.deltap = []; // tablica wartości sprężu (deltap)\n daneDoWykresu.Q = []; // tablica wartości wydajności\n daneDoWykresu.Q = []; // tablica wartości wydajności\n daneDoWykresu.eta = []; // etazn * stosunek_et\n\tdaneDoWykresu.wspQ = []; //współczynnik Q: 1-Q/Qmax\n\tdaneDoWykresu.mp = [] ; // tablica wartości mocy pobieranej\n\t\n /* obliczanie punktów charakterystyk */\n\t\n for (var i = 0; i < 5; i++)\n\t{\n daneDoWykresu.Q[i] = krok * dane.Qzn;\n daneDoWykresu.wspQ[i] = 1 - (daneDoWykresu.Q[i] / Qmax);\n daneDoWykresu.eta[i] = dane.etazn * stosunek_et[i];\n\t\tdaneDoWykresu.deltap[i] =((293/(273+dane.tc))*((ro * (Math.pow(u2, 2)) * mi0 * daneDoWykresu.wspQ[i] * daneDoWykresu.eta[i])) / 1000); // kPa\n\t\tdaneDoWykresu.mp[i] = ((daneDoWykresu.Q[i]*daneDoWykresu.deltap[i])/(daneDoWykresu.eta[i]*dane.etas))/100; // kW/100\n krok += 0.2;\n }\n return daneDoWykresu;\n}", "function hitungLuasLingkaran(jariJari){\n return 3.14 * jariJari ^ 2 \n}", "function IndicadorRangoEdad () {}", "function afase_luna(njd){\n\n // calcola l'angolo di fase della luna per la data (njd)\n // gennaio 2012\n\n var dati_luna=pos_luna(njd); // recupero fase/elongazione (1)\n var dati_sole=pos_sole(njd);\n\n var elongazione1=dati_luna[4]; // elongazione in gradi sessadecimali.\n var dist_luna=dati_luna[7]/149597870; \n var dist_sole=dati_sole[4]; // distanza del sole in UA.\n\n elongazione=Math.abs(elongazione1)*1;\n\n var dist_sl=dist_luna*dist_luna+dist_sole*dist_sole-2*dist_luna*dist_sole*Math.cos(Rad(elongazione)); // distanza sole-luna\n dist_sl=Math.sqrt(dist_sl);\n\n // calcolo dell'angolo di fase in gradi . \n\n var Dpt= dist_luna; // distanza pianeta-terra.\n var Dts= dist_sole; // distanza terra-sole.\n var Dps= dist_sl; // distanza pianeta-sole.\n\n // teorema del coseno\n\n var delta_fase=(Dts*Dts+Dps*Dps-Dpt*Dpt)/(2*Dps*Dts);\n delta_fase=Math.acos(delta_fase); \n delta_fase=Rda(delta_fase);\n\n var angolo_fase=180-elongazione-delta_fase; // angolo di fase in gradi.\n\n if(elongazione1<0) {angolo_fase=-angolo_fase; }\n\n return angolo_fase;\n\n}", "function Angkot(sopir, trayek, kas, penumpang){\n this.sopir = sopir;\n this.trayek = trayek;\n this.kas = kas;\n this.penumpang = penumpang;\n\n //method penumpang naik\n this.penumpangNaik = function(namaPenumpang){\n this.penumpang.push(namaPenumpang);\n return this.penumpang;\n }\n\n // method penumpang turun\n this.penumpangTurun = function(namaPenumpang, bayar){\n if(this.penumpang.length === 0){\n console.log('angkot masih kosong');\n return false;\n }\n\n for(var i = 0; i< this.penumpang.length; i++){\n if(this.penumpang[i] == namaPenumpang){\n this.penumpang[i] = undefined;\n this.kas += bayar;\n return this.penumpang;\n }\n }\n }\n}", "function hitungVolumedanLuasPermukaanBalok(panjang, lebar, tinggi) {\n luasPermukaanBalok = 2 * ( (panjang * lebar) + (panjang * tinggi) + (lebar * tinggi) );\n volumeBalok = panjang * lebar * tinggi;\n document.write(\"Panjang : \" + panjang + \"<br/>\");\n document.write(\"Lebar : \" + lebar + \"<br/>\");\n document.write(\"Tinggi : \" + tinggi + \"<br/>\" + \"<br/>\");\n document.write(\"Volume Balok : \" + volumeBalok + \"<br/>\");\n document.write(\"Luas Permukaan Balok : \" + luasPermukaanBalok + \"<br/>\");\n}", "function tampilkan() {\n console.log(\"halo!\");\n}", "function Guarda_Clics_AFN_Menos()\r\n{\r\n\tGuarda_Clics(4,0);\r\n}", "saludar(fn){\n console.log(`Hola me llamo ${this.nombre} ${this.apellido}`)\n if(fn){\n fn(this.nombre,this.apellido, false)\n }\n }", "function miFuncion(){\n\n}", "function tampilkanAngkaA(angka = 1) {\n return angka;\n}", "saludar(fn){\n console.log(`Hola me llamo ${this.nombre} ${this.apellido} y soy programador`)\n if(fn){\n fn(this.nombre,this.apellido, true)\n }\n }", "function Ha(){}", "function letra(tecla) {\n //alert(tecla);\n var ltPCode;\n var acertouAq; // pesquisar se true letras que acertou\n var errouAq; // pesquisar letras que errou\n\n key = tecla;\n lt = String.fromCharCode(key).toLowerCase();\n ltPCode = lt.charCodeAt(0);\n\n acertouAq = acertou.indexOf(lt);\n errouAq = errou.indexOf(lt);\n\n if(key == 186){\n alert('Clique C ou outra consoante!');\n }else if(ltPCode == 97 || ltPCode == 98 || ltPCode == 99 || ltPCode == 100 || ltPCode == 101 || ltPCode == 102 || ltPCode == 103 || ltPCode == 104 || ltPCode == 105 ||\n ltPCode == 106 || ltPCode == 107 || ltPCode == 108 || ltPCode == 109 || ltPCode == 110 || ltPCode == 111 || ltPCode == 112 || ltPCode == 113 || ltPCode == 114 ||\n ltPCode == 115 || ltPCode == 116 || ltPCode == 117 || ltPCode == 118 || ltPCode == 119 || ltPCode == 120 || ltPCode == 121 || ltPCode == 122){\n\n if(acertou.length >= obj.length || imgAtual >= 6){\n\n }else if(perdeu == true) {\n\n }else if(acertouAq >= 0 || errouAq >= 0){\n alert('Você já tinha digitado a tecla \\\"'+lt+'\\\"');\n }else{\n ltPre = limpaLetra(lt);\n verLetra(ltPre);\n }\n\n }\n}", "function KenalanV3 (nama, hobi) {\n console.log(`Hello, Nama Saya ${nama}`)\n console.log(`Saya Suka ${hobi}`)\n console.log(`Sekian`)\n}", "function fl_outToOznei_aman ()\n\t\t{if(freez==\"false\"){\n\t\t\tconsole.log(\"hit\")\n\t\t\tthis.rimon.alpha=1\n\t\t\tthis.sufgania.alpha=1\n\t\t\tthis.selek.alpha=1\n\t\t\tthis.tamar.alpha=1\n\t\t\tthis.karpas.alpha=1\n\t\t\tthis.levivot.alpha=1\n\t\t\tthis.haroset.alpha=1\n\t\t\tthis.maza.alpha=1\n\t\t\tthis.hasa.alpha=1\n\t\t\tthis.beiza.alpha=1\n\t\t\tthis.hazeret.alpha=1\n\t\t\tthis.mamtak.alpha=1\n\t\t\tthis.gvina.alpha=1\n\t\t\tthis.dvash.alpha=1\n\t\t\tthis.dag.alpha=1\n\t\t\tthis.sumsum.alpha=1\n\t\t\tthis.perot.alpha=1\n\t\t\tthis.mishloah.alpha=1\n\t\t\tthis.of.alpha=1\n\t\t this.chanuka_btn.alpha=1\n\t\t this.tu_btn.alpha=1\n\t\t this.pesach_btn.alpha=1\n\t\t this.shavuot_btn.alpha=1\n\t\t this.rosh_ha_shana_btn.alpha=1\n\t\t this.bible_btn.alpha=1\n\t\t\t\t\t this.arrow_btn.alpha=0\n\t\tthis.arrowAside_mc.alpha=0\n\t\tthis.gvina_explain.alpha=0\n\t\tthis.mishloah_explain.alpha=0\n\t\tthis.sufgania_explain.alpha=0\n\t\tthis.perot_explain.alpha=0\n\t\tthis.tapuah_explain.alpha=0\n\t\tthis.maza_explain.alpha=0\n\t\t\n\t\t}}", "function PenjumlahanDuabujurSangkar(a,b){\n return a * a+ b * b;\n}", "function comportement (){\n\t }", "saludar(fn){//recepcion de funcion\n var {nombre, apellido}=this //desgrloce de variables\n console.log(`Hola me llamo ${nombre} ${apellido}`)\n if(fn){\n fn(nombre, apellido, true)\n }\n }", "function fl_outToSufgania ()\n\t\t{if(freez==\"false\"){\n\t\t\tconsole.log(\"hit\")\n\t\t\tthis.rimon.alpha=1\n\t\t\tthis.selek.alpha=1\n\t\t\tthis.tamar.alpha=1\n\t\t\tthis.karpas.alpha=1\n\t\t\tthis.levivot.alpha=1\n\t\t\tthis.haroset.alpha=1\n\t\t\tthis.maza.alpha=1\n\t\t\tthis.hasa.alpha=1\n\t\t\tthis.beiza.alpha=1\n\t\t\tthis.hazeret.alpha=1\n\t\t\tthis.mamtak.alpha=1\n\t\t\tthis.gvina.alpha=1\n\t\t\tthis.oznei_aman.alpha=1\n\t\t\tthis.dvash.alpha=1\n\t\t\tthis.dag.alpha=1\n\t\t\tthis.sumsum.alpha=1\n\t\t\tthis.perot.alpha=1\n\t\t\tthis.mishloah.alpha=1\n\t\t\tthis.of.alpha=1\n\t\t this.tu_btn.alpha=1\n\t\t this.purim_btn.alpha=1\n\t\t this.pesach_btn.alpha=1\n\t\t this.shavuot_btn.alpha=1\n\t\t this.rosh_ha_shana_btn.alpha=1\n\t\t this.bible_btn.alpha=1\n\t\t\t\t\t this.arrow_btn.alpha=0\n\t\tthis.arrowAside_mc.alpha=0\n\t\tthis.gvina_explain.alpha=0\n\t\tthis.mishloah_explain.alpha=0\n\t\tthis.sufgania_explain.alpha=0\n\t\tthis.perot_explain.alpha=0\n\t\tthis.tapuah_explain.alpha=0\n\t\tthis.maza_explain.alpha=0\n\t\t\n\t\t}}", "falar2(){\n console.log('Olá2') \n }", "function Pe(){}", "function hitungLuasSegiTiga(alas,tinggi){\n var luas = 0.5 * alas * tinggi\n return luas\n}", "function Puissance4(lig,col,l,c){\r\n //commencement de l'analyse\r\n console.log(\"Valeurs: \"+lig+\" \"+col+\" / Incrément \"+i+ \" \"+c);\r\n if(c == 0 && l == 0){\r\n //pour moi c'est inversé a verticale, b horizontal, c diag gauche et d diag droit\r\n // horizontalité\r\n var va = 1 +Puissance4(lig +1,col,1,0) + Puissance4(lig-1,col,-1,0);\r\n // verticalité\r\n var vb = 1 +Puissance4(lig,col+1,0,1) + Puissance4(lig,col-1,0,-1);\r\n // diagonale de droite\r\n var vc = 1 +Puissance4(lig+1,col+1,1,1) + Puissance4(lig-1,col-1,-1,-1); \r\n // diagonale de gauche\r\n var vd = 1 +Puissance4(lig-1,col+1,-1,1) + Puissance4(lig+1,col-1,1,-1);\r\n console.log(va,vb,vc,vd);\r\n if(va == 4 || vb == 4 || vc == 4 || vd == 4)return true;\r\n else return false; \r\n }\r\n //On vérifie que \"lig\" et \"col\" ne sortent pas du tableau \r\n if (lig<this.ligne && lig>=0 && col<this.colonne && col>=0){\r\n if(this.plateau[lig][col]==joueur){\r\n return 1+ Puissance4(lig + l, col + c, l, c);}\r\n else {return 0;}\r\n }\r\n else return 0;\r\n }", "function buatKalimat(nama, umur, alamat, hobi) {\n // Code kamu mulai dari sini\n var kalimat = \"Nama saya \" + nama + \", Umur \" + umur + \" Bertempat tinggal di \" + alamat + \", hobi saya \" + hobi;\n // Tampilkan dengan cara document.getElementById(\"jawaban3\").innerHTML seperti di CONTOH.\n document.getElementById(\"jawaban3\").innerHTML = kalimat;\n }", "function Mahasiswa(nama, energi){\n this.nama = nama;\n this.energi = energi;\n\n this.makan = function(porsi){\n this.energi += porsi;\n console.log(`Hello ${this.nama}, selamat makan`);\n }\n\n this.main = function(jam){\n this.energi -= jam;\n console.log(`Hello ${this.nama}, selamat main`);\n }\n}", "getPersonasPorSala(sala) {\n\n }", "function Pythia() {}", "function angkot (supir, penumpang){\n this.supir = supir;\n this.penumpang = penumpang;\n\n this.naik = function(nama_penumpang){\n this.penumpang.push(nama_penumpang);\n return this.penumpang;\n }\n \n}", "function Go_Funciones()\n {\n if( g_listar == 1 )\n {\n Get_Marca_Producto();\n }\n \n }", "function upisNajaFunc()\n{\n\t/* ako je br bacanja veci od 1, nije najavljeno nedozvoljen upis */\n\tif (brojBacanja > 1 && indNajave < 1)\n\t{\n\t\talert(\"Niste najavili!\");\n\t\treturn;\n\t}\n\t/* u suprotnom u prvom smo bacanju i zelimo da najavimo */\n\telse if (brojBacanja == 1 && indNajave < 1)\n\t{\n\t\tindNajave = Number(this.id.slice(1, ));\n\n\t\t/* manipulate css for different background color */\n\t\tvar elm = document.getElementById(this.id);\n\t\telm.className = (elm.className == \"najaKlik\") ? \"polje naja\" : \"najaKlik\";\n\t\treturn;\n\t}\n\telse if (brojBacanja === 0)\n\t\treturn;\n\n\t/* get the value of the field clicked */\n\tvar vred = Number(this.id.slice(1, ));\n\n\t/* if not equal, user did not announce that field */\n\tif (vred != indNajave)\n\t{\n\t\talert(\"Niste TO najavili!\");\n\t\treturn; \n\t}\n\t\n\n\t///* see if the previous field is not -1 */\n\t///* else disable writting to preserve order */\n\t//if(vred < 12 && kNaja[vred] < 0)\n\t//{\n\t//\talert(\"Nedozvoljen upis!\");\n\t//\treturn;\n\t//}\n\t\n\t/* did we already write into this field */\n\tif(kNaja[vred-1] >= 0)\n\t{\n\t\talert(\"Vec ste upisali u ovo polje!\");\n\t\treturn;\n\t}\n\n\tvar tmp = 0;\n\tvar tmpNiz = [];\n\n\t/* splice izabraneKockice and baceneKockice */\n\tfor(var i=0; i<5; ++i)\n\t{\n\t\tif (Number(izabraneKockice[i].innerText))\n\t\t\ttmpNiz.push(Number(izabraneKockice[i].innerText));\n\t}\n\n\tfor(var i=0; i<5; ++i)\n\t{\n\t\tif (Number(baceneKockice[i].innerText))\n\t\t\ttmpNiz.push(Number(baceneKockice[i].innerText));\n\t}\n\n\tif(tmpNiz.length != 5)\n\t\talert(\"Niz nije 5! vec: \" + tmpNiz.length);\n\n\t/* decide which field was clicked: broj, maxmin ili igra */\n\tswitch(vred)\n\t{\n\t\tcase 1:\n\t\tcase 2:\n\t\tcase 3:\n\t\tcase 4:\n\t\tcase 5:\n\t\tcase 6:\n\t\t\tfor(var i=0; i<5; ++i)\n\t\t\t{\n\t\t\t\tif(tmpNiz[i] == vred)\n\t\t\t\t\ttmp += tmpNiz[i]\n\t\t\t}\n\t\t\tkNaja[vred-1] = tmp;\n\t\t\tsumaKolFunc(kNaja, \"suma4\");\n\t\t\tsumaRazFunc(kNaja, \"suma8\")\n\t\t\tbreak;\n\t\tcase 7:\n\t\tcase 8:\n\t\t\ttmp = zbir(tmpNiz);\n\t\t\tkNaja[vred-1] = tmp;\n\t\t\t/* suma8 */\n\t\t\tsumaRazFunc(kNaja, \"suma8\")\n\t\t\tbreak;\n\t\tcase 9:\n\t\t\ttmp = jelFul(tmpNiz);\n\t\t\tkNaja[vred-1] = tmp;\n\t\t\tsumaIgFunc(kNaja, \"suma12\");\n\t\t\tbreak;\n\t\tcase 10:\n\t\t\ttmp = jelPoker(tmpNiz);\n\t\t\tkNaja[vred-1] = tmp;\n\t\t\tsumaIgFunc(kNaja, \"suma12\");\n\t\t\tbreak;\n\t\tcase 11:\n\t\t\ttmp = jelKenta(tmpNiz);\n\t\t\tkNaja[vred-1] = tmp;\n\t\t\tsumaIgFunc(kNaja, \"suma12\");\n\t\t\tbreak;\n\t\tcase 12:\n\t\t\ttmp = jelYamb(tmpNiz);\n\t\t\tkNaja[vred-1] = tmp;\n\t\t\tsumaIgFunc(kNaja, \"suma12\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\t/* write number of vred thrown */\n\tdocument.getElementById(this.id).innerText=Number(tmp);\n\n\t/* manipulate css for different background color */\n\tvar elm = document.getElementById(this.id);\n\telm.className = (elm.className == \"najaKlik\") ? \"polje naja\" : \"najaKlik\";\n\tindNajave = 0;\n\tresetuj(izabraneKockice, baceneKockice);\n\n}", "function sumaRazFunc(niz, ajdi)\n{\n\tvar tmp = 0;\n\n\tif (niz[0] >= 0 && niz[6] >=0 && niz[7] >=0)\n\t{\n\t\ttmp = (niz[6] - niz[7])*niz[0];\n\t\tdocument.getElementById(ajdi).innerText=tmp;\n\tvar i1 = Number(document.getElementById(\"suma5\").innerText);\n\tvar i2 = Number(document.getElementById(\"suma6\").innerText);\n\tvar i3 = Number(document.getElementById(\"suma7\").innerText);\n\tvar i4 = Number(document.getElementById(\"suma8\").innerText);\n\n\ti1 = i1 + i2 + i3 + i4;\n\tdocument.getElementById(\"suma14\").innerText=i1;\n\n\t\n\tvar i1 = Number(document.getElementById(\"suma13\").innerText);\n\tvar i2 = Number(document.getElementById(\"suma14\").innerText);\n\tvar i3 = Number(document.getElementById(\"suma15\").innerText);\n\t\n\ti1 = i1 + i2 + i3;\n\tdocument.getElementById(\"konrez\").innerText=i1;\n\t}\n}", "function ocen_statycznie()\n{\n return szachownica.ocena.material + (szachownica.ocena.faza_gry * szachownica.ocena.tablice + (70 - szachownica.ocena.faza_gry) * szachownica.ocena.tablice_koncowka) * 0.03;\n}", "function areacuadrado (lado){\n return lado * lado;\n}", "asetaKupla(nimi,kupla){\n for(var i = 0; i < this.hahmot.length; i++){\n var hahmo = this.hahmot[i];\n if (hahmo.nimi == nimi) hahmo.asetaKupla(kupla);\n }\n }", "function pengkodeanPopulasi(pos) {\n var urutan = new Array();\n //Pencocokan Posisi\n for (var i = 0; i < pos.length; i++) {\n urutan[i] = pengkodean1Partikel(pos[i]);\n }\n return urutan;\n}", "function ispisiKateogorijeProizvoda(kat, katProizvod, deoStrane){\n let html = \"\";\n\n kat.forEach(k => {\n let katPoId = katProizvod.filter(el => el.idKat == k.id);\n html += `<h5 class=\"text-center pt-2 pb-2\">${k.naziv}</h5>\n ${chbFilterKategorije(katPoId)} `; \n \n });\n html += chbFilterPaketAkcija();\n\n $(\"[name='paket']\").click(filtrirajPoPaketima);\n $(\"[name='popust']\").click(filtrirajPoPopustu);\n \n $(deoStrane).html(html);\n $(\"[name='kategorije']\").click(filterPoKategorijama);\n}", "function jelKenta(niz)\n{\n\t/* make a set from an array */\n\tvar skup = napraviSet(niz);\n\tvar tmpn = Array.from(skup);\n\ttmpn.sort();\n\n\tif(skup.size === 5)\n\t{\n\t\tconsole.log(tmpn[4]);\n\t\t/* kandidat za kentu */\n\t\tif((tmpn[4] - tmpn[0]) === 4)\n\t\t{\n\t\t\t/* velika ili mala kenta? */\n\t\t\tif(tmpn[0] === 1)\n\t\t\t\treturn 75;\n\t\t\telse\n\t\t\t\treturn 80;\n\t\t}\n\t\telse\n\t\t\treturn 0;\n\t}\n\telse\n\t\treturn 0;\n\n}", "function saludarFamilia(apellido){\n return function saludarMiembro(nombre){\n console.log(`hola ${nombre} ${apellido}`)\n }\n}", "function condiçaoVitoria(){}", "function hitungLuasPersegi(sisi) {\n var luas = sisi * sisi;\n return luas;\n}", "kartica1()\n {\n this.karticaForma=true;\n this.karticaRezultati=false;\n }", "function sumuoti(sk1 = 0,sk2 = 0) {\n let masyvas;\n masyvas = [sk1, sk2];\n let suma;\n\n //suma = masyvas[0] + masyvas[1];\n suma = sk1 + sk2;\n\n return suma ; //grazinti bet koki kintamojo tipa\n}", "function pozdravi(a){\n console.log(\"Dobrodosli \" + a);\n}" ]
[ "0.68615425", "0.6587972", "0.6524697", "0.6462105", "0.6457918", "0.6417833", "0.64163977", "0.6383044", "0.6322294", "0.63193476", "0.63102686", "0.63033897", "0.62999547", "0.62942857", "0.62810725", "0.62797815", "0.6272681", "0.6272681", "0.6272681", "0.6261768", "0.62533593", "0.6235732", "0.6215558", "0.6174803", "0.6157368", "0.61478305", "0.61225444", "0.61163116", "0.60913885", "0.6086379", "0.60694957", "0.6068959", "0.6061034", "0.60539395", "0.60482186", "0.60398513", "0.6033759", "0.60170555", "0.60062134", "0.6002494", "0.59832615", "0.5981112", "0.5972009", "0.59546673", "0.5949429", "0.5946002", "0.594388", "0.59427017", "0.59420043", "0.5923649", "0.59228283", "0.58980846", "0.58980316", "0.58914936", "0.58798856", "0.5875785", "0.58735263", "0.58702916", "0.5866154", "0.5850688", "0.58468455", "0.5845107", "0.5833363", "0.5827832", "0.5825885", "0.5825568", "0.58213276", "0.5815419", "0.5812712", "0.5810123", "0.580096", "0.57937276", "0.57933825", "0.5787093", "0.57867706", "0.5783589", "0.5778269", "0.5772439", "0.57568663", "0.5754917", "0.5736244", "0.57353425", "0.57301134", "0.57256716", "0.57196325", "0.5708982", "0.57088", "0.5708651", "0.5704893", "0.5704115", "0.57034004", "0.5701243", "0.56997573", "0.56988096", "0.5692675", "0.56905425", "0.56850845", "0.56832576", "0.5679829", "0.5671255", "0.5659563" ]
0.0
-1
The whole page has loaded, including all dependent resources such as stylesheets and images.
function _pageLoaded() { window.removeEventListener( 'load', _pageLoaded ); refresh(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function pageFullyLoaded () {}", "function pageReady() {\n svg4everybody();\n initScrollMonitor();\n initModals();\n }", "function pageReady() {\n legacySupport();\n initSliders();\n }", "function pageLoaded(){\t\n\tconsole.log(\"Page loaded.\");\n\tconsole.log(\"Loading jQuery...\");\t\n\tloadJQuery();\t\n}", "function pageLoaded() {\n\n\t\tvar elHeader = document.getElementsByTagName('header')[0];\n\n\t\telHeader.addEventListener(animationEvent, removeFOUT);\n\n\t\tfunction removeFOUT() {\n\n\t\t\tclassie.add(elHTML, 'ready');\n\t\t\telHeader.removeEventListener(animationEvent, removeFOUT);\n\n\t\t}\n\n\t}", "function allScriptsLoaded() {\n trace('allScriptsLoaded', TraceLevel.DEBUG);\n CWS.curState = WidgetState.INITIAL;\n CWS.flags.scriptsLoaded = true;\n if (CWS.flags.htmlLoaded) allWidgetStuffLoaded();\n }", "function pageLoaded() {\t\t\t\n\t\twriteToConsole(\"Page Loaded\");\n\t}", "pageReady() {}", "function pageReady() {\n legacySupport();\n\n updateHeaderActiveClass();\n initHeaderScroll();\n\n setLogDefaultState();\n setStepsClasses();\n _window.on('resize', debounce(setStepsClasses, 200))\n\n initMasks();\n initValidations();\n initSelectric();\n initDatepicker();\n\n _window.on('resize', debounce(setBreakpoint, 200))\n }", "function page_loaded() {\n post_load_setup();\n}", "function loaded() {\n\taddElements();\n\tosScroll();\n\t// initiate tabs\n\t$('#tabs').tab();\n\t// set event listeners\n\tsetOneTimeEventListeners();\n\t//updateChecked();\n}", "function load() {\n \n //writes all the html for the page\n htmlWriter();\n }", "function pageLoaded() {\n if (!isPageLoaded) {\n isPageLoaded = true;\n if (scrollIntervalId) {\n clearInterval(scrollIntervalId);\n }\n\n callReady();\n }\n }", "function pageLoaded() {\n if (!isPageLoaded) {\n isPageLoaded = true;\n if (scrollIntervalId) {\n clearInterval(scrollIntervalId);\n }\n\n callReady();\n }\n }", "function pageLoaded() {\n if (!isPageLoaded) {\n isPageLoaded = true;\n if (scrollIntervalId) {\n clearInterval(scrollIntervalId);\n }\n\n callReady();\n }\n }", "function pageLoaded() {\n if (!isPageLoaded) {\n isPageLoaded = true;\n if (scrollIntervalId) {\n clearInterval(scrollIntervalId);\n }\n\n callReady();\n }\n }", "function pageLoaded() {\n if (!isPageLoaded) {\n isPageLoaded = true;\n if (scrollIntervalId) {\n clearInterval(scrollIntervalId);\n }\n\n callReady();\n }\n }", "function documentReadyFunction() {\n onPageLoadOrResize();\n onPageLoad();\n }", "function finishedLoad() {\n console.log('finishedLoad()');\n if (externalIsLoaded()) {\n init();\n }\n }", "onPageReady () {}", "function onloadHandler(){\n console.info(\"Nick Cage is ready!\");\n // where the magic happens\n replaceAllElements();\n }", "onPageLoaded() {\n window.clearTimeout(this.animationTimeout_);\n window.clearTimeout(this.loadingTimeout_);\n this.setUIStep(AssistantLoadingUIState.LOADED);\n }", "function pageReady(){\n handleUTM();\n legacySupport();\n initModals();\n initScrollMonitor();\n initVideos();\n _window.on('resize', debounce(initVideos, 200))\n initSmartBanner();\n initTeleport();\n initMasks();\n }", "function init(){\n console.log(\"Page loaded and DOM is ready\");\n}", "function _load() {\r\n document.getElementById(\"loading-icon\").style.visibility = \"hidden\";\r\n document.getElementById(\"body\").style.visibility = \"visible\";\r\n }", "function pageLoad(){\n $jQ('body').zIndex(); // jQuery UI Check\n window.onbeforeunload=function(){return '';}; // Hack to prevent any page.reload\n startCSSInfo();\n hackUserAgent();\n hackRemoveAnimations();\n hackDisableSubmit();\n hackActions();\n setNumScripts();\n setTimeStatus();\n setSystemColors();\n setVisibility();\n setUserActions();\n setAllVisibleElementsInfo();\n hackFrameScroll();\n}", "function pageDocReady () {\n\n}", "function loadComplete() {\n\thasLoaded = true;\n}", "function initHypoPage() {\n // this starts the preloader queue loading\n // when complete the assetsLoadingComplete callback is triggered\n loadAssets();\n}", "function init() {\n loadTheme();\n loadBorderRadius();\n loadBookmarksBar();\n loadStartPage();\n loadHomePage();\n loadSearchEngine();\n loadCache();\n loadWelcome();\n}", "function loadHomePage(){\n\tloadNavbar();\n\tloadJumbotron();\n\tgenerateCarousels();\t\n}", "ready() {\n this.isReady = true;\n if (this.onLoad) {\n this.onLoad.call();\n }\n }", "function loadComplete() {\n if (++docsLoaded == 1) {\n setUpPageStatus = 'complete';\n }\n}", "function loadComplete() {\n if (++docsLoaded == 1) {\n setUpPageStatus = 'complete';\n }\n}", "function loadComplete() {\n if (++docsLoaded == 1) {\n setUpPageStatus = 'complete';\n }\n}", "function loadComplete() {\n if (++docsLoaded == 1) {\n setUpPageStatus = 'complete';\n }\n}", "function _onAllJsIncludesDone() {\n\t\tinitNavigationMode();\n//\t\tSitoolsDesk.loadPreferences(this);\n\n\t\tthis.fireEvent('modulesLoaded');\n\t}", "function handleBodyLoad() {\n document.body.classList.add('loaded');\n}", "function is_document_ready() {\n\n var visibleLoader = null;\n for (const loader of container.getElementsByClassName(\"loader\")) {\n if (loader.visible) {\n visibleLoader = loader;\n }\n }\n if (!visibleLoader) {\n get_all_prs();\n setInterval(get_all_prs, 30000);\n\n } else {\n console.log(\"Document not fully loaded. Waiting a bit more\");\n setTimeout(is_document_ready, 1000);\n }\n }", "function init() {\n documentReady(documentLoaded);\n}", "function init() {\n // THIS IS THE CODE THAT WILL BE EXECUTED ONCE THE WEBPAGE LOADS\n }", "function mainLoaded() {\n if (typeof(executeOnContentLoad) == \"function\") {\n if (contentLoadDestination && location.hash != contentLoadDestination) return;//wait til we are on the correct page\n var fn = executeOnContentLoad;\n executeOnContentLoad = null;\n contentLoadDestination = null;\n fn();\n }\n }", "function init()\n {\n $(document).on(\"loaded:everything\", runAll);\n }", "function ready() {\n if (!isReady) {\n triggerEvent(document, \"ready\");\n isReady = true;\n }\n }", "function pageLoaded() {\n \n\t\tvar cmd = sendToDebugService('GlobalPageLoaded', { });\n \t// before returning - process all pending queue messages \n \twhile ((msg = JsHybuggerNI.getQueuedMessage(false)) != null) {\n \t\tprocessCommand(parseSafe(msg),null);\n \t\t}\n }", "function onPageLoaded() {\n}", "function tabLoad() {\n // Tab load safety check\n if (tabHasLoaded) {\n return;\n }\n tabHasLoaded = true;\n\n setupPage();\n\n getAlerts();\n }", "function pageLoaded () {\n\n // Show the introduction modal\n UI.showIntro();\n\n // Show the overlay \n UI.displayOverlay(true);\n\n}", "function initPage() {\n $.get('/api/headlines?saved=true').done((data) => {\n articleContainer.empty();\n\n if (data && data.length > 0) {\n renderArticles(data);\n\n // Activate tooltips for the action buttons.\n $('[data-toggle=\"tooltip\"]').tooltip();\n } else {\n renderEmpty();\n }\n });\n }", "function loadCSS() {\n\n // CSS file not loaded yet? => load CSS file\n if ( !resource ) jQuery( 'head' ).append( '<link rel=\"stylesheet\" type=\"text/css\" href=\"' + url + '\">' );\n\n // immediate perform success callback\n success();\n\n }", "function dependencyLoaded() {\n dependenciesLoaded += 1;\n if (dependenciesLoaded >= dependencies) {\n odyssey.dispatchEvent(new Odyssey.Events.InitializedEvent());\n }\n }", "function onLoaded()\n\t{\n\t\twindow.initExhibitorsList();\n\t\twindow.initFloorPlans();\n\t\twindow.initConciege();\n\t\twindow.initAmenities();\n\t\twindow.initVisas();\n\t}", "async function initializePage() {\n loadProjectsContainer();\n loadCalisthenicsContainer();\n loadCommentsContainer();\n}", "function bgAnimationComplete() {\n preloadBg.hide();\n\n site = new Site();\n site.init();\n }", "function dom_loaded_handler() {\n // function flag since we only want to execute this once\n if (dom_loaded_handler.done) { return; }\n dom_loaded_handler.done = true;\n\n DOM_LOADED = true;\n ENQUEUE_REQUESTS = false;\n\n _.each(instances, function(inst) {\n inst._dom_loaded();\n });\n }", "function initPage() {\n $.get('/api/headlines?saved=false').done((data) => {\n articleContainer.empty();\n if (data && data.length > 0) {\n renderArticles(data);\n\n // Activate tooltips for the action buttons.\n $('[data-toggle=\"tooltip\"]').tooltip();\n } else {\n renderEmpty();\n }\n });\n }", "function mainComplete() {\n\t\tconsole.log('it is all loaded up');\n\t\t//Demo.main.initialize();\n\t}", "function pageLoad() {\n setControlValues();\n processHashInstruction();\n\n if (Common.isIE) Common.fixToMaxItemWidth('settings-header', 16, false);\n\n document.getElementById('theme').addEventListener('change', themeSelectChange);\n document.getElementById('defaults').addEventListener('click', defaultsClick);\n document.getElementById('save').addEventListener('click', saveClick);\n document.getElementById('cancel').addEventListener('click', cancelClick);\n\n document.getElementById('offline').style\n .display = (navigator.onLine ? 'none' : 'block');\n window.addEventListener('offline', appOffline);\n window.addEventListener('online', appOnline);\n}", "function onLoadComplete()\n {\n this.loaded = true;\n }", "function loaded() {\n ut.assert(true);\n ut.async(false);\n }", "function templateLoaded() {\n setUpStars();\n checkIfReserved();\n $('.breadcrumb-end').html($('.info h2').html());\n}", "function onLoad() { \n\n const pageStyle = getCombinedStyle(\".page\", {\n\t\tbackgroundColor: Color.create(\"#FFFFFF\"),\n\t\talignContent: FlexLayout.AlignContent.STRETCH,\n\t\talignItems: FlexLayout.AlignItems.STRETCH,\n\t\tdirection: FlexLayout.Direction.INHERIT,\n\t\tflexDirection: FlexLayout.FlexDirection.COLUMN,\n\t\tflexWrap: FlexLayout.FlexWrap.NOWRAP,\n\t\tjustifyContent: FlexLayout.JustifyContent.FLEX_START\n\t});\n\t\n\tObject.assign(this.layout, pageStyle);\n\t\n}", "function onLoadComplete () {\n // ready = true;\n}", "function resourceLoaded()\n{\n\tif(++curLoadResNum >= totalLoadResources){\n\t\tredraw();\n\t}\n}", "loadStylesAndResources() {\n if (stylesLoaded) return;\n stylesLoaded = true;\n \n let style = document.createElement('style');\n style.type = 'text/css';\n style.innerHTML = styles;\n document.body.appendChild(style);\n\n for (let url of [fontAwesome + '/css/all.css', heebo + '/css.css']) {\n let link = document.createElement('link');\n link.rel = 'stylesheet';\n link.type = 'text/css';\n link.href = url;\n document.head.appendChild(link);\n }\n }", "loaded() {}", "function isPageLoaded() {\n lp ++;\n\n /*if (typeof evt == 'object') {\n src = evt.target.src;\n var pl = src.lastIndexOf('/');\n src = src.substr(pl + 1);\n }else src = evt;\n\n get('say').innerHTML += src + ', ' + lp + '<br />';*/\n if (lp == np + nd) {\n\n removeElement('divLoading');\n removeElement('shadow');\n }\n }", "function pagePreload(){\n setWebcrawlerID();\n setChildsAndParents();\n startHTTPStatus();\n pageLoad();\n}", "function coreInitLoadPage() {\n if (typeof $(\"body\").attr(\"control\") !== \"undefined\")\n WEBUI.MAINPAGE = $(\"body\")[$(\"body\").attr(\"control\").split(\".\")[1]]();\n }", "function mPageLoaded(){\n\t\t\n\t\tconsole.log(\"got to page Loaded\");\n\t\t\n\t\t//load the google visualization library \n\t\t//added the callback - want the name of the callback function to be gLoaded\n\t\t\n\t\tgoogle.load(\"visualization\", \"1\", {packages:[\"corechart\"], callback: \"gLoaded\"});\n\n\t\t\n\t}", "function init () {\r\n\t\tconsole.log('all is loaded.');\r\n\t}", "function ready() {\n\n\tif(!Modernizr.csstransforms3d) $('body').prepend('<div class=\"alert\"><div class=\"box\"><h2>Fatti un regalo.</h2><p>Questo sito usa tecnologie moderne non compatibili con il tuo vecchissimo browser.</p><p>Fatti un regalo, impiega due minuti a installare gratuitamente un browser recente, tipo <a href=\"http://www.google.it/intl/it/chrome/browser/\">Google Chrome</a>. Scoprirai che il web è molto più bello!</p></div></div>');\n\tloader.init();\n\t$('nav').addClass('hidden');\n\t//particles.init();\n\twork.init();\n\tnewhash.change(true);\n\textra();\n\tskillMng.init();\n\tcomponentForm.init();\n\tresponsiveNav();\n\tmaterial_click();\n\tcuul.init();\n\tdisableHover();\n\tscroll_down.init();\n}", "function pageLoad(){\n\t\tconsole.log(\"init hello\");\n\t\tgetDates()\n\t}", "function pageLoaded() {\n\tgoogle.load(\"visualization\", \"1\", {\n\t\tpackages : [\"corechart\"],\n\t\tcallback : googleLoaded\n\t});\n}", "function pageLoaded() {\n\tgoogle.load(\"visualization\", \"1\", {\n\t\tpackages : [\"corechart\"],\n\t\tcallback : googleLoaded\n\t});\n}", "function initPage()\n\t{\n\t\tinitGlobalVars();\n\t\tinitDOM();\n\t\tinitEvents();\n\t}", "function afterLoading(){\n\t\t\tupdatePageInfo();\n\t\t}", "function preLoad() {\n // load something and continue on only when finished\n}", "function buildPage() {\n // Load Reusables\n $.get('includes/reusables.html', (reusables) => {\n $(\"br\").before(reusables);\n }).promise().done(() => {\n console.log(\"<Loader> Reusables loaded\");\n \n // Load Start Scene\n $.get('includes/start_scene.html', (start_scene) => {\n $(\"br\").before(start_scene);\n }).promise().done(() => {\n console.log(\"<Loader> Start scene loaded\");\n \n // Load Play Scene\n $.get('includes/play_scene.html', (play_scene) => {\n $(\"br\").before(play_scene);\n }).promise().done(() => {\n console.log(\"<Loader> Play scene loaded\");\n \n // Load Leaderboard Scene\n $.get('includes/leaderboard_scene.html', (leaderboard_scene) => {\n $(\"br\").before(leaderboard_scene);\n }).promise().done(() => {\n console.log(\"<Loader> Leaderboard scene loaded\");\n\n // Load End Scene\n $.get('includes/end_scene.html', (end_scene) => {\n $(\"br\").before(end_scene);\n }).promise().done(() => {\n console.log(\"<Loader> End scene loaded\");\n\n // Load Game Scripts\n $(\"#abofScripts\").html('<script src=\"scripts/engine.js\"></script>').promise().done(function() {\n $(\"#abofScripts script\").after('<script src=\"scripts/game.js\"></script>').promise().done(() => {\n $.when(\"#abofScripts\").done(() => {\n console.log(\"<Loader> Executing scripts...\");\n // Remove the <br> tag placeholder\n $(\"br\").remove();\n game.google.load();\n });\n });\n });\n });\n });\n });\n });\n });\n}", "function preLoad() {\n return;\n}", "function goReady(){ // wait for everything to load first\n\tif (domReady && svgReady!=null && loaded)\n\t\treadyStart(svgReady);\n}", "function homePageLoader() {\n\n pageCreator(\"home-page\");\n navBar(\"home-page\");\n restaurantLogo();\n bookTableBtn(\"home-page\");\n socialMedia();\n}", "loadResources() {\n lbs.loader.scripts = lbs.loader.scripts.filter(this.uniqueFilter)\n lbs.loader.styles = lbs.loader.styles.filter(this.uniqueFilter)\n lbs.loader.libs = lbs.loader.libs.filter(this.uniqueFilter)\n\n lbs.log.debug(`Scripts to load:${lbs.loader.scripts}`)\n lbs.log.debug(`Styles to load: ${lbs.loader.styles}`)\n lbs.log.debug(`Libs to load: ${lbs.loader.libs}`)\n\n $.each(lbs.loader.libs, (i) => {\n lbs.loader.loadScript(lbs.loader.libs[i])\n })\n\n $.each(lbs.loader.scripts, (i) => {\n lbs.loader.loadScript(lbs.loader.scripts[i])\n })\n\n $.each(lbs.loader.styles, (i) => {\n lbs.loader.loadStyle(lbs.loader.styles[i])\n })\n }", "function isLoaded() {\n\treturn LOADED;\n}", "function initLoad()\n{\n console.log('page load');\n myGame.buildBoard();\n myGame.nextMove();\n myGame.reset();\n}", "function pageLoad() {\n // console.log('pageLoad');\n\n const blank = window.location.hash.endsWith('-blank');\n if (!blank) {\n setupMenu();\n }\n\n setupImageControls();\n loadSavedDiagram();\n\n if (!blank) {\n updateMenu();\n setMenuPosition();\n setControlsPosition();\n\n document.getElementById('offline').style\n .display = (navigator.onLine ? 'none' : 'block');\n window.addEventListener('offline', appOffline);\n window.addEventListener('online', appOnline);\n }\n}", "function loadStart() {\n // Prepare the screen and load new content\n collapseHeader(false);\n wipeContents();\n loadHTML('#info-content', 'ajax/info.html');\n loadHTML('#upper-content', 'ajax/texts.html #welcome-text');\n loadHTML('#burger-container', 'ajax/burger-background.html #burger-flags', function() {\n loadScript(\"js/flag-events.js\");\n });\n}", "function __onLoad() {\n\tLOADED=true;\n}", "function onBodyLoad() {\n document.querySelector('.presentation').classList.add('visible')\n\n // Set up\n getSlideNumberFromUrlFragment()\n showSlide(true, true)\n onSlideEnter(slideEls[currentSlideNumber], true)\n\n // Slide manipulation\n hyphenateSlides()\n setUpBetterPunctuation()\n\n document.body.addEventListener('keydown', onKeyDown)\n document.body.focus()\n}", "function initialize() {\n $.get(\"views/AdminHomePage.html\")\n .done(setup)\n .fail(error);\n }", "_loadCurrentPage() {\n this._loadCardsForCurrentPage();\n this._renderCurrentPage();\n }", "function tabLoad() {\n // Tab load safety check\n if (tabHasLoaded) {\n return;\n }\n tabHasLoaded = true;\n\n setupPage();\n\n getTaskStatuses();\n getTasks();\n }", "function domReady() {\n // Make sure that the DOM is not already loaded\n if (!isReady) {\n // Remember that the DOM is ready\n isReady = true;\n\n if (readyList) {\n for (var fn = 0; fn < readyList.length; fn++) {\n readyList[fn].call(window, []);\n }\n\n readyList = [];\n }\n }\n }", "function domReady() {\n // Make sure that the DOM is not already loaded\n if (!isReady) {\n // Remember that the DOM is ready\n isReady = true;\n\n if (readyList) {\n for (var fn = 0; fn < readyList.length; fn++) {\n readyList[fn].call(window, []);\n }\n\n readyList = [];\n }\n }\n }", "_didLoad () {\n // Clear the height cache\n this._lastHeight = 0\n \n // Post-process content\n this._unescapeImageURLs()\n \n // Setup event listeners\n this._addHeightListener('details', 'toggle')\n this._addHeightListener('img, svg', 'load')\n }", "function initializePage() {\n handleGlobalEvent();\n handleSideBar();\n handleMessageBar();\n handleCollapsibleController();\n handleResetButton();\n handleDisabledSubmit();\n handleAjaxError();\n handleAjaxSetup();\n }", "function pageInitalize(){\n\n articleContainer.empty();//Empties article container.//\n $.get(\"/api/headlines?saved=false\").then(function(data){//Runs AJAX request for unsaved\n if (data && data.length) {//Renders found headlines to the page.//\n renderArticles(data);\n }else{\n renderEmpty();//Renders no articles message.//\n }\n });\n }", "function setReady() {\n debug.log( arguments.callee.name );\n // Hacky-hacky for Linkinus 2.2 / iOS.\n location.href = 'linkinus-style://styleDidFinishLoading';\n \n scroller.setReady();\n overlay.setReady();\n \n //spam(); // Uncomment for scroll debugging.\n}", "setPageLoading() {\n this.pageReady = false\n }", "onload() {}" ]
[ "0.73301554", "0.7009687", "0.68653196", "0.68193144", "0.6792291", "0.67457306", "0.67425376", "0.6723652", "0.668899", "0.66843516", "0.6672045", "0.66604257", "0.6651822", "0.6651822", "0.6651822", "0.6651822", "0.6621475", "0.660283", "0.6555931", "0.65452135", "0.65070075", "0.6485983", "0.6476214", "0.6440863", "0.6332474", "0.63214743", "0.63146037", "0.6312949", "0.63047934", "0.63016564", "0.6282005", "0.6265908", "0.62480927", "0.62480927", "0.62480927", "0.62480927", "0.62457335", "0.6225888", "0.6207186", "0.62051326", "0.619517", "0.61621386", "0.61608917", "0.61594534", "0.6157671", "0.61365694", "0.61314803", "0.6125916", "0.6108945", "0.61048084", "0.6100152", "0.609681", "0.6096127", "0.60896534", "0.60806835", "0.6067826", "0.6062931", "0.60610044", "0.6057974", "0.60552907", "0.6052216", "0.605179", "0.6045651", "0.6042708", "0.6033823", "0.60150725", "0.60133123", "0.6013135", "0.6011504", "0.6008965", "0.59972245", "0.59922934", "0.5968222", "0.5967253", "0.5967253", "0.59606063", "0.5957943", "0.5953623", "0.5948223", "0.5940074", "0.5938109", "0.59327227", "0.59298396", "0.59208655", "0.5914287", "0.59066963", "0.59002995", "0.58989924", "0.589564", "0.5893132", "0.58842635", "0.588001", "0.58745927", "0.58745927", "0.58744365", "0.58709574", "0.58639145", "0.5862958", "0.5853886", "0.5853727" ]
0.62963146
30
Handle the end of a transition.
function _transitionComplete() { this.dispatchEvent( BaseTransition.END_EVENT, { target: this } ); if ( element.scrollHeight > previousHeight ) { element.style.maxHeight = element.scrollHeight + 'px'; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "endTransitionHandler(e) {\n if (this.active === true) {\n this.changeToDeactive();\n } else if (this.active === false) {\n this.transitionEndListenerOff();\n }\n }", "transitionCompleted() {\n // implement if needed\n }", "function finished(ev) {\n if ( ev && ev.target !== element[0]) return;\n\n if ( ev ) $timeout.cancel(timer);\n element.off($mdConstant.CSS.TRANSITIONEND, finished);\n\n // Never reject since ngAnimate may cause timeouts due missed transitionEnd events\n resolve();\n\n }", "function completeOnTransitionEnd(ev) {\n if (ev.target !== this) return;\n transitionComplete();\n }", "function completeOnTransitionEnd(ev) {\n if (ev.target !== this) return;\n transitionComplete();\n }", "function finished(ev) {\n if ( ev && ev.target !== element[0]) return;\n\n if ( ev ) $timeout.cancel(timer);\n element.off($mdConstant.CSS.TRANSITIONEND, finished);\n\n // Never reject since ngAnimate may cause timeouts due missed transitionEnd events\n resolve();\n\n }", "function finished(ev) {\n if (ev && ev.target !== element[0]) return;\n\n if (ev) $timeout.cancel(timer);\n element.off($mdConstant.CSS.TRANSITIONEND, finished);\n\n // Never reject since ngAnimate may cause timeouts due missed transitionEnd events\n resolve();\n\n }", "function finished(ev) {\n if ( ev && ev.target !== element[0]) return;\n\n if ( ev ) $timeout.cancel(timer);\n element.off($mdConstant.CSS.TRANSITIONEND, finished);\n\n // Never reject since ngAnimate may cause timeouts due missed transitionEnd events\n resolve();\n\n }", "function finished(ev) {\n if ( ev && ev.target !== element[0]) return;\n\n if ( ev ) $timeout.cancel(timer);\n element.off($mdConstant.CSS.TRANSITIONEND, finished);\n\n // Never reject since ngAnimate may cause timeouts due missed transitionEnd events\n resolve();\n\n }", "function transitionEnd() {\n\t\t\t\t\tif (bouncing) {\n\t\t\t\t\t\tbouncing = false;\n\t\t\t\t\t\treboundScroll();\n\t\t\t\t\t}\n\n\t\t\t\t\tclearTimeout(timeoutID);\n\t\t\t\t}", "function onEnd() {\n wrapper.classed( 'no-transition', true );\n wrapperNode.removeEventListener( 'transitionend', onEnd );\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n 'WebkitTransition': 'webkitTransitionEnd',\n 'MozTransition': 'transitionend',\n 'OTransition': 'oTransitionEnd otransitionend',\n 'transition': 'transitionend'\n }\n\n for(var name in transEndEventNames) {\n if(el.style[name] !== undefined) {\n return {\n end: transEndEventNames[name]\n }\n }\n }\n }", "function finished(ev){if(ev&&ev.target!==element[0])return;if(ev)$timeout.cancel(timer);element.off($mdConstant.CSS.TRANSITIONEND,finished);// Never reject since ngAnimate may cause timeouts due missed transitionEnd events\n\tresolve();}", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n 'WebkitTransition': 'webkitTransitionEnd',\n 'MozTransition': 'transitionend',\n 'OTransition': 'oTransitionEnd otransitionend',\n 'transition': 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return {\n end: transEndEventNames[name]\n }\n }\n }\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n 'WebkitTransition': 'webkitTransitionEnd',\n 'MozTransition': 'transitionend',\n 'OTransition': 'oTransitionEnd otransitionend',\n 'transition': 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return {\n end: transEndEventNames[name]\n }\n }\n }\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n 'WebkitTransition' : 'webkitTransitionEnd'\n , 'MozTransition' : 'transitionend'\n , 'OTransition' : 'oTransitionEnd otransitionend'\n , 'transition' : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n 'WebkitTransition' : 'webkitTransitionEnd'\n , 'MozTransition' : 'transitionend'\n , 'OTransition' : 'oTransitionEnd otransitionend'\n , 'transition' : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n 'WebkitTransition' : 'webkitTransitionEnd'\n , 'MozTransition' : 'transitionend'\n , 'OTransition' : 'oTransitionEnd otransitionend'\n , 'transition' : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n 'WebkitTransition' : 'webkitTransitionEnd'\n , 'MozTransition' : 'transitionend'\n , 'OTransition' : 'oTransitionEnd otransitionend'\n , 'transition' : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n 'WebkitTransition' : 'webkitTransitionEnd'\n , 'MozTransition' : 'transitionend'\n , 'OTransition' : 'oTransitionEnd otransitionend'\n , 'transition' : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n 'WebkitTransition' : 'webkitTransitionEnd'\n , 'MozTransition' : 'transitionend'\n , 'OTransition' : 'oTransitionEnd otransitionend'\n , 'transition' : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n 'WebkitTransition' : 'webkitTransitionEnd'\n , 'MozTransition' : 'transitionend'\n , 'OTransition' : 'oTransitionEnd otransitionend'\n , 'transition' : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n 'WebkitTransition' : 'webkitTransitionEnd'\n , 'MozTransition' : 'transitionend'\n , 'OTransition' : 'oTransitionEnd otransitionend'\n , 'transition' : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n 'WebkitTransition' : 'webkitTransitionEnd'\n , 'MozTransition' : 'transitionend'\n , 'OTransition' : 'oTransitionEnd otransitionend'\n , 'transition' : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n 'WebkitTransition' : 'webkitTransitionEnd'\n , 'MozTransition' : 'transitionend'\n , 'OTransition' : 'oTransitionEnd otransitionend'\n , 'transition' : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n 'WebkitTransition' : 'webkitTransitionEnd'\n , 'MozTransition' : 'transitionend'\n , 'OTransition' : 'oTransitionEnd otransitionend'\n , 'transition' : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n 'WebkitTransition' : 'webkitTransitionEnd'\n , 'MozTransition' : 'transitionend'\n , 'OTransition' : 'oTransitionEnd otransitionend'\n , 'transition' : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n 'WebkitTransition' : 'webkitTransitionEnd'\n , 'MozTransition' : 'transitionend'\n , 'OTransition' : 'oTransitionEnd otransitionend'\n , 'transition' : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n 'WebkitTransition' : 'webkitTransitionEnd'\n , 'MozTransition' : 'transitionend'\n , 'OTransition' : 'oTransitionEnd otransitionend'\n , 'transition' : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n 'WebkitTransition' : 'webkitTransitionEnd'\n , 'MozTransition' : 'transitionend'\n , 'OTransition' : 'oTransitionEnd otransitionend'\n , 'transition' : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n 'WebkitTransition' : 'webkitTransitionEnd'\n , 'MozTransition' : 'transitionend'\n , 'OTransition' : 'oTransitionEnd otransitionend'\n , 'transition' : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n 'WebkitTransition' : 'webkitTransitionEnd'\n , 'MozTransition' : 'transitionend'\n , 'OTransition' : 'oTransitionEnd otransitionend'\n , 'transition' : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n }", "end(event) {\n\n }", "function transitionEnd() {\n var el = document.createElement( 'bootstrap' )\n var transEndEventNames = {\n WebkitTransition: 'webkitTransitionEnd',\n MozTransition: 'transitionend',\n OTransition: 'oTransitionEnd otransitionend',\n transition: 'transitionend'\n }\n for ( var name in transEndEventNames ) {\n if ( el.style[ name ] !== undefined ) {\n return {\n end: transEndEventNames[ name ]\n }\n }\n }\n return false // explicit for ie8 ( ._.)\n }", "function _onAnimationEnd () {\n clearTimeout(transitionEndTimeout);\n $target.off(events);\n animationEnded();\n deferred.resolve();\n }", "function transitionEnd() {\n var el = document.createElement('smartbanner')\n\n var transEndEventNames = {\n WebkitTransition: 'webkitTransitionEnd',\n MozTransition: 'transitionend',\n OTransition: 'oTransitionEnd otransitionend',\n transition: 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return {end: transEndEventNames[name]}\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition: 'webkitTransitionEnd',\n MozTransition: 'transitionend',\n OTransition: 'oTransitionEnd otransitionend',\n transition: 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return {end: transEndEventNames[name]}\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition: 'webkitTransitionEnd',\n MozTransition: 'transitionend',\n OTransition: 'oTransitionEnd otransitionend',\n transition: 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return {end: transEndEventNames[name]}\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition: 'webkitTransitionEnd',\n MozTransition: 'transitionend',\n OTransition: 'oTransitionEnd otransitionend',\n transition: 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return {end: transEndEventNames[name]}\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition: 'webkitTransitionEnd',\n MozTransition: 'transitionend',\n OTransition: 'oTransitionEnd otransitionend',\n transition: 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition: 'webkitTransitionEnd',\n MozTransition: 'transitionend',\n OTransition: 'oTransitionEnd otransitionend',\n transition: 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return {\n end: transEndEventNames[name]\n }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }", "function transitionEnd() {\n var el = document.createElement('bootstrap')\n\n var transEndEventNames = {\n WebkitTransition : 'webkitTransitionEnd',\n MozTransition : 'transitionend',\n OTransition : 'oTransitionEnd otransitionend',\n transition : 'transitionend'\n }\n\n for (var name in transEndEventNames) {\n if (el.style[name] !== undefined) {\n return { end: transEndEventNames[name] }\n }\n }\n\n return false // explicit for ie8 ( ._.)\n }" ]
[ "0.76843834", "0.7508275", "0.74288833", "0.73918307", "0.73918307", "0.7374426", "0.7352981", "0.7350636", "0.7350636", "0.7218734", "0.7193805", "0.70266", "0.70214474", "0.69857705", "0.69857705", "0.696578", "0.696578", "0.696578", "0.696578", "0.696578", "0.696578", "0.696578", "0.696578", "0.696578", "0.696578", "0.696578", "0.696578", "0.696578", "0.696578", "0.696578", "0.696578", "0.696578", "0.6929649", "0.69188106", "0.6853627", "0.6837768", "0.6815405", "0.6815405", "0.6815405", "0.68112177", "0.6766342", "0.6709417", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047", "0.66884047" ]
0.7106824
11