Best JavaScript code snippet using cypress
cua_so.py
Source:cua_so.py
1import pygame2from geopy.geocoders import Nominatim3from geopy.distance import geodesic4import math56geolocator = Nominatim(user_agent="MyApp")7pygame.init()89# Create Screen10x_screen = 100011y_screen = 80012screen = pygame.display.set_mode((x_screen, y_screen))1314location_color = (255, 51, 153)15background_color = (255, 255, 255)16true_color = (0, 204, 0)17false_color = (255, 0, 0)18# Title of screen19pygame.display.set_caption("Wero - Wordle")2021# Text title22text_size_1 = 3023text_size_2 = 1524font_1 = pygame.font.SysFont("Times New Roman", text_size_1, bold=True)25font_2 = pygame.font.SysFont("Times New Roman", text_size_2, bold=True)26x_namegame = (x_screen // 2)27y_namegame = 02829wordle = font_1.render('Wordle', True, (0, 0, 0))30vietnam = font_1.render('VietNam', True, (255, 51, 153))31# running game3233game_location = 'Can Tho'34# guess_location = 'Lang Son'3536fps = 6037timer = pygame.time.Clock()383940def draw_checking_distance():41 pygame.draw.rect(screen, location_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 10, 100, 40), 2, 5)42 pygame.draw.rect(screen, location_color, pygame.Rect(x_screen // 2 + 240, y_screen // 16 + 10, 100, 40), 2, 5)43 pygame.draw.circle(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 30), 20, 5)44 # pygame.draw.line(screen, location_color, (x_screen// 2 + 405, y_screen//16 + 100), (x_screen// 2 + 420, y_screen//16 + 100), 4)4546 pygame.draw.rect(screen, location_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 80, 100, 40), 2, 5)47 pygame.draw.rect(screen, location_color, pygame.Rect(x_screen // 2 + 240, y_screen // 16 + 80, 100, 40), 2, 5)48 pygame.draw.circle(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 100), 20, 5)4950 pygame.draw.rect(screen, location_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 150, 100, 40), 2, 5)51 pygame.draw.rect(screen, location_color, pygame.Rect(x_screen // 2 + 240, y_screen // 16 + 150, 100, 40), 2, 5)52 pygame.draw.circle(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 170), 20, 5)5354 pygame.draw.rect(screen, location_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 220, 100, 40), 2, 5)55 pygame.draw.rect(screen, location_color, pygame.Rect(x_screen // 2 + 240, y_screen // 16 + 220, 100, 40), 2, 5)56 pygame.draw.circle(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 240), 20, 5)5758 pygame.draw.rect(screen, location_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 290, 100, 40), 2, 5)59 pygame.draw.rect(screen, location_color, pygame.Rect(x_screen // 2 + 240, y_screen // 16 + 290, 100, 40), 2, 5)60 pygame.draw.circle(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 310), 20, 5)616263# calculate distances of 5 places64def checking_distance_1(game_location, guess_location, distance=0):65 # calculate distance66 guess = guess_location67 location_1 = geolocator.geocode(guess)68 location_2 = geolocator.geocode(game_location)69 loc1 = (location_1.latitude, location_1.longitude)70 loc2 = (location_2.latitude, location_2.longitude)71 dis = str(int(geodesic(loc1, loc2).km))72 guess1 = font_2.render(guess, True, (255, 51, 153))73 distance = font_2.render(dis, True, (255, 51, 153))74 screen.blit(guess1, guess1.get_rect(center=(x_screen // 2 + 150, y_screen // 16 + 30)))75 screen.blit(distance, distance.get_rect(center=(x_screen // 2 + 290, y_screen // 16 + 30)))76 if dis == '0':77 pygame.draw.rect(screen, true_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 10, 100, 40), 2, 5)78 else:79 pygame.draw.rect(screen, false_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 10, 100, 40), 2, 5)80 # calculate compass direction81 alpha_1 = loc1[1] * (math.pi / 180)82 alpha_2 = loc2[1] * math.pi / 18083 phi_1 = loc1[0] * math.pi / 18084 phi_2 = loc2[0] * math.pi / 18085 delta_alpha = (alpha_2 - alpha_1)86 y = math.sin(delta_alpha) * math.cos(phi_2)87 x = math.cos(phi_1) * math.sin(phi_2) - math.sin(phi_1) * math.cos(phi_2) * math.cos(delta_alpha)88 angle = math.atan2(y, x)89 bearing = int((angle * 180 / math.pi + 360) % 360)90 if '0' == dis:91 pygame.draw.circle(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 30), 5, 5)92 elif 0 <= bearing < 90:93 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 30),94 (x_screen // 2 + 405, y_screen // 16 + 15), 4)95 elif 90 <= bearing < 180:96 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 30),97 (x_screen // 2 + 420, y_screen // 16 + 30), 4)98 elif 180 <= bearing < 270:99 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 30),100 (x_screen // 2 + 405, y_screen // 16 + 45), 4)101 elif 270 <= bearing < 360:102 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 45),103 (x_screen // 2 + 390, y_screen // 16 + 30), 4)104 print(dis)105 print(bearing)106107108def checking_distance_2(game_location, guess_location, distance=0):109 guess = guess_location110 location_1 = geolocator.geocode(guess)111 location_2 = geolocator.geocode(game_location)112 loc1 = (location_1.latitude, location_1.longitude)113 loc2 = (location_2.latitude, location_2.longitude)114 dis = str(int(geodesic(loc1, loc2).km))115 guess1 = font_2.render(guess, True, (255, 51, 153))116 distance = font_2.render(dis, True, (255, 51, 153))117 screen.blit(guess1, guess1.get_rect(center=(x_screen // 2 + 150, y_screen // 16 + 100)))118 screen.blit(distance, distance.get_rect(center=(x_screen // 2 + 290, y_screen // 16 + 100)))119 if dis == '0':120 pygame.draw.rect(screen, true_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 80, 100, 40), 2, 5)121 else:122 pygame.draw.rect(screen, false_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 80, 100, 40), 2, 5)123124 alpha_1 = loc1[1] * (math.pi / 180)125 alpha_2 = loc2[1] * math.pi / 180126 phi_1 = loc1[0] * math.pi / 180127 phi_2 = loc2[0] * math.pi / 180128 delta_alpha = (alpha_2 - alpha_1)129 y = math.sin(delta_alpha) * math.cos(phi_2)130 x = math.cos(phi_1) * math.sin(phi_2) - math.sin(phi_1) * math.cos(phi_2) * math.cos(delta_alpha)131 angle = math.atan2(y, x)132 bearing = int((angle * 180 / math.pi + 360) % 360)133 if '0' == dis:134 pygame.draw.circle(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 100), 5, 5)135 elif 0 <= bearing < 90:136 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 100),137 (x_screen // 2 + 405, y_screen // 16 + 85), 4)138 elif 90 <= bearing < 180:139 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 100),140 (x_screen // 2 + 420, y_screen // 16 + 100), 4)141 elif 180 <= bearing < 270:142 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 100),143 (x_screen // 2 + 405, y_screen // 16 + 115), 4)144 elif 270 <= bearing < 360:145 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 115),146 (x_screen // 2 + 390, y_screen // 16 + 100), 4)147 print(dis)148149150def checking_distance_3(game_location, guess_location, distance=0):151 guess = guess_location152 location_1 = geolocator.geocode(guess)153 location_2 = geolocator.geocode(game_location)154 loc1 = (location_1.latitude, location_1.longitude)155 loc2 = (location_2.latitude, location_2.longitude)156 dis = str(int(geodesic(loc1, loc2).km))157 guess1 = font_2.render(guess, True, (255, 51, 153))158 distance = font_2.render(dis, True, (255, 51, 153))159 screen.blit(guess1, guess1.get_rect(center=(x_screen // 2 + 150, y_screen // 16 + 170)))160 screen.blit(distance, distance.get_rect(center=(x_screen // 2 + 290, y_screen // 16 + 170)))161 if dis == '0':162 pygame.draw.rect(screen, true_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 150, 100, 40), 2, 5)163 else:164 pygame.draw.rect(screen, false_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 150, 100, 40), 2, 5)165166 alpha_1 = loc1[1] * (math.pi / 180)167 alpha_2 = loc2[1] * math.pi / 180168 phi_1 = loc1[0] * math.pi / 180169 phi_2 = loc2[0] * math.pi / 180170 delta_alpha = (alpha_2 - alpha_1)171 y = math.sin(delta_alpha) * math.cos(phi_2)172 x = math.cos(phi_1) * math.sin(phi_2) - math.sin(phi_1) * math.cos(phi_2) * math.cos(delta_alpha)173 angle = math.atan2(y, x)174 bearing = int((angle * 180 / math.pi + 360) % 360)175 if '0' == dis:176 pygame.draw.circle(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 170), 5, 5)177 elif 0 <= bearing < 90:178 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 170),179 (x_screen // 2 + 405, y_screen // 16 + 155), 4)180 elif 90 <= bearing < 180:181 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 170),182 (x_screen // 2 + 420, y_screen // 16 + 170), 4)183 elif 180 <= bearing < 270:184 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 170),185 (x_screen // 2 + 405, y_screen // 16 + 185), 4)186 elif 270 <= bearing < 360:187 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 185),188 (x_screen // 2 + 390, y_screen // 16 + 170), 4)189 print(dis)190191192def checking_distance_4(game_location, guess_location, distance=0):193 guess = guess_location194 location_1 = geolocator.geocode(guess)195 location_2 = geolocator.geocode(game_location)196 loc1 = (location_1.latitude, location_1.longitude)197 loc2 = (location_2.latitude, location_2.longitude)198 dis = str(int(geodesic(loc1, loc2).km))199 guess1 = font_2.render(guess, True, (255, 51, 153))200 distance = font_2.render(dis, True, (255, 51, 153))201 screen.blit(guess1, guess1.get_rect(center=(x_screen // 2 + 150, y_screen // 16 + 240)))202 screen.blit(distance, distance.get_rect(center=(x_screen // 2 + 290, y_screen // 16 + 240)))203204 if dis == '0':205 pygame.draw.rect(screen, true_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 220, 100, 40), 2, 5)206 else:207 pygame.draw.rect(screen, false_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 220, 100, 40), 2, 5)208209 alpha_1 = loc1[1] * (math.pi / 180)210 alpha_2 = loc2[1] * math.pi / 180211 phi_1 = loc1[0] * math.pi / 180212 phi_2 = loc2[0] * math.pi / 180213 delta_alpha = (alpha_2 - alpha_1)214 y = math.sin(delta_alpha) * math.cos(phi_2)215 x = math.cos(phi_1) * math.sin(phi_2) - math.sin(phi_1) * math.cos(phi_2) * math.cos(delta_alpha)216 angle = math.atan2(y, x)217 bearing = int((angle * 180 / math.pi + 360) % 360)218 if '0' == dis:219 pygame.draw.circle(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 240), 5, 5)220 elif 0 <= bearing < 90:221 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 240),222 (x_screen // 2 + 405, y_screen // 16 + 225), 4)223 elif 90 <= bearing < 180:224 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 240),225 (x_screen // 2 + 420, y_screen // 16 + 240), 4)226 elif 180 <= bearing < 270:227 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 240),228 (x_screen // 2 + 405, y_screen // 16 + 255), 4)229 elif 270 <= bearing < 360:230 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 255),231 (x_screen // 2 + 390, y_screen // 16 + 240), 4)232 print(dis)233234235def checking_distance_5(game_location, guess_location, distance=0):236 guess = guess_location237 location_1 = geolocator.geocode(guess)238 location_2 = geolocator.geocode(game_location)239 loc1 = (location_1.latitude, location_1.longitude)240 loc2 = (location_2.latitude, location_2.longitude)241 dis = str(int(geodesic(loc1, loc2).km))242 guess1 = font_2.render(guess, True, (255, 51, 153))243 distance = font_2.render(dis, True, (255, 51, 153))244 screen.blit(guess1, guess1.get_rect(center=(x_screen // 2 + 150, y_screen // 16 + 310)))245 screen.blit(distance, distance.get_rect(center=(x_screen // 2 + 290, y_screen // 16 + 310)))246 if dis == '0':247 pygame.draw.rect(screen, true_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 290, 100, 40), 2, 5)248 else:249 pygame.draw.rect(screen, false_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 290, 100, 40), 2, 5)250251 alpha_1 = loc1[1] * (math.pi / 180)252 alpha_2 = loc2[1] * math.pi / 180253 phi_1 = loc1[0] * math.pi / 180254 phi_2 = loc2[0] * math.pi / 180255 delta_alpha = (alpha_2 - alpha_1)256 y = math.sin(delta_alpha) * math.cos(phi_2)257 x = math.cos(phi_1) * math.sin(phi_2) - math.sin(phi_1) * math.cos(phi_2) * math.cos(delta_alpha)258 angle = math.atan2(y, x)259 bearing = int((angle * 180 / math.pi + 360) % 360)260 if '0' == dis:261 pygame.draw.circle(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 310), 5, 5)262 elif 0 <= bearing < 90:263 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 310),264 (x_screen // 2 + 405, y_screen // 16 + 295), 4)265 elif 90 <= bearing < 180:266 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 310),267 (x_screen // 2 + 420, y_screen // 16 + 310), 4)268 elif 180 <= bearing < 270:269 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 310),270 (x_screen // 2 + 405, y_screen // 16 + 325), 4)271 elif 270 <= bearing < 360:272 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 325),273 (x_screen // 2 + 390, y_screen // 16 + 310), 4)274 print(dis)275276# def checking_distance(x, game_location, guess_location, distance = 0):277# guess_1 = ''278# guess_2 = ''279# guess_3 = ''280# guess_4 = ''281# guess_5 = ''282# dis_1 = ''283# dis_2 = ''284# if x == 1:285# guess_1 = guess_location286# location_1 = geolocator.geocode(game_location)287# location_2 = geolocator.geocode(guess_1)288# loc1 = (location_1.latitude, location_1.longitude)289# loc2 = (location_2.latitude, location_2.longitude)290# dis_1 = str(int(geodesic(loc1, loc2).km))291# guess1 = font_2.render(guess_1, True, (255, 51, 153))292# distance_1 = font_2.render(dis_1, True, (255, 51, 153))293# screen.blit(guess1, guess1.get_rect(center = (x_screen// 2 + 150, y_screen//16 + 30)))294# screen.blit(distance_1, distance_1.get_rect(center = (x_screen// 2 + 290, y_screen//16 + 30)))295# print(dis_1)296# if x == 2:297# guess_2 = guess_location298#299# location_1 = geolocator.geocode(game_location)300# location_2 = geolocator.geocode(guess_2)301# loc1 = (location_1.latitude, location_1.longitude)302# loc2 = (location_2.latitude, location_2.longitude)303# dis_2 = str(int(geodesic(loc1, loc2).km))304#305# screen.blit(guess1, guess1.get_rect(center = (x_screen// 2 + 150, y_screen//16 + 30)))306# screen.blit(distance_1, distance_1.get_rect(center = (x_screen// 2 + 290, y_screen//16 + 30)))307# print(dis_1)308#309# guess2 = font_2.render(guess_2, True, (255, 51, 153))310# distance_2 = font_2.render(dis_2, True, (255, 51, 153))311# screen.blit(guess2, guess2.get_rect(center = (x_screen// 2 + 150, y_screen//16 + 100)))312# screen.blit(distance_2, distance_2.get_rect(center = (x_screen// 2 + 290, y_screen//16 + 100)))313# print(dis_2)314315316def getting_guess():317 guess = str(input('doan dia diem: '))318 return guess319320321x = 1322exit = False323guess_1 = ''324guess_2 = ''325guess_3 = ''326guess_4 = ''327guess_5 = ''328guess_6 = ''329while not exit:330 for event in pygame.event.get():331 if event.type == pygame.QUIT:332 exit = True333 timer.tick(fps)334 screen.fill(background_color)335 screen.blit(wordle, wordle.get_rect(center=(x_namegame - 55, 20)))336 screen.blit(vietnam, vietnam.get_rect(center=(x_namegame + 55, 20)))337 draw_checking_distance()338 print(x)339 if x == 1:340 guess_1 = getting_guess()341 checking_distance_1(guess_location=guess_1, game_location=game_location)342 if x == 2:343 guess_2 = getting_guess()344 checking_distance_1(guess_location=guess_1, game_location=game_location)345 checking_distance_2(guess_location=guess_2, game_location=game_location)346 if x == 3:347 guess_3 = getting_guess()348 checking_distance_1(guess_location=guess_1, game_location=game_location)349 checking_distance_2(guess_location=guess_2, game_location=game_location)350 checking_distance_3(guess_location=guess_3, game_location=game_location)351 if x == 4:352 guess_4 = getting_guess()353 checking_distance_1(guess_location=guess_1, game_location=game_location)354 checking_distance_2(guess_location=guess_2, game_location=game_location)355 checking_distance_3(guess_location=guess_3, game_location=game_location)356 checking_distance_4(guess_location=guess_4, game_location=game_location)357 if x == 5:358 guess_5 = getting_guess()359 checking_distance_1(guess_location=guess_1, game_location=game_location)360 checking_distance_2(guess_location=guess_2, game_location=game_location)361 checking_distance_3(guess_location=guess_3, game_location=game_location)362 checking_distance_4(guess_location=guess_4, game_location=game_location)363 checking_distance_5(guess_location=guess_5, game_location=game_location)364 if x == 6:365 guess_6 = getting_guess()366 pygame.display.update()367 pygame.display.flip()368 x += 1369 # checking_distance(x, game_location, guess_location)370 # if x == 1:371 # guess_location = str(input())372 # checking_distance(x, game_location, guess_location)
...
nativescript-geolocation.js
Source:nativescript-geolocation.js
1"use strict";2Object.defineProperty(exports, "__esModule", { value: true });3var application_1 = require("application");4var platform_1 = require("platform");5var enums_1 = require("ui/enums");6var timer_1 = require("timer");7var trace_1 = require("trace");8var nativescript_geolocation_common_1 = require("./nativescript-geolocation-common");9var locationListeners = {};10var watchId = 0;11var androidLocationManager;12function getAndroidLocationManager() {13 if (!androidLocationManager) {14 androidLocationManager = application_1.android.context15 .getSystemService(android.content.Context.LOCATION_SERVICE);16 }17 return androidLocationManager;18}19function createLocationListener(successCallback) {20 var locationListener = new android.location.LocationListener({21 onLocationChanged: function (location1) {22 var locationCallback = this._onLocation;23 if (locationCallback) {24 locationCallback(locationFromAndroidLocation(location1));25 }26 },27 onProviderDisabled: function (provider) {28 },29 onProviderEnabled: function (provider) {30 },31 onStatusChanged: function (arg1, arg2, arg3) {32 }33 });34 watchId++;35 locationListener._onLocation = successCallback;36 locationListener.id = watchId;37 locationListeners[watchId] = locationListener;38 return locationListener;39}40function locationFromAndroidLocation(androidLocation) {41 var location = new nativescript_geolocation_common_1.Location();42 location.latitude = androidLocation.getLatitude();43 location.longitude = androidLocation.getLongitude();44 location.altitude = androidLocation.getAltitude();45 location.horizontalAccuracy = androidLocation.getAccuracy();46 location.verticalAccuracy = androidLocation.getAccuracy();47 location.speed = androidLocation.getSpeed();48 location.direction = androidLocation.getBearing();49 location.timestamp = new Date(androidLocation.getTime());50 location.android = androidLocation;51 return location;52}53function androidLocationFromLocation(location) {54 var androidLocation = new android.location.Location("custom");55 androidLocation.setLatitude(location.latitude);56 androidLocation.setLongitude(location.longitude);57 if (location.altitude) {58 androidLocation.setAltitude(location.altitude);59 }60 if (location.speed) {61 androidLocation.setSpeed(float(location.speed));62 }63 if (location.direction) {64 androidLocation.setBearing(float(location.direction));65 }66 if (location.timestamp) {67 try {68 androidLocation.setTime(long(location.timestamp.getTime()));69 }70 catch (e) {71 console.error("invalid location timestamp");72 }73 }74 return androidLocation;75}76function criteriaFromOptions(options) {77 var criteria = new android.location.Criteria();78 if (options && options.desiredAccuracy <= enums_1.Accuracy.high) {79 criteria.setAccuracy(android.location.Criteria.ACCURACY_FINE);80 }81 else {82 criteria.setAccuracy(android.location.Criteria.ACCURACY_COARSE);83 }84 return criteria;85}86function watchLocationCore(errorCallback, options, locListener) {87 var criteria = criteriaFromOptions(options);88 try {89 var updateTime = (options && typeof options.minimumUpdateTime === "number") ?90 options.minimumUpdateTime :91 nativescript_geolocation_common_1.minTimeUpdate;92 var updateDistance = (options && typeof options.updateDistance === "number") ?93 options.updateDistance :94 nativescript_geolocation_common_1.minRangeUpdate;95 getAndroidLocationManager().requestLocationUpdates(updateTime, updateDistance, criteria, locListener, null);96 }97 catch (e) {98 LocationMonitor.stopLocationMonitoring(locListener.id);99 errorCallback(e);100 }101}102function enableLocationServiceRequest(currentContext, successCallback, successArgs, errorCallback, errorArgs) {103 if (!isEnabled()) {104 var onActivityResultHandler_1 = function (data) {105 application_1.android.off(application_1.AndroidApplication.activityResultEvent, onActivityResultHandler_1);106 if (data.requestCode === 0) {107 if (isEnabled()) {108 if (successCallback) {109 successCallback.apply(this, successArgs);110 }111 }112 else {113 if (errorCallback) {114 errorCallback.apply(this, errorArgs);115 }116 }117 }118 application_1.android.off(application_1.AndroidApplication.activityResultEvent, onActivityResultHandler_1);119 };120 application_1.android.on(application_1.AndroidApplication.activityResultEvent, onActivityResultHandler_1);121 var LOCATION_SETTINGS = android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS;122 currentContext.startActivityForResult(new android.content.Intent(LOCATION_SETTINGS), 0);123 }124 else {125 if (successCallback) {126 successCallback.apply(this, successArgs);127 }128 }129}130function enableLocationRequestCore(successCallback, successArgs, errorCallback, errorArgs) {131 var currentContext = application_1.android.currentContext;132 if (parseInt(platform_1.device.sdkVersion) >= 23) {133 var activityRequestPermissionsHandler_1 = function (data) {134 if (data.requestCode === 5000) {135 var PERMISSION_GRANTED = android.content.pm.PackageManager.PERMISSION_GRANTED;136 if (data.grantResults.length > 0 && data.grantResults[0] === PERMISSION_GRANTED) {137 enableLocationServiceRequest(currentContext, successCallback, successArgs, errorCallback, errorArgs);138 }139 else {140 if (errorCallback) {141 errorCallback.apply(this, errorArgs);142 }143 }144 }145 application_1.android.off(application_1.AndroidApplication.activityRequestPermissionsEvent, activityRequestPermissionsHandler_1);146 };147 application_1.android.on(application_1.AndroidApplication.activityRequestPermissionsEvent, activityRequestPermissionsHandler_1);148 var res = android.support.v4.content.ContextCompat149 .checkSelfPermission(currentContext, android.Manifest.permission.ACCESS_FINE_LOCATION);150 if (res === -1) {151 android.support.v4.app.ActivityCompat152 .requestPermissions(currentContext, ["android.permission.ACCESS_FINE_LOCATION"], 5000);153 }154 else {155 enableLocationServiceRequest(currentContext, successCallback, successArgs, errorCallback, errorArgs);156 }157 }158 else {159 enableLocationServiceRequest(currentContext, successCallback, successArgs, errorCallback, errorArgs);160 }161}162function watchLocation(successCallback, errorCallback, options) {163 var zonedSuccessCallback = global.zonedCallback(successCallback);164 var zonedErrorCallback = global.zonedCallback(errorCallback);165 var locListener = createLocationListener(zonedSuccessCallback);166 if (!isEnabled()) {167 var notGrantedError = new Error("Location service is not enabled or using it is not granted.");168 enableLocationRequestCore(watchLocationCore, [169 zonedSuccessCallback,170 zonedErrorCallback,171 options,172 locListener173 ], zonedErrorCallback, [notGrantedError]);174 }175 else {176 watchLocationCore(zonedErrorCallback, options, locListener);177 }178 return locListener.id;179}180exports.watchLocation = watchLocation;181function getCurrentLocation(options) {182 options = options || {};183 if (options.timeout === 0) {184 return new Promise(function (resolve, reject) {185 var lastLocation = LocationMonitor.getLastKnownLocation();186 if (lastLocation) {187 if (typeof options.maximumAge === "number") {188 if (lastLocation.timestamp.valueOf() + options.maximumAge > new Date().valueOf()) {189 resolve(lastLocation);190 }191 else {192 reject(new Error("Last known location too old!"));193 }194 }195 else {196 resolve(lastLocation);197 }198 }199 else {200 reject(new Error("There is no last known location!"));201 }202 });203 }204 return new Promise(function (resolve, reject) {205 var locListener;206 var enabledCallback = function (ecbResolve, ecbReject, ecbOptions) {207 var successCallback = function (location) {208 LocationMonitor.stopLocationMonitoring(locListener.id);209 if (ecbOptions && typeof ecbOptions.maximumAge === "number") {210 if (location.timestamp.valueOf() + ecbOptions.maximumAge > new Date().valueOf()) {211 ecbResolve(location);212 }213 else {214 ecbReject(new Error("New location is older than requested maximum age!"));215 }216 }217 else {218 ecbResolve(location);219 }220 };221 locListener = LocationMonitor.createListenerWithCallbackAndOptions(successCallback, ecbOptions);222 try {223 getAndroidLocationManager().requestSingleUpdate(criteriaFromOptions(ecbOptions), locListener, null);224 }225 catch (e) {226 ecbReject(e);227 }228 if (ecbOptions && typeof ecbOptions.timeout === "number") {229 var timerId_1 = timer_1.setTimeout(function () {230 timer_1.clearTimeout(timerId_1);231 LocationMonitor.stopLocationMonitoring(locListener.id);232 ecbReject(new Error("Timeout while searching for location!"));233 }, ecbOptions.timeout || nativescript_geolocation_common_1.defaultGetLocationTimeout);234 }235 };236 var permissionDeniedCallback = function (pdcReject) {237 pdcReject(new Error("Location service is not enabled or using it is not granted."));238 };239 if (!isEnabled()) {240 enableLocationRequestCore(enabledCallback, [resolve, reject, options], permissionDeniedCallback, [reject]);241 }242 else {243 enabledCallback(resolve, reject, options);244 }245 });246}247exports.getCurrentLocation = getCurrentLocation;248function clearWatch(_watchId) {249 LocationMonitor.stopLocationMonitoring(_watchId);250}251exports.clearWatch = clearWatch;252function enableLocationRequest(always) {253 return new Promise(function (resolve, reject) {254 if (isEnabled()) {255 resolve();256 return;257 }258 var enabledCallback = function (ecbResolve, ecbReject) {259 ecbResolve();260 };261 var permissionDeniedCallback = function (pdcReject) {262 pdcReject(new Error("Location service is not enabled or using it is not granted."));263 };264 enableLocationRequestCore(enabledCallback, [resolve], permissionDeniedCallback, [reject]);265 });266}267exports.enableLocationRequest = enableLocationRequest;268function isEnabled() {269 var criteria = new android.location.Criteria();270 criteria.setAccuracy(android.location.Criteria.ACCURACY_COARSE);271 var enabledProviders = getAndroidLocationManager().getProviders(criteria, true);272 return (enabledProviders.size() > 0) ? true : false;273}274exports.isEnabled = isEnabled;275function distance(loc1, loc2) {276 if (!loc1.android) {277 loc1.android = androidLocationFromLocation(loc1);278 }279 if (!loc2.android) {280 loc2.android = androidLocationFromLocation(loc2);281 }282 return loc1.android.distanceTo(loc2.android);283}284exports.distance = distance;285var LocationMonitor = (function () {286 function LocationMonitor() {287 }288 LocationMonitor.getLastKnownLocation = function () {289 var criteria = new android.location.Criteria();290 criteria.setAccuracy(android.location.Criteria.ACCURACY_COARSE);291 try {292 var iterator = getAndroidLocationManager().getProviders(criteria, false).iterator();293 var androidLocation = void 0;294 while (iterator.hasNext()) {295 var provider = iterator.next();296 var tempLocation = getAndroidLocationManager().getLastKnownLocation(provider);297 if (!androidLocation || tempLocation.getTime() > androidLocation.getTime()) {298 androidLocation = tempLocation;299 }300 }301 if (androidLocation) {302 return locationFromAndroidLocation(androidLocation);303 }304 }305 catch (e) {306 trace_1.write("Error: " + e.message, "Error");307 }308 return null;309 };310 LocationMonitor.startLocationMonitoring = function (options, listener) {311 var updateTime = (options && typeof options.minimumUpdateTime === "number") ?312 options.minimumUpdateTime :313 nativescript_geolocation_common_1.minTimeUpdate;314 var updateDistance = (options && typeof options.updateDistance === "number") ?315 options.updateDistance :316 nativescript_geolocation_common_1.minRangeUpdate;317 getAndroidLocationManager().requestLocationUpdates(updateTime, updateDistance, criteriaFromOptions(options), listener, null);318 };319 LocationMonitor.createListenerWithCallbackAndOptions = function (successCallback, options) {320 return createLocationListener(successCallback);321 };322 LocationMonitor.stopLocationMonitoring = function (locListenerId) {323 var listener = locationListeners[locListenerId];324 if (listener) {325 getAndroidLocationManager().removeUpdates(listener);326 delete locationListeners[locListenerId];327 }328 };329 return LocationMonitor;330}());...
setup.py
Source:setup.py
1from math import isnan2import placemaker3'''4 Area for yahoo placemaker and other 5 location finding functions6'''7YAHOO_APPID = 'dj0yJmk9OG9SNGFTbmphTTZiJmQ9WVdrOVMxVnBhbXh3TldjbWNHbzlNamcyTXpnek1EWXkmcz1jb25zdW1lcnNlY3JldCZ4PTMw'8YAHOO_TYPES = ['Commune', 9 'Municipality', 10 'District', 11 'Ward',12 'POI', 13 'Town', 14 'Suburb', 15 'Postal Code',16 'LocalAdmin',17 'County', 18 'Zip']19p = placemaker.placemaker(YAHOO_APPID)20 21def encode_utf8(s):22 if isinstance(s, unicode):23 return s.encode('utf-8')24 try:25 s.decode('utf-8')26 return str(s)27 except:28 pass29 try:30 return str(s.encode('utf-8'))31 except:32 res = ''.join([unichr(ord(c)) for c in s])33 return str(res.encode('utf-8'))34 35def get_coordinates_from_text(text):36 # use yahoo placemaker to search for locations37 try:38 location = p.find_places(encode_utf8(text))39 time.sleep(0.1)40 except Exception, e:41 print 'Error in placemaker: %s' % e42 time.sleep(5)43 location = []44 if len(location) == 0:45 return None46 location = location[0]47 print 'output %s - %s' % (location.placetype, location.name)48 #if location.placetype in YAHOO_TYPES:49 return [location.centroid.latitude, 50 location.centroid.longitude]51 print 'nothing for ' + text52 return None53 54location_cache = {}55'''56 Putting user info in a dictionary57'''58'''59user_info = {}60user_info_file = pd.read_csv("users.csv")61# Populate dictionary62for user in user_info_file.iterrows():63 user = user[1]64 location = None65 66 # process location67 if isinstance(user['location'], str):68 if user['location'] in location_cache:69 location = location_cache[user['location']]70 else:71 location = get_coordinates_from_text(user['location'])72 if location:73 location_cache[user['location']] = location74 else:75 location = None76 77 78 user_info[user['user_id']] = {79 'birth': user['birthyear'],80 'gender': user['gender'],81 'location': location,82 }83 84# Alternate code for writing to mongo85data = json.loads(open('data', 'r').read())86for uid, user in data.iteritems():87 user['id'] = int(uid)88 user_info.insert([user])89'''90 91'''92 Create attendance dictionaries93 Provided in both directions94'''95'''96def update_attendance(uid, eid, att_type):97 attendance.update(98 {'uid': uid, 'eid': eid},99 {'$set': {'uid': uid, 'eid': eid, att_type: True}}, 100 upsert=True)101chunks = pd.read_csv("events.csv", iterator=True, chunksize=1000)102count = 0103for chunk in chunks:104 print count105 count += 1000106 107 for e in chunk.iterrows():108 e = e[1]109 eid = e['event_id']110 uid = e['user_id']111 112 update_attendance(uid, eid, 'yes')113 update_attendance(uid, eid, 'interested')114''' 115 116'''117 Populate events dictionary118'''119'''120chunks = pd.read_csv("events.csv", iterator=True, chunksize=1000)121count = 0122for chunk in chunks:123 print count124 count += 1000125 #if count < 1564000:126 # continue127 for e in chunk.iterrows():128 e = e[1]129 eid = e['event_id']130 location = None131 if e['lat'] and e['lng'] and not isnan(e['lat']) and not isnan(e['lng']):132 location = [e['lat'], e['lng']]133 elif e['city'] or e['state'] or e['country']:134 loc_string = '%s, %s, %s' % (e['city'], e['state'], e['country'])135 if loc_string in location_cache:136 location = location_cache[loc_string]137 else:138 location = get_coordinates_from_text(loc_string)139 if location:140 location_cache[loc_string] = location141 142 words = list(e[9:110])143 event = {144 'id': eid,145 'location': location,146 'words': words147 }148 event_info.insert([event])149 150chunks = pd.read_csv("events.csv", iterator=True, chunksize=1000)151count = 0152for chunk in chunks:153 print count154 count += 1000155 for e in chunk.iterrows():156 e = e[1]157 eid = e['event_id']158 uid = e['user_id']159 # add creator to event attendance collection160 update_attendance(uid, eid, 'yes')161 update_attendance(uid, eid, 'interested')162''' 163 164'''165 Insert train data into attendance collection166'''167'''168train = pd.read_csv( "train.csv", converters={"timestamp": parse})169for pair in train.iterrows():170 pair = pair[1]171 uid = pair['user']172 eid = pair['event']173 for attr in ['invited', 'interested', 'not_interested']:174 if pair[attr]:175 update_attendance(uid, eid, attr)176'''177''' 178 Process event_attendees file to update attendance collection179'''180'''181event_attendees = pd.read_csv("event_attendees.csv")182for event in event_attendees.iterrows():183 event = event[1]184 eid = event['event']185 for attr in ['yes', 'maybe', 'invited', 'no']:186 users = event[attr]187 if isinstance(users, float):188 continue189 users = [int(u) for u in users.split()]190 for uid in users:191 update_attendance(uid, eid, attr)192'''193''' 194 Process friends file195'''196'''197friends_file = pd.read_csv('user_friends.csv')198friends_dict = {}199# create friends data in memory200for record in friends_file.iterrows():201 record = record[1]202 uid1 = record['user']203 if uid1 not in friends_dict:204 friends_dict[uid1] = []205 friends = record['friends']206 if isinstance(friends, float):207 continue208 friends = [int(u) for u in record['friends'].split()]209 for uid2 in friends:210 friends_dict[uid1].append(uid2)211 212# copy data to mongo213for uid, friends in friends_dict.iteritems():214 record = {215 'uid': uid,216 'friends': list(friends)217 }218 friends_db.insert([record])219'''220''' 221 Fill out missing location222'''223user_sure = {}224event_sure = {}225for user in user_info.find():226 if user['location']:227 user_sure[user['id']] = user['location']228 229for event in event_info.find():230 if event['location']:231 event_sure[event['id']] = event['location']232 233count = 0234for event in event_info.find():235 count += 1236 if count % 10000 == 0:237 print count238 location = event['location']239 if location:240 if len(location) == 2 and isinstance(location[0], float) and \241 (isnan(location[0]) or isnan(location[1])):242 location = None243 else:244 if isinstance(location[0], list):245 location = [tuple(l) for l in location]246 else:247 location = tuple(location)248 249 event_info.update({'id': event['id']},250 {'$set': {'location': location}})251 252count = 0253updated = 0254for event in event_info.find():255 count += 1256 if count % 1000 == 0:257 print count258 259 if event['id'] in event_locations:260 continue261 262 attend = attendance.find({'eid': event['id']})263 votes = {}264 265 for a in attend:266 if 'yes' not in a:267 continue268 if a['uid'] in user_sure:269 location = user_sure[a['uid']]270 if isinstance(location[0], float) or isinstance(location[0], int):271 location = [location]272 for l in location:273 l = tuple(l)274 votes[l] = votes.get(l, 0) + 1275 276 if not votes: 277 continue278 279 votes = votes.items()280 votes.sort(key=lambda x: -x[1])281 votes = votes[:5]282 if len(votes) > 1 and votes[0][1] > 3 * votes[1][1]:283 votes = [votes[1]]284 285 votes = [list(v[0]) for v in votes]286 287 if len(votes) == 1:288 votes = votes[0]289 290 print votes291 updated += 1292 event_info.update({'id': event['id']},293 {'$set': {'location': votes}})294 295 296count = 0297updated = 0298for user in user_info.find():299 count += 1300 if count % 1000 == 0:301 print count302 303 if user['id'] in user_sure:304 continue305 306 attend = attendance.find({'uid': user['id']})307 votes = {}308 309 for a in attend:310 if a['eid'] in event_sure:311 location = event_sure[a['eid']]312 if isinstance(location[0], float) or isinstance(location[0], int):313 location = [location]314 for l in location:315 votes[tuple(l)] = votes.get(tuple(l), 0) + 1316 317 if not votes: 318 continue319 320 votes = votes.items()321 votes.sort(key=lambda x: -x[1])322 votes = votes[:5]323 if len(votes) > 1 and votes[0][1] > 3 * votes[1][1]:324 votes = [votes[1]]325 326 votes = [list(v[0]) for v in votes]327 user_sure[user['id']] = votes328 329 updated += 1330 user_info.update({'id': user['id']},331 {'$set': {'location': votes}})332 333for user in user_info.find():334 if not user['location']:335 continue336 user_info.update({'id': user['id']},337 {'$set': {'location': tuple(user['location'])}})338 339user_dict = list(user_info.find())340user_dict = {u['id']:u for u in user_dict}341# create event profiles based on users342event_ids = set([])343for u in user_info.find():344 if u['age']:345 attends = attendance.find({'uid': u['id']})346 347 348count = event_info.count()349for e in event_info.find():350 attends = attendance.find({'eid': e['id']})351 count -= 1352 if count % 10000 == 0:353 print count354 ages = []355 sexes = {'male':0, 'female':0}356 for at in attends:357 if 'yes' not in attends:358 continue359 uid = at['uid']360 if uid in user_dict:361 a = user_dict[uid]['age']362 if a:363 ages.append(a)364 365 if ages:366 age = np.mean(ages)367 print age368 break369 event_info.update({'id': e['id']},370 {'$set': {'age': age}})371 372 373 374user_info_file = pd.read_csv("users.csv")375updated = 0376for user in user_info_file.iterrows():377 user = user[1]378 location = None379 380 if user['user_id'] in user_sure:381 continue382 383 # process location384 if isinstance(user['location'], str):385 location = get_coordinates_from_text(user['location'])386 else:387 location = None388 389 if location:390 updated += 1391 user_sure[user['user_id']] = [location]392 user_info.update({'id': user['user_id']},393 {'$set': {'location': [location]}})394 395 396count = 0397updated = 0398friends_info = {}399for user in user_info.find():400 count += 1401 if count % 1000 == 0:402 print count403 404 if user['id'] in user_sure:405 continue406 407 friends = friends_db.find_one({'uid': user['id']})408 friends = friends['friends']409 friends = list(user_info.find({'id':{'$in': friends}}))410 friends_info[user['id']] = friends411updated = 0412for uid, friends in friends_info.iteritems():413 s = 0414 nr = 0415 416 for f in friends:417 if f['age']:418 s += f['age']419 nr += 1420 if nr:421 guess = s * 1.0 / nr422 user_info.update({'id': uid},423 {'$set': {'age': guess}})424 updated += 1425 426 427count = 0428event_locations = {}429for e in event_info.find():430 count += 1431 if count % 10000 == 0:432 print count433 if e['location']:434 event_locations[e['id']] = e['location']435 436count = 0437updated = 0438for event in event_info.find():439 count += 1440 if count % 10000 == 0:441 print count442 443 location = event['location']444 if location:445 continue446 loc_string = event_locations.get(event['id'])447 if not loc_string or loc_string == 'nan, nan, nan':448 continue449 450 if loc_string in location_cache:451 location = location_cache[loc_string]452 else:453 location = get_coordinates_from_text(loc_string)454 if location:455 location_cache[loc_string] = location456 457 if location:458 updated += 1459 event_info.update({'id': event['id']},460 {'$set': {'location': location}})461 462for u in user_info.find():463 a = u['birth']464 try:465 a = int(a)466 if a < 1940:467 a = None468 else:469 a = 2013 - a470 except:471 a = None472 ages[a] = ages.get(a, 0) + 1473 user_info.update({'id': u['id']},474 {'$set': {'age': a}})475 476user_sure = {}477for u in user_info.find():478 a = u['age']479 if a:480 user_sure[u['id']] = a481 482 483# set user timezone from file484user_info_file = pd.read_csv("users.csv")485user_tz = {}486updated = 0487for user in user_info_file.iterrows():488 user = user[1]489 tz = user['timezone']490 if math.isnan(tz):491 tz = None492 user_tz[user['user_id']] = tz493 494for uid, tz in user_tz.iteritems():495 user_info.update({'id': uid},496 {'$set': {'timezone': tz}})497 498# propagate timezone499etz = {}500for a in attendance.find():501 eid = a['eid']502 uid = a['uid']503 if uid not in user_tz:504 continue505 if 'yes' not in a and 'maybe' not in a:506 continue507 if eid not in etz:508 etz[eid] = {}509 tz = user_tz[a['uid']]510 etz[eid][tz] = etz[eid].get(tz, 0) + 1 511 512etzf = {}513for eid, tz_dict in etz.iteritems():514 tzl = tz_dict.items()515 tzl.sort(key=lambda x: -x[1])516 etzf[eid] = tzl[0]517 518 519count = len(etzf)520for eid, tz in etzf.iteritems():521 count -= 1522 if count % 10000 == 0:523 print count524 event_info.update({'id': eid},525 {'$set': {'timezone': tz}})526 527 528 529chunks = pd.read_csv("events.csv", iterator=True, chunksize=10000)530count = 0531for chunk in chunks:532 print count533 count += 10000534 for e in chunk.iterrows():535 e = e[1]536 t = e['start_time']537 t = parse(t)538 t = time.mktime(t.timetuple())539 event_info.update({'id': e['event_id']},...
test_trace_parser.py
Source:test_trace_parser.py
...37 builder = TraceTreeBuilder()38 trace = builder \39 .start_test("Andreas") \40 .start_unit("Tommy") \41 .enter_location("1") \42 .end_unit() \43 .end_test() \44 .build()45 sequence = [ *trace.sequence ]46 self.assertEqual(len(sequence), 1)47 location_1: Location = sequence[0]48 self.assertIsInstance(location_1, Location)49 self.assertEqual(location_1.test.name, "Andreas")50 self.assertEqual(location_1.unit.name, "Tommy")51 self.assertEqual(location_1.id, "1")52 def test_trace_tree_builder_two_units_two_locations_test_trace(self) -> None:53 builder = TraceTreeBuilder()54 trace = builder \55 .start_test("Andreas") \56 .start_unit("Tommy1") \57 .enter_location("1") \58 .start_unit("Tommy2") \59 .enter_location("2") \60 .end_unit() \61 .end_unit() \62 .end_test() \63 .build()64 sequence = [ *trace.sequence ]65 self.assertEqual(len(sequence), 2)66 location_1: Location = sequence[0]67 self.assertEqual(location_1.test.name, "Andreas")68 self.assertEqual(location_1.unit.name, "Tommy1")69 self.assertEqual(location_1.id, "1")70 location_2: Location = sequence[1]71 self.assertEqual(location_2.test.name, "Andreas")72 self.assertEqual(location_2.unit.name, "Tommy2")73 self.assertEqual(location_2.id, "2")74 75 self.assertEqual(location_1.test, location_2.test)76 def test_trace_tree_builder_two_units_three_locations_test_trace(self) -> None:77 builder = TraceTreeBuilder()78 trace = builder \79 .start_test("Andreas") \80 .start_unit("Tommy1") \81 .enter_location("1") \82 .start_unit("Tommy2") \83 .enter_location("2") \84 .end_unit() \85 .enter_location("3") \86 .end_unit() \87 .end_test() \88 .build()89 sequence = [ *trace.sequence ]90 self.assertEqual(len(sequence), 3)91 location_1: Location = sequence[0]92 self.assertEqual(location_1.unit.name, "Tommy1")93 self.assertEqual(location_1.id, "1")94 location_2: Location = sequence[1]95 self.assertEqual(location_2.unit.name, "Tommy2")96 self.assertEqual(location_2.id, "2")97 location_3: Location = sequence[2]98 self.assertEqual(location_3.unit.name, "Tommy1")99 self.assertEqual(location_3.id, "3")100 101 self.assertEqual(location_1.test, location_2.test)102 self.assertEqual(location_2.test, location_3.test)103 def test_trace_tree_builder_many_units_many_locations_test_trace(self) -> None:104 builder = TraceTreeBuilder()105 trace = builder \106 .start_test("Andreas") \107 .start_unit("Tommy1") \108 .enter_location("1") \109 .start_unit("Tommy2") \110 .enter_location("2") \111 .enter_location("3") \112 .start_unit("Tommy3") \113 .enter_location("4") \114 .end_unit() \115 .enter_location("5") \116 .end_unit() \117 .enter_location("6") \118 .start_unit("Tommy4") \119 .enter_location("7") \120 .start_unit("Tommy5") \121 .enter_location("8") \122 .end_unit() \123 .enter_location("9") \124 .end_unit() \125 .enter_location("10") \126 .end_unit() \127 .end_test() \128 .build()129 sequence = [ *trace.sequence ]130 self.assertEqual(len(sequence), 10)131 location_1: Location = sequence[0]132 self.assertEqual(location_1.test.name, "Andreas")133 self.assertEqual(location_1.unit.name, "Tommy1")134 self.assertEqual(location_1.id, "1")135 location_2: Location = sequence[1]136 self.assertEqual(location_2.test.name, "Andreas")137 self.assertEqual(location_2.unit.name, "Tommy2")138 self.assertEqual(location_2.id, "2")139 location_3: Location = sequence[2]140 self.assertEqual(location_3.test.name, "Andreas")141 self.assertEqual(location_3.unit.name, "Tommy2")142 self.assertEqual(location_3.id, "3")143 location_4: Location = sequence[3]144 self.assertEqual(location_4.test.name, "Andreas")145 self.assertEqual(location_4.unit.name, "Tommy3")146 self.assertEqual(location_4.id, "4")147 location_5: Location = sequence[4]148 self.assertEqual(location_5.test.name, "Andreas")149 self.assertEqual(location_5.unit.name, "Tommy2")150 self.assertEqual(location_5.id, "5")151 location_6: Location = sequence[5]152 self.assertEqual(location_6.test.name, "Andreas")153 self.assertEqual(location_6.unit.name, "Tommy1")154 self.assertEqual(location_6.id, "6")155 location_7: Location = sequence[6]156 self.assertEqual(location_7.test.name, "Andreas")157 self.assertEqual(location_7.unit.name, "Tommy4")158 self.assertEqual(location_7.id, "7")159 location_8: Location = sequence[7]160 self.assertEqual(location_8.test.name, "Andreas")161 self.assertEqual(location_8.unit.name, "Tommy5")162 self.assertEqual(location_8.id, "8")163 location_9: Location = sequence[8]164 self.assertEqual(location_9.test.name, "Andreas")165 self.assertEqual(location_9.unit.name, "Tommy4")166 self.assertEqual(location_9.id, "9")167 location_10: Location = sequence[9]168 self.assertEqual(location_10.test.name, "Andreas")169 self.assertEqual(location_10.unit.name, "Tommy1")170 self.assertEqual(location_10.id, "10")171 def test_trace_in_unit(self) -> None:172 builder = TraceTreeBuilder()173 trace = builder \174 .start_test("Andreas") \175 .start_unit("Tommy1") \176 .enter_location("1") \177 .start_unit("Tommy2") \178 .enter_location("2") \179 .enter_location("3") \180 .start_unit("Tommy3") \181 .enter_location("4") \182 .end_unit() \183 .enter_location("5") \184 .end_unit() \185 .enter_location("6") \186 .start_unit("Tommy4") \187 .enter_location("7") \188 .start_unit("Tommy5") \189 .enter_location("8") \190 .end_unit() \191 .enter_location("9") \192 .end_unit() \193 .enter_location("10") \194 .end_unit() \195 .end_test() \196 .build()197 actual = [ *trace.in_unit("Tommy1") ]198 self.assertEqual(len(actual), 3)199 location_1: Location = actual[0]200 self.assertEqual(location_1.test.name, "Andreas")201 self.assertEqual(location_1.unit.name, "Tommy1")202 self.assertEqual(location_1.id, "1")203 location_6: Location = actual[1]204 self.assertEqual(location_6.test.name, "Andreas")205 self.assertEqual(location_6.unit.name, "Tommy1")206 self.assertEqual(location_6.id, "6")207 location_10: Location = actual[2]...
1063.py
Source:1063.py
1 2def move(moving,king_location,stone_location):3 king_location = list(king_location)4 king_location[1] = int(king_location[1])5 stone_location = list(stone_location)6 stone_location[1] = int(stone_location[1])7 8 if moving == 'B':9 if king_location[1] != 1:10 if ((king_location[1]-1) == (stone_location[1])) & ((king_location[0]) == (stone_location[0])):11 if stone_location[1] !=1:12 king_location[1] -=113 stone_location[1] -=114 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))15 else:16 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))17 else:18 king_location[1] -=119 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))20 else: 21 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))22 23 24 elif moving == 'T':25 if king_location[1] != 8:26 if ((king_location[1]+1) == (stone_location[1])) & ((king_location[0]) == (stone_location[0])):27 if stone_location[1] !=8:28 king_location[1] +=129 stone_location[1] +=130 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))31 else:32 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))33 34 else:35 king_location[1] +=136 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))37 else: 38 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))39 elif moving == 'L':40 if king_location[0] != 'A':41 if (chr(ord(king_location[0])-1) == (stone_location[0])) & ((king_location[1]) == (stone_location[1])):42 if stone_location[0] !='A':43 king_location[0] = chr(ord(king_location[0])-1)44 stone_location[0] = chr(ord(king_location[0])-1)45 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))46 else:47 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))48 else:49 king_location[0] = chr(ord(king_location[0])-1)50 return ''.join(map(str,king_location)), ''.join(map(str,stone_location)) 51 else: 52 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))53 54 elif moving == 'R':55 if king_location[0] != 'H':56 if (chr(ord(king_location[0])+1) == (stone_location[0])) & ((king_location[1]) == (stone_location[1])):57 if stone_location[0] !='H':58 king_location[0] = chr(ord(king_location[0])+1)59 stone_location[0] = chr(ord(king_location[0])+1)60 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))61 else:62 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))63 else:64 king_location[0] = chr(ord(king_location[0])+1)65 return ''.join(map(str,king_location)), ''.join(map(str,stone_location)) 66 else: 67 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))68 69 70 elif moving == 'RT':71 if (king_location[0] != 'H')&(king_location[1] != 8):72 if (chr(ord(king_location[0])+1) == (stone_location[0])) & ((king_location[1]+1) == (stone_location[1])):73 if (stone_location[0] != 'H')&(stone_location[1] != 8):74 king_location[0] = chr(ord(king_location[0])+1)75 king_location[1]+=176 77 stone_location[0] = chr(ord(king_location[0])+1)78 stone_location[1]+=179 80 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))81 82 else:83 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))84 85 else:86 king_location[0] = chr(ord(king_location[0])+1)87 king_location[1]+=188 return ''.join(map(str,king_location)), ''.join(map(str,stone_location)) 89 90 else: 91 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))92 93 elif moving == 'LT':94 if (king_location[0] != 'A')&(king_location[1] != 8):95 if (chr(ord(king_location[0])-1) == (stone_location[0])) & ((king_location[1]+1) == (stone_location[1])):96 if (stone_location[0] != 'A')&(stone_location[1] != 8):97 king_location[0] = chr(ord(king_location[0])-1)98 king_location[1]+=199 100 stone_location[0] = chr(ord(king_location[0])-1)101 stone_location[1]+=1102 103 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))104 105 else:106 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))107 108 else:109 king_location[0] = chr(ord(king_location[0])-1)110 king_location[1]+=1111 return ''.join(map(str,king_location)), ''.join(map(str,stone_location)) 112 113 else: 114 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))115 116 elif moving == 'LB':117 if (king_location[0] != 'A')&(king_location[1] != 1):118 if (chr(ord(king_location[0])-1) == (stone_location[0])) & ((king_location[1]-1) == (stone_location[1])):119 if (stone_location[0] != 'A')&(stone_location[1] != 1):120 king_location[0] = chr(ord(king_location[0])-1)121 king_location[1]-=1122 123 stone_location[0] = chr(ord(king_location[0])-1)124 stone_location[1]-=1125 126 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))127 128 else:129 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))130 131 else:132 king_location[0] = chr(ord(king_location[0])-1)133 king_location[1]-=1134 return ''.join(map(str,king_location)), ''.join(map(str,stone_location)) 135 136 else: 137 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))138 139 140 elif moving == 'RB':141 if (king_location[0] != 'H')&(king_location[1] != 1):142 if (chr(ord(king_location[0])+1) == (stone_location[0])) & ((king_location[1]-1) == (stone_location[1])):143 if (stone_location[0] != 'A')&(stone_location[1] != 1):144 king_location[0] = chr(ord(king_location[0])+1)145 king_location[1]-=1146 147 stone_location[0] = chr(ord(king_location[0])+1)148 stone_location[1]-=1149 150 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))151 152 else:153 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))154 155 else:156 king_location[0] = chr(ord(king_location[0])+1)157 king_location[1]-=1158 return ''.join(map(str,king_location)), ''.join(map(str,stone_location)) 159 160 else: 161 return ''.join(map(str,king_location)), ''.join(map(str,stone_location))162 163 164 165 166king_location, stone_location, move_num = input().split(' ')167move_num = int(move_num)168for i in range(move_num):169 tmp = input()170 king_location, stone_location = move(tmp,king_location,stone_location)171 172print(king_location)...
geolocation-redux.spec.js
Source:geolocation-redux.spec.js
1import reducer, * as redux from "./geolocation-redux";2const { INITIAL_STATE } = redux;3describe("geolocation redux", () => {4 describe("reducers", () => {5 describe("isFetchingLocation", () => {6 it("should handle initial state", () => {7 const { isFetchingLocation } = reducer(undefined, undefined);8 expect(isFetchingLocation).toEqual(INITIAL_STATE.isFetchingLocation);9 });10 it("should handle unknown action types", () => {11 const { isFetchingLocation } = reducer(INITIAL_STATE, { type: "UNKNOWN" });12 expect(isFetchingLocation).toEqual(INITIAL_STATE.isFetchingLocation);13 });14 it(`${redux.FETCH_GEO_LOCATION_REQUEST} action type should set isFetchingLocation to true`, () => {15 const state = { ...INITIAL_STATE, isFetchingLocation: false };16 const { isFetchingLocation } = reducer(state, {17 type: redux.FETCH_GEO_LOCATION_REQUEST,18 });19 expect(isFetchingLocation).toEqual(true);20 });21 it(`${redux.FETCH_GEO_LOCATION_SUCCESS} action type should set isFetchingLocation to false`, () => {22 const state = { ...INITIAL_STATE, isFetchingLocation: true };23 const { isFetchingLocation } = reducer(state, {24 type: redux.FETCH_GEO_LOCATION_SUCCESS,25 payload: {26 lat: "234",27 lng: "121",28 },29 });30 expect(isFetchingLocation).toEqual(false);31 });32 it(`${redux.FETCH_GEO_LOCATION_FAILURE} action type should set isFetchingLocation to false`, () => {33 const state = { ...INITIAL_STATE, isFetchingLocation: true };34 const { isFetchingLocation } = reducer(state, {35 type: redux.FETCH_GEO_LOCATION_FAILURE,36 error: "error",37 });38 expect(isFetchingLocation).toEqual(false);39 });40 });41 describe("hasFetchedLocation", () => {42 it("should handle initial state", () => {43 const { hasFetchedLocation } = reducer(undefined, undefined);44 expect(hasFetchedLocation).toEqual(INITIAL_STATE.hasFetchedLocation);45 });46 it("should handle unknown action types", () => {47 const { hasFetchedLocation } = reducer(INITIAL_STATE, { type: "UNKNOWN" });48 expect(hasFetchedLocation).toEqual(INITIAL_STATE.hasFetchedLocation);49 });50 it(`${redux.FETCH_GEO_LOCATION_REQUEST} action type should set hasFetchedLocation to null`, () => {51 const state = { ...INITIAL_STATE, hasFetchedLocation: false };52 const { hasFetchedLocation } = reducer(state, {53 type: redux.FETCH_GEO_LOCATION_REQUEST,54 });55 expect(hasFetchedLocation).toEqual(null);56 });57 it(`${redux.FETCH_GEO_LOCATION_SUCCESS} action type should set hasFetchedLocation to true`, () => {58 const state = { ...INITIAL_STATE, hasFetchedLocation: true };59 const { hasFetchedLocation } = reducer(state, {60 type: redux.FETCH_GEO_LOCATION_SUCCESS,61 payload: {62 lat: "234",63 lng: "121",64 },65 });66 expect(hasFetchedLocation).toEqual(true);67 });68 it(`${redux.FETCH_GEO_LOCATION_FAILURE} action type should set isFetchingLocation to false`, () => {69 const state = { ...INITIAL_STATE, isFetchingLocation: true };70 const { isFetchingLocation } = reducer(state, {71 type: redux.FETCH_GEO_LOCATION_FAILURE,72 error: "error",73 });74 expect(isFetchingLocation).toEqual(false);75 });76 });77 describe("usersLocation", () => {78 it("should handle initial state", () => {79 const { usersLocation } = reducer(undefined, undefined);80 expect(usersLocation).toEqual(INITIAL_STATE.usersLocation);81 });82 it("should handle unknown action types", () => {83 const { usersLocation } = reducer(INITIAL_STATE, { type: "UNKNOWN" });84 expect(usersLocation).toEqual(INITIAL_STATE.usersLocation);85 });86 it(`${redux.FETCH_GEO_LOCATION_REQUEST} action type should set usersLocation to empty obj`, () => {87 const state = { ...INITIAL_STATE, usersLocation: [] };88 const { usersLocation } = reducer(state, {89 type: redux.FETCH_GEO_LOCATION_REQUEST,90 });91 expect(usersLocation).toEqual({});92 });93 it(`${redux.FETCH_GEO_LOCATION_SUCCESS} action type should set usersLocation to payload`, () => {94 const state = { ...INITIAL_STATE, usersLocation: true };95 const { usersLocation } = reducer(state, {96 type: redux.FETCH_GEO_LOCATION_SUCCESS,97 payload: {98 lat: "234",99 lng: "121",100 },101 });102 expect(usersLocation).toEqual({ lat: "234", lng: "121" });103 });104 it(`${redux.FETCH_GEO_LOCATION_FAILURE} action type should set usersLocation to empty obj`, () => {105 const state = { ...INITIAL_STATE, usersLocation: true };106 const { usersLocation } = reducer(state, {107 type: redux.FETCH_GEO_LOCATION_FAILURE,108 error: "error",109 });110 expect(usersLocation).toEqual({});111 });112 });113 describe("error", () => {114 it("should handle initial state", () => {115 const { error } = reducer(undefined, undefined);116 expect(error).toEqual(INITIAL_STATE.error);117 });118 it("should handle unknown action types", () => {119 const { error } = reducer(INITIAL_STATE, { type: "UNKNOWN" });120 expect(error).toEqual(INITIAL_STATE.error);121 });122 it(`${redux.FETCH_GEO_LOCATION_REQUEST} action type should set error to null`, () => {123 const state = { ...INITIAL_STATE, error: [] };124 const { error } = reducer(state, {125 type: redux.FETCH_GEO_LOCATION_REQUEST,126 });127 expect(error).toEqual(null);128 });129 it(`${redux.FETCH_GEO_LOCATION_SUCCESS} action type should set error to null`, () => {130 const state = { ...INITIAL_STATE, error: true };131 const { error } = reducer(state, {132 type: redux.FETCH_GEO_LOCATION_SUCCESS,133 payload: {134 latitude: "234",135 longitude: "121",136 },137 });138 expect(error).toEqual(null);139 });140 it(`${redux.FETCH_GEO_LOCATION_FAILURE} action type should set error to payload`, () => {141 const state = { ...INITIAL_STATE, error: true };142 const { error } = reducer(state, {143 type: redux.FETCH_GEO_LOCATION_FAILURE,144 error: "error",145 });146 expect(error).toEqual("error");147 });148 });149 });150 describe("action creators", () => {151 describe("fetchGeoLocation", () => {152 it(`should return action type ${redux.FETCH_GEO_LOCATION} with payload`, () => {153 expect(redux.fetchGeoLocation()).toEqual({154 type: redux.FETCH_GEO_LOCATION,155 });156 });157 });158 });...
ntriples.js
Source:ntriples.js
1/**********************************************************2* This script provides syntax highlighting support for 3* the Ntriples format.4* Ntriples format specification: 5* http://www.w3.org/TR/rdf-testcases/#ntriples6***********************************************************/7/* 8 The following expression defines the defined ASF grammar transitions.9 pre_subject ->10 {11 ( writing_subject_uri | writing_bnode_uri )12 -> pre_predicate 13 -> writing_predicate_uri 14 -> pre_object 15 -> writing_object_uri | writing_object_bnode | 16 ( 17 writing_object_literal 18 -> writing_literal_lang | writing_literal_type19 )20 -> post_object21 -> BEGIN22 } otherwise {23 -> ERROR24 }25*/26CodeMirror.defineMode("ntriples", function() { 27 var Location = {28 PRE_SUBJECT : 0,29 WRITING_SUB_URI : 1,30 WRITING_BNODE_URI : 2,31 PRE_PRED : 3,32 WRITING_PRED_URI : 4,33 PRE_OBJ : 5,34 WRITING_OBJ_URI : 6,35 WRITING_OBJ_BNODE : 7,36 WRITING_OBJ_LITERAL : 8,37 WRITING_LIT_LANG : 9,38 WRITING_LIT_TYPE : 10,39 POST_OBJ : 11,40 ERROR : 1241 };42 function transitState(currState, c) {43 var currLocation = currState.location;44 var ret;45 46 // Opening.47 if (currLocation == Location.PRE_SUBJECT && c == '<') ret = Location.WRITING_SUB_URI;48 else if(currLocation == Location.PRE_SUBJECT && c == '_') ret = Location.WRITING_BNODE_URI;49 else if(currLocation == Location.PRE_PRED && c == '<') ret = Location.WRITING_PRED_URI;50 else if(currLocation == Location.PRE_OBJ && c == '<') ret = Location.WRITING_OBJ_URI;51 else if(currLocation == Location.PRE_OBJ && c == '_') ret = Location.WRITING_OBJ_BNODE;52 else if(currLocation == Location.PRE_OBJ && c == '"') ret = Location.WRITING_OBJ_LITERAL;53 54 // Closing.55 else if(currLocation == Location.WRITING_SUB_URI && c == '>') ret = Location.PRE_PRED;56 else if(currLocation == Location.WRITING_BNODE_URI && c == ' ') ret = Location.PRE_PRED;57 else if(currLocation == Location.WRITING_PRED_URI && c == '>') ret = Location.PRE_OBJ;58 else if(currLocation == Location.WRITING_OBJ_URI && c == '>') ret = Location.POST_OBJ;59 else if(currLocation == Location.WRITING_OBJ_BNODE && c == ' ') ret = Location.POST_OBJ;60 else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '"') ret = Location.POST_OBJ;61 else if(currLocation == Location.WRITING_LIT_LANG && c == ' ') ret = Location.POST_OBJ;62 else if(currLocation == Location.WRITING_LIT_TYPE && c == '>') ret = Location.POST_OBJ;63 64 // Closing typed and language literal.65 else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '@') ret = Location.WRITING_LIT_LANG;66 else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '^') ret = Location.WRITING_LIT_TYPE;67 // Spaces.68 else if( c == ' ' && 69 (70 currLocation == Location.PRE_SUBJECT || 71 currLocation == Location.PRE_PRED || 72 currLocation == Location.PRE_OBJ || 73 currLocation == Location.POST_OBJ74 )75 ) ret = currLocation;76 77 // Reset.78 else if(currLocation == Location.POST_OBJ && c == '.') ret = Location.PRE_SUBJECT; 79 80 // Error81 else ret = Location.ERROR;82 83 currState.location=ret;84 }85 return {86 startState: function() {87 return { 88 location : Location.PRE_SUBJECT,89 uris : [],90 anchors : [],91 bnodes : [],92 langs : [],93 types : []94 };95 },96 token: function(stream, state) {97 var ch = stream.next();98 if(ch == '<') {99 transitState(state, ch);100 var parsedURI = '';101 stream.eatWhile( function(c) { if( c != '#' && c != '>' ) { parsedURI += c; return true; } return false;} );102 state.uris.push(parsedURI);103 if( stream.match('#', false) ) return 'variable';104 stream.next();105 transitState(state, '>');106 return 'variable';107 }108 if(ch == '#') {109 var parsedAnchor = '';110 stream.eatWhile(function(c) { if(c != '>' && c != ' ') { parsedAnchor+= c; return true; } return false;});111 state.anchors.push(parsedAnchor);112 return 'variable-2';113 }114 if(ch == '>') {115 transitState(state, '>');116 return 'variable';117 }118 if(ch == '_') {119 transitState(state, ch);120 var parsedBNode = '';121 stream.eatWhile(function(c) { if( c != ' ' ) { parsedBNode += c; return true; } return false;});122 state.bnodes.push(parsedBNode);123 stream.next();124 transitState(state, ' ');125 return 'builtin';126 }127 if(ch == '"') {128 transitState(state, ch);129 stream.eatWhile( function(c) { return c != '"'; } );130 stream.next();131 if( stream.peek() != '@' && stream.peek() != '^' ) {132 transitState(state, '"');133 }134 return 'string';135 }136 if( ch == '@' ) {137 transitState(state, '@');138 var parsedLang = '';139 stream.eatWhile(function(c) { if( c != ' ' ) { parsedLang += c; return true; } return false;});140 state.langs.push(parsedLang);141 stream.next();142 transitState(state, ' ');143 return 'string-2';144 }145 if( ch == '^' ) {146 stream.next();147 transitState(state, '^');148 var parsedType = '';149 stream.eatWhile(function(c) { if( c != '>' ) { parsedType += c; return true; } return false;} );150 state.types.push(parsedType);151 stream.next();152 transitState(state, '>');153 return 'variable';154 }155 if( ch == ' ' ) {156 transitState(state, ch);157 }158 if( ch == '.' ) {159 transitState(state, ch);160 }161 }162 };163});...
index.js
Source:index.js
1/* This Source Code Form is subject to the terms of the Mozilla Public2 * License, v. 2.0. If a copy of the MPL was not distributed with this3 * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */4// @flow5import {6 getBreakpoint,7 getSource,8 getSourceActorsForSource,9} from "../../selectors";10import { isGenerated } from "../source";11import { sortSelectedLocations } from "../location";12import assert from "../assert";13import { features } from "../prefs";14export * from "./astBreakpointLocation";15export * from "./breakpointPositions";16import type {17 Source,18 SourceActor,19 SourceLocation,20 SourceActorLocation,21 PendingLocation,22 Breakpoint,23 BreakpointLocation,24 PendingBreakpoint,25} from "../../types";26import type { State } from "../../reducers/types";27// Return the first argument that is a string, or null if nothing is a28// string.29export function firstString(...args: string[]): ?string {30 for (const arg of args) {31 if (typeof arg === "string") {32 return arg;33 }34 }35 return null;36}37// The ID for a Breakpoint is derived from its location in its Source.38export function makeBreakpointId(location: SourceLocation): string {39 const { sourceId, line, column } = location;40 const columnString = column || "";41 return `${sourceId}:${line}:${columnString}`;42}43export function getLocationWithoutColumn(location: SourceLocation): string {44 const { sourceId, line } = location;45 return `${sourceId}:${line}`;46}47type AnySourceLocation = SourceLocation | PendingLocation;48export function makePendingLocationId(location: AnySourceLocation): string {49 assertPendingLocation(location);50 const { sourceUrl, line, column } = location;51 const sourceUrlString = sourceUrl || "";52 const columnString = column || "";53 return `${sourceUrlString}:${line}:${columnString}`;54}55export function makeBreakpointLocation(56 state: State,57 location: SourceLocation58): BreakpointLocation {59 const source = getSource(state, location.sourceId);60 if (!source) {61 throw new Error("no source");62 }63 const breakpointLocation: any = {64 line: location.line,65 column: location.column,66 };67 if (source.url) {68 breakpointLocation.sourceUrl = source.url;69 } else {70 breakpointLocation.sourceId = getSourceActorsForSource(71 state,72 source.id73 )[0].id;74 }75 return breakpointLocation;76}77export function makeSourceActorLocation(78 sourceActor: SourceActor,79 location: SourceLocation80) {81 return {82 sourceActor,83 line: location.line,84 column: location.column,85 };86}87// The ID for a BreakpointActor is derived from its location in its SourceActor.88export function makeBreakpointActorId(location: SourceActorLocation): string {89 const { sourceActor, line, column } = location;90 return `${sourceActor}:${line}:${column || ""}`;91}92export function assertBreakpoint(breakpoint: Breakpoint): void {93 assertLocation(breakpoint.location);94 assertLocation(breakpoint.generatedLocation);95}96export function assertPendingBreakpoint(97 pendingBreakpoint: PendingBreakpoint98): void {99 assertPendingLocation(pendingBreakpoint.location);100 assertPendingLocation(pendingBreakpoint.generatedLocation);101}102export function assertLocation(location: SourceLocation): void {103 assertPendingLocation(location);104 const { sourceId } = location;105 assert(!!sourceId, "location must have a source id");106}107export function assertPendingLocation(location: PendingLocation): void {108 assert(!!location, "location must exist");109 const { sourceUrl } = location;110 // sourceUrl is null when the source does not have a url111 assert(sourceUrl !== undefined, "location must have a source url");112 assert(location.hasOwnProperty("line"), "location must have a line");113 assert(114 location.hasOwnProperty("column") != null,115 "location must have a column"116 );117}118// syncing119export function breakpointAtLocation(120 breakpoints: Breakpoint[],121 { line, column }: SourceLocation122): ?Breakpoint {123 return breakpoints.find(breakpoint => {124 const sameLine = breakpoint.location.line === line;125 if (!sameLine) {126 return false;127 }128 // NOTE: when column breakpoints are disabled we want to find129 // the first breakpoint130 if (!features.columnBreakpoints) {131 return true;132 }133 return breakpoint.location.column === column;134 });135}136export function breakpointExists(137 state: State,138 location: SourceLocation139): boolean {140 const currentBp = getBreakpoint(state, location);141 return !!currentBp && !currentBp.disabled;142}143export function createXHRBreakpoint(144 path: string,145 method: string,146 overrides?: Object = {}147) {148 const properties = {149 path,150 method,151 disabled: false,152 loading: false,153 text: L10N.getFormatStr("xhrBreakpoints.item.label", path),154 };155 return { ...properties, ...overrides };156}157function createPendingLocation(location: PendingLocation) {158 const { sourceUrl, line, column } = location;159 return { sourceUrl, line, column };160}161export function createPendingBreakpoint(bp: Breakpoint) {162 const pendingLocation = createPendingLocation(bp.location);163 const pendingGeneratedLocation = createPendingLocation(bp.generatedLocation);164 assertPendingLocation(pendingLocation);165 return {166 options: bp.options,167 disabled: bp.disabled,168 location: pendingLocation,169 astLocation: bp.astLocation,170 generatedLocation: pendingGeneratedLocation,171 };172}173export function getSelectedText(174 breakpoint: Breakpoint,175 selectedSource: ?Source176): string {177 return !!selectedSource && isGenerated(selectedSource)178 ? breakpoint.text179 : breakpoint.originalText;180}181export function sortSelectedBreakpoints(182 breakpoints: Array<Breakpoint>,183 selectedSource: ?Source184): Array<Breakpoint> {185 return sortSelectedLocations(breakpoints, selectedSource);...
Using AI Code Generation
1describe('My First Test', () => {2 it('Does not do much!', () => {3 expect(true).to.equal(true)4 })5 })6 describe('My First Test', () => {7 it('Does not do much!', () => {8 cy.contains('type').click()9 cy.url().should('include', '/commands/actions')10 cy.get('.action-email')11 .type('fake@email')12 .should('have.value', 'fake@email')13 })14 })15 describe('My First Test', () => {16 it('clicks the link "type"', () => {17 cy.contains('type').click()18 cy.url().should('include', '/commands/actions')19 })20 })21 describe('My First Test', () => {22 it('Gets, types and asserts', () => {23 cy.pause()24 cy.contains('type').click()25 cy.url().should('include', '/commands/actions')26 cy.get('.action-email')27 .type('fake@email')28 .should('have.value', 'fake@email')29 })30 })31 describe('My First Test', () => {32 it('Gets, types and asserts', () => {33 cy.pause()34 cy.contains('type').click()35 cy.url().should('include', '/commands/actions')36 cy.get('.action-email')37 .type('fake@email')38 .should('have.value', 'fake
Using AI Code Generation
1describe('Location', function() {2 it('Get Current Location', function() {3 cy.location().should((loc) => {4 expect(loc.hash).to.be.empty5 expect(loc.host).to.eq('example.cypress.io')6 expect(loc.hostname).to.eq('example.cypress.io')7 expect(loc.pathname).to.eq('/commands/location')8 expect(loc.port).to.be.empty9 expect(loc.protocol).to.eq('https:')10 expect(loc.search).to.be.empty11 })12 })13})14describe('Location', function() {15 it('Get Current Location', function() {16 cy.location('href').should('include', 'commands/location')17 })18})19describe('Location', function() {20 it('Get Current Location', function() {21 cy.location('hash').should('be.empty')22 })23})24describe('Location', function() {25 it('Get Current Location', function() {26 cy.location('host').should('eq', 'example.cypress.io')27 })28})29describe('Location', function() {30 it('Get Current Location', function() {31 cy.location('hostname').should('eq', 'example.cypress.io')32 })33})34describe('Location', function() {35 it('Get Current Location', function() {36 })37})38describe('Location', function() {39 it('Get
Using AI Code Generation
1describe('Test Cypress', function(){2 it('Test Case', function(){3 cy.get('.search-keyword').type('ca')4 cy.wait(2000)5 cy.get('.products').as('productLocator')6 cy.get('@productLocator').find('.product').should('have.length', 4)7 cy.get('@productLocator').find('.product').eq(2).contains('ADD TO CART').click()8 cy.get('@productLocator').find('.product').each(($el, index, $list) => {9 const textVeg = $el.find('h4.product-name').text()10 if(textVeg.includes('Cashews')){11 $el.find('button').click()12 }13 })14 cy.get('.cart-icon > img').click()15 cy.contains('PROCEED TO CHECKOUT').click()16 cy.contains('Place Order').click()17 })18})
Using AI Code Generation
1describe('Test', () => {2 it('Visit the App', () => {3 cy.location().should((loc) => {4 expect(loc.host).to.eq('localhost:3000')5 expect(loc.protocol).to.eq('http:')6 expect(loc.port).to.eq('3000')7 expect(loc.pathname).to.eq('/')8 })9 })10 })
Using AI Code Generation
1describe('Test', () => {2 it('should load page', () => {3 })4 it('should get hostname', () => {5 cy.location('hostname').should('include', 'example.cypress.io')6 })7 it('should get protocol', () => {8 cy.location('protocol').should('eq', 'https:')9 })10 it('should get port', () => {11 cy.location('port').should('eq', '443')12 })13 it('should get origin', () => {14 })15 it('should get pathname', () => {16 cy.location('pathname').should('eq', '/commands/location')17 })18 it('should get search', () => {19 cy.location('search').should('eq', '')20 })21 it('should get hash', () => {22 cy.location('hash').should('eq', '')23 })24})25describe('Test', () => {26 it('should load page', () => {27 })28 it('should log', () => {29 cy.get('.action-log')30 .click()31 .should('have.class', 'active')32 })33})34describe('Test', () => {35 it('should load page', () => {36 })37 it('should log', () => {38 cy.server()39 cy.route('PUT', '/comments/*').as('updateComment')40 cy.get('.network-put').click()41 cy.wait('@updateComment')42 })43})44describe('Test', () => {45 it('should load page', () => {46 })47 it('should log', () => {48 cy.server()49 cy.route('PUT', '/comments/*').as('updateComment')50 cy.get('.network-put').click()51 cy.wait('@updateComment')52 cy.get('.network-put-comment').should('
Using AI Code Generation
1describe('Test the login page', () => {2 it('Visits the login page', () => {3 })4 it('Log in with valid credentials', () => {5 cy.get('input[name="username"]').type('username')6 cy.get('input[name="password"]').type('password')7 cy.get('button[type="submit"]').click()8 })9 it('Check that the user is on the home page', () => {10 cy.location('pathname').should('eq', '/')11 })12})
Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!