Best JavaScript code snippet using testcafe
ember-core.js
Source:ember-core.js  
...26    it('should find Ember classes', function() {27      var viewClasses = ember.findEmberClass('View');28      assert(3 === viewClasses.length);29      // App.TeacherView30      assert(17 === viewClasses[0].getLoc().start.line);31      assert(24 === viewClasses[0].getLoc().start.column);32      assert(17 === viewClasses[0].getLoc().end.line);33      assert(28 === viewClasses[0].getLoc().end.column);34      // App.StudentView35      assert(21 === viewClasses[1].getLoc().start.line);36      assert(24 === viewClasses[1].getLoc().start.column);37      assert(21 === viewClasses[1].getLoc().end.line);38      assert(28 === viewClasses[1].getLoc().end.column);39      // App.StudentView.emptyView40      assert(23 === viewClasses[2].getLoc().start.line);41      assert(21 === viewClasses[2].getLoc().start.column);42      assert(23 === viewClasses[2].getLoc().end.line);43      assert(25 === viewClasses[2].getLoc().end.column);44    });45    it('should find Ember helper functions', function() {46      var keys = ember.findEmberFunction('keys', 0);47      assert(1 === keys.length);48    });49    it('should not find Ember helper functions if argument length not match', function() {50      var keys = ember.findEmberFunction('keys', 10);51      assert(0 === keys.length);52    });53    it('should find .extend() blocks', function() {54      assert(6 === ember.findExtendBlocks().length);55    });56    it('should find properties in .extend() blocks', function() {57      var properties = ember.findExtendBlocksProperties('students');58      assert(1 === properties.length);59      var property = properties[0];60      assert('ObjectProperty' === property.type);61      assert('students' === property.key.name);62      assert('Identifier' === property.key.type);63      assert('NullLiteral' === property.value.type);64    });65  });66  describe('basic ember application with no ES6 imports', function() {67    beforeEach(function() {68      var fixture = fixtureLoader.loadString(BASE_PATH, 'basic-no-import.fixture');69      var file = new JsFile({70        source: fixture,71        filename: 'basic-no-import.fixture'72      });73      ember = new EmberCore(file);74    });75    it('should find Ember classes', function() {76      var viewClasses = ember.findEmberClass('View');77      assert(3 === viewClasses.length);78      // App.TeacherView79      assert(15 === viewClasses[0].getLoc().start.line);80      assert(24 === viewClasses[0].getLoc().start.column);81      assert(15 === viewClasses[0].getLoc().end.line);82      assert(28 === viewClasses[0].getLoc().end.column);83      // App.StudentView84      assert(19 === viewClasses[1].getLoc().start.line);85      assert(24 === viewClasses[1].getLoc().start.column);86      assert(19 === viewClasses[1].getLoc().end.line);87      assert(28 === viewClasses[1].getLoc().end.column);88      // App.StudentView.emptyView89      assert(21 === viewClasses[2].getLoc().start.line);90      assert(21 === viewClasses[2].getLoc().start.column);91      assert(21 === viewClasses[2].getLoc().end.line);92      assert(25 === viewClasses[2].getLoc().end.column);93    });94    it('should find .extend() blocks', function() {95      assert(6 === ember.findExtendBlocks().length);96    });97    it('should find properties in .extend() blocks', function() {98      var properties = ember.findExtendBlocksProperties('students');99      assert(1 === properties.length);100      var property = properties[0];101      assert('ObjectProperty' === property.type);102      assert('students' === property.key.name);103      assert('Identifier' === property.key.type);104      assert('NullLiteral' === property.value.type);105    });106  });...default.js
Source:default.js  
1// function javascript for call modal by Id2  function showModalInsertData(){3      var $modal = $('#ModalInsertData');4      $modal.modal("show");5  }67// function javascript for call modal by id8910// function javascript for call modal by Id11  var id_data;12  function showModalUpdateData(str){13      id_data = document.getElementById(str).id;14      var $modal = $('#ModalUpdateData');15      $modal.modal("show");16  }1718// function javascript for call modal by id1920//-=------------------------------------------2122// function for display  alert in modal23// id_message = id div24// message = message that wanna be show25// type = success, alert, warning , danger26function messageAlert(id_message,message,type){27    var psan  = '<div  class="alert alert-'+type+'" fade in"> '+message+' !</div>';28    var tmpil = psan.fontcolor("black");29    document.getElementById(id_message).innerHTML = tmpil ;30    return;31}3233// function for display  alert in modal34var protocol;35var host;36function getHost(){37   protocol = window.location.protocol+"//";38   host     = window.location.host +"/";39  40  return protocol+host+directory+"/";41}4243function getRequest(){44   return "page/";45}4647function changeLanguange(id){4849	var getID = id;50	51	if (window.XMLHttpRequest) {52		xmlhttp = new XMLHttpRequest();53	} else {54		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");55	}56	xmlhttp.onreadystatechange = function() {57	if (this.readyState == 4 && this.status == 200) {58		var respon=this.responseText;59			if (respon=="T") { loadHome();return ;}60			if (respon=="F") { alert("Failed change languange ! Something is wrong !"); return;}61			62		}63	};6465	xmlhttp.open("GET",getHost()+"process/change-languange.php?lang="+getID+"",true); 66	xmlhttp.send();67 686970}7172function deleteData(id){73  var getID = id;74 75  if (window.XMLHttpRequest) {76  77    xmlhttp = new XMLHttpRequest();78  } else {79  80    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");81  }82  xmlhttp.onreadystatechange = function() {83  if (this.readyState == 4 && this.status == 200) {84    var respon=this.responseText;85    if (respon=="T") { loadView();return ;}86      if (respon=="F") { alert("Failed while deleted Data ! Something is wrong !"); return;}87        88    }89  };9091xmlhttp.open("GET",getHost() +"process/delete-data.php?id="+getID+"",true);92xmlhttp.send();93}949596function refreshEx() {97  var getLoc = getHost() + getRequest()+ 'bootstrap';98  window.location.href = ""+getLoc+"";99  return;100}101102function refreshDownload() {103  var getLoc = getHost() + getRequest()+ 'download';104  window.location.href = ""+getLoc+"";105  return;106}107108109function loadHome() {110  var getLoc = getHost() + getRequest()+'home';111112  var xhttp = new XMLHttpRequest();113  xhttp.onreadystatechange = function() {114    if (this.readyState == 4 && this.status == 200) {115      document.getElementById("__BODY__").innerHTML =116      this.responseText;117    }118  };119  xhttp.open("GET", getLoc, true);120  xhttp.send();121}122123function loadFeature() {124  var getLoc = getHost() + getRequest()+'feature';125  var xhttp = new XMLHttpRequest();126  xhttp.onreadystatechange = function() {127    if (this.readyState == 4 && this.status == 200) {128      document.getElementById("__BODY__").innerHTML =129      this.responseText;130    }131  };132  xhttp.open("GET", getLoc, true);133  xhttp.send();134}135136function loadAbout() {137  var getLoc = getHost() + getRequest()+'about';138  var xhttp = new XMLHttpRequest();139  xhttp.onreadystatechange = function() {140    if (this.readyState == 4 && this.status == 200) {141      document.getElementById("__BODY__").innerHTML =142      this.responseText;143    }144  };145  xhttp.open("GET", getLoc, true);146  xhttp.send();147}148149function loadView() {150  var getLoc = getHost() + getRequest()+'view';151  var xhttp = new XMLHttpRequest();152  xhttp.onreadystatechange = function() {153    if (this.readyState == 4 && this.status == 200) {154      document.getElementById("__BODY__").innerHTML =155      this.responseText;156    }157  };158  xhttp.open("GET", getLoc, true);159  xhttp.send();160}161162function loadFunction() {163  var getLoc = getHost() + getRequest()+'function';164  var xhttp = new XMLHttpRequest();165  xhttp.onreadystatechange = function() {166    if (this.readyState == 4 && this.status == 200) {167      document.getElementById("__BODY__").innerHTML =168      this.responseText;169    }170  };171  xhttp.open("GET", getLoc, true);172  xhttp.send();173}174175function loadUpload() {176  var getLoc = getHost() + getRequest()+'upload';177  var xhttp = new XMLHttpRequest();178  xhttp.onreadystatechange = function() {179    if (this.readyState == 4 && this.status == 200) {180      document.getElementById("__BODY__").innerHTML =181      this.responseText;182    }183  };184  xhttp.open("GET", getLoc, true);185  xhttp.send();186}187188189function deleteFile(str){190   id_file = document.getElementById(str).id.trim();191192193   if (id_file==='')194   {195    return;196   }197 198 199  if (window.XMLHttpRequest) {200201    xmlhttp = new XMLHttpRequest();202  } 203  else {204205    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");206  }207  xmlhttp.onreadystatechange = function() {208  if (this.readyState == 4 && this.status == 200) {209        var respon=this.responseText;210        if (respon=="T") { 211          loadUpload();212         213        }214         215            216      }217       218  };219220  xmlhttp.open("GET",getHost() +"process/delete-file.php?id="+id_file+"",true);221  xmlhttp.send();222}223224 function downloadFile(str)225{  226      id_file = document.getElementById(str).id.trim();227228      if (id_file==='')229      {230          return;231      }232233      window.location.href = getHost()+"download.php?id="+id_file;234}
...App.js
Source:App.js  
1import React, { useState, useEffect } from "react";2import * as Data from "./crimeData";3import axios from "axios";4import Police from "./Police";5import ReactMapGL,{Marker} from 'react-map-gl'6import RoomIcon from '@material-ui/icons/Room';7import PersonPinIcon from '@material-ui/icons/PersonPin';8function App(props) {9  console.log(props)10  const [getCrimeData,setCrimeData]=useState([])11  const data=[]12  const finalData=[]13  const foundLocs=[]14  const [getLoc,setLoc]= useState({long:28,lat:77});15  16  const getValue=(e)=>{17      const {name,value}=e.target18      setLoc(data=>({19          ...data,[name]:value20      }))21      console.log(getLoc)22  }23  const [viewport, setViewport] = useState({24      width: '100vw',25      height: '70vh',26      latitude: 28.7041,27      longitude: 77.1025,28      zoom: 829    });30    31    32   useEffect( async () => {33    await axios.get("http://localhost:8000/getCrimeData")34    .then((res)=>{35     36      res.data.map((obj,ind)=>{37        data.push(obj)38        39      })40   })41    Data.crimeData.map((obj, ind) => {42      // console.log(obj)43      if (44        getDistanceFromLatLonInKm(getLoc.lat, getLoc.long, obj.lat, obj.long) <=45        1046      ) {47        foundLocs.push({lat:obj.lat,long:obj.long})48        console.log("found");49      }50      console.log(data)51      foundLocs.map((obj,ind)=>{52        data.map((obj2,ind2)=>{53          54              if(obj2.lat===obj.lat ){55                finalData.push(obj2)56              }57        })58      })59      console.log(finalData)60      if(foundLocs.length!=0)61      {62        axios.post("http://localhost:8000/",{email:props.email,data:{finalData}})63        .then((res)=>{64          console.log(res)65        })66      }67    });68     69    70   }, [getLoc])71   console.log(data)72   console.log(foundLocs)73  const track=()=>{74      const showLoc=(data)=>{75          //console.log(data.coords.latitude);76          let lat=data.coords.latitude77          let long=data.coords.longitude78          setLoc({lat:lat,long:long})79          }80          navigator.geolocation.watchPosition(81              showLoc,error=>console.log(error),82              {83                  enableHighAccuracy:true,84                  timeout:100085              }86              87          )88  }89  90  function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {91          var R = 6371; // Radius of the earth in km92          var dLat = deg2rad(lat2-lat1);  // deg2rad below93          var dLon = deg2rad(lon2-lon1); 94          var a = 95            Math.sin(dLat/2) * Math.sin(dLat/2) +96            Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 97            Math.sin(dLon/2) * Math.sin(dLon/2)98            ; 99          var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 100          var d = R * c; // Distance in km101          console.log(d)102          return d;103        }104   function deg2rad(deg) {105          return deg * (Math.PI/180)106        }107  108    return (109      <>110      <div>hello {props.email}</div>     111        <div>112           113            114            <input name='long' value={getLoc.long} onChange={getValue}></input>115            <input name='lat' value={getLoc.lat} onChange={getValue}></input>116           117            <button onClick={track}>track</button>118            <ReactMapGL119      {...viewport}120      mapboxApiAccessToken='pk.eyJ1IjoibXJpZHVsc3RhciIsImEiOiJja3JudnBubXc0bDlyMnpwOHNrOXVzNXYwIn0.ryB1v11gBLBBtUTXOnaNmA'121      mapStyle="mapbox://styles/mapbox/satellite-v8"122      onViewportChange={nextViewport => setViewport(nextViewport)}123    >124      <Marker latitude={getLoc.lat} longitude={getLoc.long}>125        <div><PersonPinIcon style={{color:"blue",fontSize:40}}/></div>126      </Marker>127      {128          Data.crimeData.map((obj,ind)=>{129            // console.log(obj.lat)130             return(131                <Marker latitude={obj.lat} longitude={obj.long}>132               <div><RoomIcon style={{color:"red",fontSize:40}}/></div>133              </Marker>134             )135         })136      }137        </ReactMapGL>138      <Police/>139      <div>140        {foundLocs.map((obj,i)=>{141          return(142            <div>143              <p>144                {obj.lat}145              </p>146            </div>147          )148        })}149      </div>150        </div>151        </>152    )153}154export default App155/*156const MyMapComponent = withScriptjs(withGoogleMap((props) =>157  <GoogleMap158    defaultZoom={12}159    defaultCenter={{ lat: getLoc.lat, lng: getLoc.long }}160     161  > 162ll163  164  {props.isMarkerShown && <Marker title='loc' label='Current Position' icon={iconImage} position={{ lat: getLoc.lat, lng: getLoc.long }} />} 165      166    {167       Data.crimeData.map((obj,ind)=>{168          // console.log(obj.lat)169           return(props.isMarkerShown && <Marker  position={{ lat: obj.lat, lng: obj.long }} />)170  171       })172    }173    </GoogleMap>174))175/////////////////////////////////////////////////////////////////////////////////////////////////////176<MyMapComponent177                isMarkerShown178                positions={getLoc}179                googleMapURL="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places"180                loadingElement={<div style={{ height: `100%` }} />}181                containerElement={<div style={{ height: `400px` }} />}182                mapElement={<div style={{ height: `100%` }} />}183/>...Monster.js
Source:Monster.js  
...27		},28		update: function(dt, ctx) {29			this.animation.update(dt);30			// Play eating sound31			var moveVector = this.game.player.loc.subtract(this.getLoc());32			if (moveVector.length() < this.activeRange && this.eating && !this.death) {33				this.game.audio.Monstereating.play();34			}35			// Ignore if death36			if (this.death || this.eating) {37				return;38			}39			// Check if monster is in active range40			var moveVector = this.game.player.loc.subtract(this.getLoc());41			if (moveVector.length() > this.activeRange) {42				this.animation.setAnimation("idle");43				this.animation.setFlip(true);44				return;45			}46			// Monster is chasing player, play growling sound47			this.game.audio.Monstergrowl.play();48			// Check whether monster is on the player49			if ((Math.abs(moveVector.x) < 110) && (Math.abs(moveVector.y) < 15)) {50				this.game.player.die();51				this.eating = true;52				if (this.name == "Shadow") 	{53					this.eatingAnimation = new ContainedAnimation(this.game, this.game.json["MonsterEating2"], this.getLoc());54				} else {55					this.eatingAnimation = new ContainedAnimation(this.game, this.game.json["MonsterEating"], this.getLoc());		56				}57				this.eatingAnimation.animation.setAnimation("eating");58				this.eatingAnimation.animation.setFlip(true);59				this.eatingAnimation.init();60				return;61			}62			moveVector = moveVector.normalize();63			if (moveVector.x > 0) {64				this.animation.setAnimation("walk");65				this.animation.setFlip(false);66			} else {67				this.animation.setAnimation("walk");68				this.animation.setFlip(true);69			}70			// Scale monster speed71			moveVector = moveVector.multiply(this.speed);72			var roomPos = this.room.getLoc();73			var roomWidth = this.room.getWidth();74			if (this.moreFreedom == true) {75				roomWidth = roomWidth + 330; // Dirty hack for last room76			}77			var newLocation = this.getLoc().add(moveVector);78			if (this.game.isValidAndSafePosition(newLocation)) {79				if ((newLocation.x > (roomPos.x - roomWidth + 410)) && (newLocation.x < (roomPos.x - 50))) {		80					this.setLoc(newLocation);81				} else {82					this.animation.setAnimation("idle");83				}84				return;85			}86			newLocation = new Vector2(this.getLoc().x + (moveVector.x / Math.abs(moveVector.x)), this.getLoc().y);87			if (this.game.isValidAndSafePosition(newLocation)) {88				if ((newLocation.x > (roomPos.x - roomWidth + 410)) && (newLocation.x < (roomPos.x - 50))) {		89					this.setLoc(newLocation);90				} else {91					this.animation.setAnimation("idle");92				}93				return;94			}95			newLocation = new Vector2(this.getLoc().x, this.getLoc().y + (moveVector.y / Math.abs(moveVector.y)));96			//newLocation = newLocation.subtractMutable(this.getLoc()).rotateMutable(45).addMutable(this.getLoc());97			if (this.game.isValidAndSafePosition(newLocation)) {98				if ((newLocation.x > (roomPos.x - roomWidth + 410)) && (newLocation.x < (roomPos.x - 50))) {		99					this.setLoc(newLocation);100				} else {101					this.animation.setAnimation("idle");102				}103				return;104			}105			this.animation.setAnimation("idle");106		},107		init: function() {108		},109		die: function() {110			if (this.eatingAnimation instanceof Object) {111				this.eatingAnimation.die();112			}113			if (!this.death) {114				this.game.audio.Monstergrowl.play();115				this.death = true;116			}117		},118		draw: function(ctx) {119			// Ignore if death120			if (this.death || this.eating) {121				return;122			}123			ctx.save();124			//ctx.fillStyle = "#00FF00";125			ctx.translate(this.getLoc().x, this.getLoc().y);126			//ctx.fillRect(-2, -2, 4, 4);127			this.animation.draw(ctx, this.z);128			ctx.restore();129			/*ctx.beginPath();130			ctx.moveTo(this.getLoc().x,this.getLoc().y);131			ctx.lineTo(newLocation.x,newLocation.y);132			ctx.stroke();133			ctx.beginPath();134			ctx.moveTo(this.getLoc().x,this.getLoc().y);135			ctx.lineTo(newLocation.x,newLocation.y);136			ctx.stroke();*/137			//ctx.fillStyle = "#00FFF0";138			//ctx.fillRect(this.room.getLoc().x - 20, this.room.getLoc().y - 20, 40, 40);139		}140	});141	return Monster;...Civilian.js
Source:Civilian.js  
...19		},20		update: function() {21			if (!this.panic) this.x -= this.walkSpeed;22			// look for distance from dino23			if (Math.abs(this.x - this.game.dino.getLoc().x) < 300) this.panic = true;24			// PANIC MODE25			if (this.panic) {26				if (this.targetX == null) {27					this.targetX = Random.getInt(this.x - 150, this.x + 150);28				}29				this.direction = (this.targetX < this.x) ? 0 : 1;30				if (this.direction == 0) {31					this.x -= this.runSpeed;32					if (this.x < this.targetX) this.targetX = null;33				}34				else {35					this.x += this.runSpeed;36					if (this.x > this.targetX) this.targetX = null;37				}38			}39		},40		draw: function(ctx) {41			// walking42			var animationOffset = !this.panic ? this.height : this.height*2;43			var frameOffset = this.frame * this.width;44			//var frameOffset = 0;45			var loc = this.getLoc();46			// move to the right position47			ctx.save();48			ctx.translate(loc.x, loc.y);49			if (this.direction == 1) ctx.scale(-1, 1);50			ctx.translate(-this.width/2, -10);51			ctx.drawImage(this.img, frameOffset, animationOffset, this.width, this.height, 0, 0, this.width, this.height);52			ctx.restore();53			// next frame54			--this.frameCounter;55			if (this.frameCounter == 0) {56				this.frame = (this.frame + 1) % 5;57				this.frameCounter = 5;58			}59		},60		getCollisionShape: function() {61			return new Rectangle(new Vector2(this.getLoc().x, this.getLoc().y - 15), new Vector2(this.x + this.width/2, this.game.height - this.game.floorHeight));62		},63		getDamage: function() {64			return 1;65		},66		getLoc: function() {67			return new Vector2(this.x - this.width/2, this.game.height - (this.game.floorHeight + this.height));68		},69		handleDamage: function(damage) {70			//var animation = new Animation(this.game, "bloodSausageSS",  1.0, this.getLoc());71			//var animation = new Animation(this.game, "bloodSausageSS", 0.1, Random.getInt(0, 360), this.getLoc());72			var animation = new Animation(this.game, "debris/bloodSausage2SS", 1.0, Random.getInt(0, 360), this.getLoc().subtract(this.width/2, this.height/2));73			this.game.addAnimation(animation);74			var animation = new Animation(this.game, "debris/bloodSausage2SS", 1.0, Random.getInt(0, 360), this.getLoc());75			this.game.addAnimation(animation);76			var animation = new Animation(this.game, "debris/bloodSausage2SS", 1.0, Random.getInt(0, 360), this.getLoc());77			this.game.addAnimation(animation);78			var animation = new Animation(this.game, "debris/bloodSausage2SS", 1.0, Random.getInt(0, 360), this.getLoc());79			this.game.addAnimation(animation);80			var animation = new Animation(this.game, "debris/bloodSausage2SS", 1.0, Random.getInt(0, 360), this.getLoc());81			this.game.addAnimation(animation);82			var animation = new Animation(this.game, "debris/bloodSausage2SS", 1.0, Random.getInt(0, 360), this.getLoc());83			this.game.addAnimation(animation);84			this.game.civilians.splice(this.game.animations.indexOf(this), 1);85			//this.game.stopActor(this);86			87			for (var i = 0; i < 20; ++i) {88				this.generateParticle(this.getLoc().add(new Vector2(Random.getInt(-10, 10), Random.getInt(-10, 10))));89			}90		},91		generateParticle: function(point) {92			var particleVelocity = new Vector2(Random.getInt(1, 5) - 3.5, Random.getInt(1, 7) - 8);93			var particle = new Particle(this.game, "human/gore" + Random.getInt(1, 9), point, Random.getInt(0, 360), 0.50, particleVelocity, 0.025);94			this.game.addParticle(particle);95		}96	})97	return Civilian;...Trigger.js
Source:Trigger.js  
...26					this.keyProcessed = false;27					return;28				}29				// Check distance to trigger30				if ((((this.game.player.getLoc().x - this.getLoc().x) * (this.game.player.getLoc().x - this.getLoc().x))31						+ ((this.game.player.getLoc().y - this.getLoc().y) * (this.game.player.getLoc().y - this.getLoc().y))) > this.activateRange) {32					this.keyProcessed = false;33					return;34				}35				if (this.keyProcessed == false) {36					this.keyProcessed = true;37					this.active = !this.active;38					for (var i = 0; i < this.triggerables.length; ++i) {39						this.triggerables[i].activate(this.active);40					}41					if (this.active) {42						this.animation.setAnimation("on");43					} else {44						this.animation.setAnimation("off");45					}	46				}47			} else {48				// If trigger is activated manually, only activate if spacebar is pressed49				if (this.activated && !(this.game.isKeyDown(this.game.keyCodes.space) == true)) {50					if (this.active) {51						for (var i = 0; i < this.triggerables.length; ++i) {52							this.triggerables[i].activate(false);53						}54						this.animation.setAnimation("off");55						this.active = false;56					}57					return;58				}59				// Check distance to trigger60				if ((((this.game.player.getLoc().x - this.getLoc().x) * (this.game.player.getLoc().x - this.getLoc().x))61						+ ((this.game.player.getLoc().y - this.getLoc().y) * (this.game.player.getLoc().y - this.getLoc().y))) > this.activateRange) {62					if (this.active) {63						for (var i = 0; i < this.triggerables.length; ++i) {64							this.triggerables[i].activate(false);65						}66						this.animation.setAnimation("off");67						this.active = false;68					}69					return;70				}71				if (this.active == false) {72					this.active = true;73					for (var i = 0; i < this.triggerables.length; ++i) {74						this.triggerables[i].activate(true);75					}76					this.animation.setAnimation("on");77				}78			}79		},80		draw: function(ctx) {81			ctx.save();82			//ctx.fillStyle = "#00FFFF";83			ctx.translate(this.getLoc().x, this.getLoc().y);84			//ctx.fillRect(-2, -2, 4, 4);85			this.animation.draw(ctx);86			ctx.restore();87		}88	});89	return Trigger;...DailyPresenter.js
Source:DailyPresenter.js  
...19      Permissions.LOCATION20    );21    if (status === "granted") {22      setPs(true);23      getLoc();24    } else {25      setPs(false);26    }27  };28  const getPermStatus = async () => {29    const { status, expires, permissions } = await Permissions.getAsync(30      Permissions.LOCATION31    );32    console.log(status);33    console.log(ps);34    if (status === "granted") {35      setPs(true);36      getLoc();37    }38  };39  useEffect(() => {40    const unsubscribe = navigation41      .dangerouslyGetParent()42      .addListener("tabPress", (e) => {43        e.preventDefault();44        getPermStatus();45        navigation.navigate("Daily");46      });47    return unsubscribe;48  }, [navigation]);49  const getLoc = async () => {50    setisLoading(true);51    try {52      var loca = await Location.getCurrentPositionAsync({});53      setLocation(loca);54    } catch {55      setPs(false);56      Cities1 = [];57      console.log(Cities1);58      setisLoading(false);59      return;60    }61    try {62      await dispatch(63        dailyhourlyactions.getCityName(loca.coords.latitude, loca.coords.longitude)64      );65      await dispatch(66        dailyhourlyactions.selectDH(loca.coords.latitude, loca.coords.longitude)67      );68      setisLoading(false);69      return;70    } catch (error) {71      Alert.alert("Error1", "Something went wrong during network call", [72        { text: "Okay" },73      ]);74    } finally {75      setisLoading(false);76    }77  };78  const pTRHandler = async () => {79    getLoc();80  };81  useEffect(() => {82    let f = async () => {83      await getPermStatus();84      getLoc();85    };86    f();87  }, []);88  return (89    <DailyView 90        location={location}91        ps={ps}92        isLoading={isLoading}93        pTRHandler={pTRHandler}94        getLoc={getLoc}95        Cities={Cities}96        Cities1={Cities1}97        getPerm={getPerm}98        />...catalog_set_default_values_based_on_selection.js
Source:catalog_set_default_values_based_on_selection.js  
...7*/8// SET DEFAULT NAME BASED ON CURRENT USER9javascript: gs.getUserID()10// SET DEFAULT EMAIL VALUE BASED ON USER11javascript: getLoc();12function getLoc() {13    var u = new GlideRecord('sys_user');14    if (u.get(gs.getUserID())) {15        return u.getValue('email');16    } else {17        return '';18    }19}20// SET DEFAULT CONTACT NUMBER VALUE BASED ON USER21javascript: getLoc();22function getLoc() {23    var u = new GlideRecord('sys_user');24    if (u.get(gs.getUserID())) {25        return u.getValue('mobile_phone');26    } else {27        return '';28    }29}30// SET DEFAULT LOCATION VALUE BASED ON USER31javascript: getLoc();32function getLoc() {33    var u = new GlideRecord('sys_user');34    var location_table = new GlideRecord('cmn_location');35    if (u.get(gs.getUserID())) {36        var loc_key = u.getValue('location');37    } else {38        return '';39    }40    if (location_table.get(loc_key)) {41        var loc_name = location_table.getValue('name');42        return loc_name;43    } else {44        return '';45    }46}47// SET USERNAME BASED ON USER48javascript: getLoc();49function getLoc() {50    var u = new GlideRecord('sys_user');51    if (u.get(gs.getUserID())) {52        return u.getValue('user_name');53    } else {54        return '';55    }...Using AI Code Generation
1import {Selector} from 'testcafe';2test('My first test', async t => {3        .typeText('#developer-name', 'John Smith')4        .click('#submit-button')5        .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');6});7const testcafe = require('testcafe');8const getLoc = require('./getLoc');9const tc = testcafe('localhost', 1337, 1338);10    .createRunner()11    .src('./test.js')12    .browsers('chrome')13    .run()14    .then(failedCount => {15        console.log('Tests failed: ' + failedCount);16        tc.close();17    });18const { Selector } = require('testcafe');19const getLoc = (selector) => {20    return {21        typeText: async (text) => {22            await Selector(selector).typeText(text);23        },24        click: async () => {25            await Selector(selector).click();26        },27        getInnerText: async () => {28            await Selector(selector).innerText;29        }30    }31}32module.exports = getLoc;33import {Selector} from 'testcafe';34test('My first test', async t => {35        .typeText('#developer-name', 'John Smith')Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3        .typeText('#developer-name', 'John Smith')4        .click('#submit-button');5    const articleHeader = await Selector('.result-content').getLoc();6    console.log(articleHeader);7});8const createTestCafe = require('testcafe');9const fs = require('fs');10const htmlReporter = require('testcafe-reporter-html');11const testCafe = await createTestCafe('localhost', 1337, 1338);12const runner = testCafe.createRunner();13    .src('test.js')14    .browsers('chrome')15    .reporter(htmlReporter, {16        write: fs.createWriteStream('reports/report.html')17    })18    .run({19    });20testCafe.close();21const createTestCafe = require('testcafe');22const fs = require('fs');23const jsonReporter = require('testcafe-reporter-json');24const testCafe = await createTestCafe('localhost', 1337, 1338);25const runner = testCafe.createRunner();26    .src('test.js')27    .browsers('chrome')28    .reporter(jsonReporter, {29        write: fs.createWriteStream('reports/report.json')30    })31    .run({Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3        .typeText('#developer-name', 'John Smith')4        .click('#tried-test-cafe')5        .click(Selector('#submit-button'));6});7import { Selector } from 'testcafe';8import { getLoc } from 'testcafe-react-selectors';9const button = Selector(getLoc('Button'));10const input = Selector(getLoc('Input'));11test('My first test', async t => {12        .typeText(input, 'John Smith')13        .click(button);14});15getLoc(componentName, options)16import { getLoc } from 'testcafe-react-selectors';17const button = Selector(getLoc('Button'));18const input = Selector(getLoc('Input'));19test('My first test', async t => {20        .typeText(input, 'John Smith')21        .click(button);22});23getReact()24import { getReact } from 'testcafe-react-selectors';Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3    const getLocation = Selector(() => document.location.href);4        .expect(getLocation).contains('example');5});6import { Selector } from 'testcafe';7test('My first test', async t => {8    const getLocation = Selector(() => document.location.href, { visibilityCheck: true });9        .expect(getLocation).contains('example');10});11import { Selector } from 'testcafe';12test('My first test', async t => {13    const getLocation = Selector(() => document.location.href, { visibilityCheck: true });14    getLocation.myProperty = 'my property value';15        .expect(getLocation.myProperty).contains('my property value');16});17import { Selector } from 'testcafe';18test('My first test', async t => {19    const getLocation = Selector(() => document.location.href, { visibilityCheck: true });20    getLocation.myProperty = 'my property value';21    getLocation.myMethod = function () {22        return 'my method value';23    };24        .expect(getLocation.myMethod()).contains('my method value');25});Using AI Code Generation
1import { Selector } from 'testcafe';2test('My Test', async t => {3        .typeText('#developer-name', 'John Smith')4        .click('#submit-button');5    const articleHeader = await Selector('.result-content').find('h1');6    let headerText = await articleHeader.innerText;7    let headerLocation = await articleHeader.getLoc();8});9import { Selector } from 'testcafe';10test('My Test', async t => {11        .typeText('#developer-name', 'John Smith')12        .click('#submit-button');13    const articleHeader = await Selector('.result-content').find('h1');14    let headerText = await articleHeader.innerText;15    let headerLocation = await articleHeader.getLoc();16});17import { Selector } from 'testcafe';18test('My Test', async t => {19        .typeText('#developer-name', 'John Smith')20        .click('#submit-button');21    const articleHeader = await Selector('.result-content').find('h1');22    let headerText = await articleHeader.innerText;23    let headerLocation = await articleHeader.getLoc();24});25import { Selector } from 'testcafe';26test('My Test', async t => {27        .typeText('#developer-name', 'John Smith')28        .click('#submit-button');29    const articleHeader = await Selector('.result-content').find('h1Using AI Code Generation
1import { Selector } from 'testcafe';2import { getLoc } from './locators';3test('My first test', async t => {4        .typeText(getLoc('name'), 'Peter Parker')5        .click(getLoc('submit-button'));6});7import { Selector } from 'testcafe';8export const getLoc = (locatorName) => {9    const locators = {10        'name': Selector('input#developer-name'),11        'submit-button': Selector('#submit-button')12    };13    return locators[locatorName];14};15import { Selector } from 'testcafe';16import { getLoc } from './locators';17test('My first test', async t => {18        .typeText(getLoc('name'), 'Peter Parker')19        .click(getLoc('submit-button'));20});21import { Selector } from 'testcafe';22export const getLoc = (locatorName) => {23    const locators = {24        'name': Selector('input#developer-name'),25        'submit-button': Selector('#submit-button')26    };27    return locators[locatorName];28};29import { Selector } from 'testcafe';30import { getLoc } from './locators';Using AI Code Generation
1import { Selector } from 'testcafe';2test('Getting the location of an element', async t => {3    const element = Selector('#populate');4    const elementLocation = await element.getLoc();5    console.log(elementLocation);6});Using AI Code Generation
1import { Selector } from 'testcafe';2const getLoc = require('testcafe-react-selectors').getLoc;3const myReactComponent = Selector(getLoc('MyReactComponent'));4const myReactComponentButton = myReactComponent.find('button');5test('My test', async t => {6        .click(myReactComponentButton);7});8### getLoc(locator, options)Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
