Best Python code snippet using autotest_python
SISRS.py
Source:SISRS.py
1from audioop import avg2import data3import math4import random5import numpy as np6import copy7q = 54008Q = 864009Vertices, dmatrix, solutions, total_dist = None, None, None, None10s_0 = None11T_0 = 10012T_f = 113iterations = None14c = None15L_max = 1016c_avarage = 1017beta = 0.0118gamma = 0.0119def initialize(instance, iter):20 global Vertices, dmatrix, solutions, total_dist, s_0, iterations, c21 Vertices, dmatrix, solutions, total_dist = data.read_instance(instance)22 s_0 = [r[0] for r in solutions]23 iterations = iter24 c = (T_f/T_0)**(1/iterations)25def local_search(s):26 s_best = s_027 T = T_028 for f in range(iterations):29 s_ruin = Ruin(copy.deepcopy(s))30 s_new = Recreate(s_ruin)31 if s_new != -1:32 if costTotal(s_new) < costTotal(s) - T * math.log(random.uniform(0, 1)):33 s = s_new34 if costTotal(s_new) < costTotal(s_best):35 s_best = s_new36 T *= c37 return s_best, [costRoute(r) for r in s_best], costTotal(s_best)38 39def Ruin(s):40 A = [i for i in range(220)]41 route_dict = {}42 for r in s:43 for e in r:44 route_dict[e] = s.index(r)45 A.remove(e)46 l_max = min(L_max, sum(len(r) for r in s)/len(s) - sum([1 if len(r) == 0 else 0 for r in s]))47 k_max = (4*c_avarage)/(1 + l_max) - 148 k_s = math.floor(random.uniform(1, k_max + 1))49 t = None50 c_seed = None51 while t == None:52 c_seed = random.randrange(20, 220)53 for r in s:54 if c_seed in r:55 t = r[0]56 c_adj = [(e, np.where(dmatrix[c_seed] == e)[0][0]) for e in dmatrix[c_seed]]57 c_adj.sort()58 c_adj_2 = [e[1] for e in c_adj]59 R = []60 for cust in c_adj_2: 61 if not len(R) < k_s:62 break63 if cust not in A and cust > 19:64 new_t = route_dict[cust]65 if new_t not in R:66 c_t = cust67 l_max_t = min(len(s[new_t]), l_max)68 l_t = math.floor(random.uniform(1, l_max_t + 1))69 A.extend(RemoveSelected(s, new_t, l_t, c_t))70 R.append(new_t)71 return s72def Recreate(s):73 A = [i for i in range(220)]74 for r in s:75 for e in r:76 A.remove(e)77 my_sort(A)78 to_remove = []79 to_route = None80 for cust in A:81 P = None82 for t in range(20):83 for P_t in range(1, len(s[t]) + 1):84 tw = checkTimeWindows(s[t], cust, P_t)85 if tw == 1:86 break87 if tw == 0:88 if random.uniform(0, 1) < 1 - gamma:89 if P == None or costAt(s[t], cust, P_t) < costAt(s[to_route], cust, P):90 P = P_t91 to_route = t92 if P == None:93 return -194 #print('another r', s[t])95 #print('P', P_t, cust, s[to_route])96 s[to_route].insert(P, cust)97 to_remove.append(cust)98 for cust in to_remove:99 A.remove(cust)100 return s101def RemoveSelected(s, t, l_t, c_t):102 removed = []103 up = s[t].index(c_t)104 low = s[t].index(c_t)105 removed.append(s[t].pop(up))106 for i in range(l_t - 1):107 rand = random.uniform(0, 1)108 if rand > 0.5 and up + 1 < len(s[t]):109 up += 1110 removed.append(s[t].pop(up))111 elif low - 1 > 0:112 low -= 1113 removed.append(s[t].pop(low))114 return removed115def my_sort(A):116 rand = random.uniform(0, 7)117 if rand <= 4:118 random.shuffle(A)119 elif rand <= 6:120 avg_distances = {}121 for cust in A:122 distances = []123 for x in range(20):124 distances.append(dmatrix[cust][x])125 avg_distances[cust] = min(distances)126 sorted_A = dict(sorted(avg_distances.items(), key=lambda item: item[1]))127 A = [cust for cust in sorted_A]128 elif rand <= 7:129 avg_distances = {}130 for cust in A:131 distances = []132 for x in range(20):133 distances.append(dmatrix[cust][x])134 avg_distances[cust] = min(distances)135 sorted_A = dict(sorted(avg_distances.items(), key=lambda item: item[1]))136 temp = [cust for cust in sorted_A]137 A = []138 j = len(sorted_A)139 for i in range(1, len(sorted_A)):140 A.append(temp[j-i])141def costAt(r, cust, P_t):142 route = copy.copy(r)143 old_cost = costRoute(route)144 route.insert(P_t, cust)145 new_cost = costRoute(route)146 return new_cost - old_cost147# 0 -> windows OK148# 1 -> timewindow of extra customer already over149# 2 -> customer after extra customer no longer have a working time window150def checkTimeWindows(r, cust, P_t):151 start_service = {}152 start_service[r[0]] = -5400153 for i in range(1, P_t):154 customer = r[i]155 start_service[customer] = max(Vertices[customer][1],156 start_service[r[i-1]] + q + dmatrix[r[i-1]][r[i]])157 start_service[cust] = max(Vertices[cust][1],158 start_service[r[P_t-1]] + q + dmatrix[r[P_t-1]][cust])159 if start_service[cust] > Vertices[cust][2]:160 return 1161 if P_t == len(r):162 if start_service[cust] + 5400 + dmatrix[cust][r[0]] > Q:163 return 1164 return 0165 start_service[r[P_t]] = max(Vertices[r[P_t]][1],166 start_service[cust] + q + dmatrix[cust][r[P_t]])167 if start_service[r[P_t]] > Vertices[r[P_t]][2]:168 return 2169 170 for i in range(P_t + 1, len(r)):171 customer = r[i]172 start_service[customer] = max(Vertices[customer][1],173 start_service[r[i-1]] + q + dmatrix[r[i-1]][r[i]])174 175 if start_service[customer] > Vertices[customer][2]:176 return 2177 if start_service[r[len(r) - 1]] + 5400 + dmatrix[r[len(r) - 1]][r[0]] > Q:178 return 2179 return 0180def costRoute(r):181 return sum(dmatrix[r[i],r[i+1]] for i in range(max(len(r) - 1, 0))) + dmatrix[r[len(r) - 1],r[0]]182def costTotal(s):183 total = 0184 for r in s:185 total += costRoute(r)186 return total187def check_solution(s):188 start_service = {}189 total = 0190 for r in s:191 total += 1192 start_service[r[0]] = -5400193 for i in range(1, len(r)):194 total += 1195 start_service[r[i]] = max(Vertices[r[i]][1],196 start_service[r[i-1]] + q + dmatrix[r[i-1], r[i]])197 if start_service[r[len(r) - 1]] + 5400 + dmatrix[r[len(r) - 1], r[0]] > Q:198 print('faulty solution', 'end')199 #return False200 for cust in start_service:201 if cust > 19:202 if start_service[cust] > Vertices[cust][2] or start_service[cust] < Vertices[cust][1]:203 print('faulty solution', cust, start_service[cust], Vertices[cust][2], Vertices[cust][1])204 #return False205 for i in range(220):206 if i not in start_service:207 print('not everyone visited')208 if total != 220:209 print('weird total: ', total)210 211 print(costTotal(s))212 return True213'''214f = open("improvements.txt", "a")215to_write = ""216for r in s_0:217 to_write += str(r) + "\n"218f.write(to_write)219f.write(str(costTotal(s_0)))220f.close()221print('zerooooo', check_solution(s_0))222print('Total cost of old is: ', costTotal(s_0))223#print(solutions, sum(r[1] for r in solutions))224improved = local_search(s_0)225print(check_solution(improved))226if costTotal(improved) < costTotal(s_0):227 print('improvement found')228 f = open("improvements.txt", "a")229 to_write = ""230 for r in improved:231 to_write += str(r) + "\n"232 f.write(to_write)233 f.write(str( costTotal(improved)))234 f.close()235print('Total cost of improved is: ', costTotal(improved), improved, sum([sum(1 for e in r) for r in improved]))...
__init__.py
Source:__init__.py
...39 self.revision = None40 Log.Exception('Error reading bundle revision')41 42 # Attempts to start the given service, catching and logging any exceptions43 def start_service(service_name, service_class, should_start=True):44 if should_start:45 try:46 setattr(self, service_name + 'service', service_class(self))47 except:48 Core.log_exception("Error starting %s service", service_name)49 50 node = hasattr(Core.config, 'daemonized') and Core.config.daemonized51 52 # If we're on the node, add a prefix for /services too53 if node:54 Plugin.AddPrefixHandler('/services', ServiceMain, 'Services')55 else:56 Plugin.AddPrefixHandler('/player', PlayerMain, 'Player')57 58 start_service('message', messageservice.MessageService, True)59 start_service('agent', agentservice.AgentService, True)60 start_service('scanner', scannerservice.ScannerService, not node)61 start_service('bundle', bundleservice.BundleService, not node)62 start_service('help', helpservice.HelpService, not node)63 start_service('store', storeservice.StoreService, not node)64 start_service('scanner', scannerservice.ScannerService, not node)65 start_service('install', installservice.InstallService, not node)66 start_service('player', playerservice.PlayerService, not node)67 start_service('flag', flagservice.FlagService, True)68 start_service('peer', peerservice.PeerService, True)69 start_service('stream', streamservice.StreamService, not node)70 start_service('code', codeservice.CodeService, True)71 start_service('proxy', proxyservice.ProxyService, not node)72 if not node:73 self.agentservice.update_attribution_flags()74 75system_instance = None76def Start():77 global system_instance78 system_instance = System()79 Plugin.Nice(15)80def ValidatePrefs():81 if not hasattr(Core.config, 'daemonized') or not Core.config.daemonized:82 Log("Region set to %s, using region %s", Prefs['PO_RGN'], system_instance.storeservice.region)83 Log("Updating plug-ins after a prefs change")...
test_availability_zone.py
Source:test_availability_zone.py
...17CONF.import_opt('manager', 'nova.cells.opts', group='cells')18class AvailabilityZoneJsonTest(test_servers.ServersSampleBase):19 extension_name = "os-availability-zone"20 def _setup_services(self):21 self.conductor = self.start_service('conductor',22 host='conductor', manager=CONF.conductor.manager)23 self.compute = self.start_service('compute', host='compute')24 self.cert = self.start_service('cert', host='cert')25 self.consoleauth = self.start_service('consoleauth',26 host='consoleauth')27 self.network = self.start_service('network', host='network')28 self.scheduler = self.start_service('scheduler', host='scheduler')29 self.cells = self.start_service('cells', host='cells',30 manager=CONF.cells.manager)31 def test_availability_zone_list(self):32 response = self._do_get('os-availability-zone')33 self._verify_response('availability-zone-list-resp', {}, response, 200)34 def test_availability_zone_detail(self):35 response = self._do_get('os-availability-zone/detail')36 subs = self._get_regexes()37 self._verify_response('availability-zone-detail-resp', subs, response,38 200)39 def test_availability_zone_post(self):...
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!!