Best Python code snippet using autotest_python
Pokemon Stats Downloader.py
Source:Pokemon Stats Downloader.py
1import requests,csv23link = "https://pokemon.gameinfo.io/en/pokemon/" #Link to be used to find data.4pokedex=[] #Init array of Pokémon information.56for i in range(1,721): #Loop through each Pokémon that exists.78 species_link=(link+str(i)) #Generate a link for this Pokémon species.9 f = requests.get(species_link).text #Retrieve HTML content of page.1011 try: #Some Pokémon have multiple forms (different variants of the same species). This section deals with a Pokémon that has multiple forms.12 forms=f.split('<select id="forms">')[1].split('</select>')[0].split('</option>') #Find different forms.13 del forms[-1] #Remove irrelevant data.14 for x in range(0,len(forms)): #Cycle through different forms15 forms[x]=forms[x].split(">")[1].replace(" ","-")16 if "Shadow" in forms: #Remove Shadow form as it is fundamentally identical to the default form.17 forms.remove("Shadow")18 if "Purified" in forms: #Remove Purified form as it is fundamentally identical to the default form.19 forms.remove("Purified")20 except Exception as e: #If no forms can be found.21 forms=["Normal"]2223 if forms==[]: #If no forms are found.24 forms=["Normal"]25 26 for form in forms: #For each form in the list of forms.2728 form_link=(link+str(i)+'/'+form.lower()) #Generate a link for this form29 f = requests.get(form_link).text #Retrieve HTML content of page.3031 f = f.replace('Farfetch'd',"Farfetch'd") #The species known as Farfetch'd has an odd character which should be replaced for compatibility reasons.32 pokemon_name=f.split('<meta property="og:title" content="')[1].split(" (")[0] #Extract the species name.33 pokemon_image=f.split('<meta property="og:image" content="')[1].split('"')[0] #Extract the image link.34 pokemon_name=pokemon_name.replace(" - Normal","") #If the Pokémon is in its standard form, there is no need to specify this.3536 try:37 evolution=f.split("evolves into ")[1].split(".")[0] #Extract evolution information if possible.38 evolution=evolution.replace("â","-F") #Replace certain characters for compatibility reasons.39 evolution=evolution.replace("â","-M") #Replace certain characters for compatibility reasons.40 evolution=evolution.replace("(Normal)","") #If the Pokémon is in its standard form, there is no need to specify this.41 evolution=evolution.replace(" Form","") #If the Pokémon is in an alternate form, there is no need for the word "Form" at the end.42 if "- " in evolution: #Reformat alternate forms with brackets instead of hypens.43 evolution=evolution.replace("- ","(")+")"44 except:45 evolution="None"4647 pokemon_type_text=f.split('<article class="pokemon-type">')[1].split('class="large-type">')[1].splitlines() #Extract Pokémon type text.4849 pokemon_types=[] #Create list of Pokémon types.50 pokemon_type_text=pokemon_type_text[1:] #Remove irrelevant data.51 types_obtained=False #Init loop value.52 for line in pokemon_type_text: #For each line in the extracted Pokémon type text.53 if types_obtained==False and "type large" in line and "POKEMON_TYPE_" in line: #If this line is relevant to the Pokémon's typing.54 pokemon_types.append(line.split(">")[1].split("</div")[0]) #Add it to the list of types.55 else: #If this line is not relevant to the Pokémon's typing.56 types_obtained=True #End the loop.5758 move_tables=f.split('<table class="moves">') #Extract move tables.59 del move_tables[0] #Remove irrelevant data.60 move_tables[-1]=move_tables[-1].split("</table")[0] #Remove irrelevant data.61 fast_moves=[] #Initialise fast move list. 62 charged_moves=[] #Initialise charged move list.63 for move_table in move_tables: #For each move table on the page.64 moves_to_add=[] #Init list of moves.65 for z in range(0,len(move_table.splitlines())): #For each move in the table.66 if "en/move/" in move_table.splitlines()[z]:67 moves_to_add.append(move_table.splitlines()[z+1]) #Extract move table entry.68 for item in moves_to_add: #For each move in the list of move table entries.69 if "Quick move" in move_table: #If the entry is from the fast moves table.70 fast_moves.append(item.replace("\t","").replace("-"," ")) #Add the move name to the list of fast moves.71 else: #Otherwise, if it is from the charged moves table.72 charged_moves.append(item.replace("\t","").replace("-"," ")) #Add the move name to the list of charged moves.7374 f_lines=f.splitlines() #Split the HTML content into a list of lines.75 for a in range(0,len(f_lines)): #Loop through each line to find the stats.76 if '<div class="bar sta">' in f_lines[a]: #If this line features the stamina icon.77 stamina=f_lines[a+4].split(">")[1].split("<")[0] #The stamina number will be featured on the line four lines ahead, so extract it from there.78 if '<div class="bar def">' in f_lines[a]: #If this line features the defense icon.79 defense=f_lines[a+4].split(">")[1].split("<")[0] #The defense number will be featured on the line four lines ahead, so extract it from there.80 if '<div class="bar att">' in f_lines[a]: #If this line features the attack icon.81 attack=f_lines[a+4].split(">")[1].split("<")[0] #The attack number will be featured on the line four lines ahead, so extract it from there.82 83 pokemon_name=pokemon_name.replace("â","-F") #Replace certain characters for compatibility reasons.84 pokemon_name=pokemon_name.replace("â","-M") #Replace certain characters for compatibility reasons.85 pokemon_name=pokemon_name.replace("(Normal)","") #If the Pokémon is in its standard form, there is no need to specify this.86 pokemon_name=pokemon_name.replace(" Form","") #If the Pokémon is in an alternate form, there is no need for the word "Form" at the end.87 if "- " in pokemon_name: #Reformat alternate forms with brackets instead of hypens.88 pokemon_name=pokemon_name.replace("- ","(")+")"8990 number=str(i)91 print(pokemon_name)92 93 pokedex.append({"pokemon_name":pokemon_name,"pokemon_types":pokemon_types,"charged_moves":charged_moves,"fast_moves":fast_moves,"evolution":evolution,"attack":attack,"defense":defense,"stamina":stamina,"number":str(i),"pokemon_image":pokemon_image}) #Add the acquired data to the array.9495with open('Spreadsheet.csv', 'w', newline='') as csvfile: #Open a new csv spreadsheet file.96 csvwriter = csv.writer(csvfile, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL) #Initialise csv writer.97 csvwriter.writerow(["Name","Type","Charge Moves","Fast Moves","Evolution","Attack","Defense","Stamina","National Dex No","Image"]) #Write the initial title row.98 for pokemon in pokedex: #For each dictionary entry in the array.
...
cube.py
Source:cube.py
1from itertools import chain2from functools import reduce3class Cube:4 __slots__ = ['corner_permutation', 'edge_permutation', 'corner_orientation', 'edge_orientation']5 default_vals = {6 'corner_permutation': [0, 1, 2, 3, 4, 5, 6, 7],7 'corner_orientation': [0, 0, 0, 0, 0, 0, 0, 0],8 'edge_orientation': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],9 'edge_permutation': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]10 }11 def __init__(self, *args, **kwargs):12 for key, value in self.default_vals.items():13 if key in kwargs:14 value = kwargs[key]15 setattr(self, key, value.copy())16 def __str__(self):17 result = chain(*[[str(getattr(self, item)), item, '\n'] for item in self.__slots__])18 return "".join(result)19 def __hash__(self):20 return reduce(lambda x, y: x ^ y, (hash(str(getattr(self, val))) for val in self.__slots__))21 def solved(self):22 return False not in [getattr(self, val) == self.default_vals[val] for val in self.__slots__]23 def move(self, move_string):24 return self.perform_move_old(nr=int(move_string[1]),25 move_table=self.move_tables[move_string[0].lower()])26 move_tables = {27 'r': [[1, 3, 7, 5], [9, 6, 10, 2], [2, 1, 2, 1], [0, 0, 0, 0]],28 'l': [[0, 4, 6, 2], [8, 0, 11, 4], [2, 1, 2, 1], [0, 0, 0, 0]],29 'u': [[1, 5, 4, 0], [1, 2, 3, 0], [0, 0, 0, 0], [0, 0, 0, 0]],30 'd': [[3, 2, 6, 7], [5, 4, 7, 6], [0, 0, 0, 0], [0, 0, 0, 0]],31 'f': [[0, 2, 3, 1], [1, 8, 5, 9], [1, 2, 1, 2], [1, 1, 1, 1]],32 'b': [[4, 5, 7, 6], [3, 10, 7, 11], [1, 2, 1, 2], [1, 1, 1, 1]]33 }34 def perform_move_old(self, nr, move_table):35 move_cper, move_eper, move_cor, move_eor = move_table36 c, e, ct, et = move_cper, move_eper, move_cor, move_eor37 for i in range(0, nr):38 t = self.corner_permutation[c[0]]39 self.corner_permutation[c[0]] = self.corner_permutation[c[1]]40 self.corner_permutation[c[1]] = self.corner_permutation[c[2]]41 self.corner_permutation[c[2]] = self.corner_permutation[c[3]]42 self.corner_permutation[c[3]] = t43 t = self.edge_permutation[e[0]]44 self.edge_permutation[e[0]] = self.edge_permutation[e[1]]45 self.edge_permutation[e[1]] = self.edge_permutation[e[2]]46 self.edge_permutation[e[2]] = self.edge_permutation[e[3]]47 self.edge_permutation[e[3]] = t48 t = self.corner_orientation[c[0]]49 self.corner_orientation[c[0]] = ((self.corner_orientation[c[1]] + ct[0]) % 3)50 self.corner_orientation[c[1]] = ((self.corner_orientation[c[2]] + ct[1]) % 3)51 self.corner_orientation[c[2]] = ((self.corner_orientation[c[3]] + ct[2]) % 3)52 self.corner_orientation[c[3]] = ((t + ct[3]) % 3)53 t = self.edge_orientation[e[0]]54 self.edge_orientation[e[0]] = (self.edge_orientation[e[1]] + et[0]) % 255 self.edge_orientation[e[1]] = (self.edge_orientation[e[2]] + et[1]) % 256 self.edge_orientation[e[2]] = (self.edge_orientation[e[3]] + et[2]) % 257 self.edge_orientation[e[3]] = (t + et[3]) % 258 return self59 #60 # def perform_move(self, nr, move_table):61 # attrs = zip([getattr(self, item) for item in self.__slots__], move_table, [20, 20, 3, 2])62 # for i in range(0, nr):63 # for T, v, Modulo in attrs:64 # a = [v[0], v[1], v[2], v[3]] if Modulo < 5 else [0, 0, 0, 0]65 # print(a)66 # print(T)67 # print(v)68 # print((T[v[3]] + a[2]) % Modulo)69 # print((T[v[0]] + a[3]) % Modulo)70 # print()71 # T[v[0]], T[v[1]], T[v[2]], T[v[3]] = ((T[v[1]] + a[0]) % Modulo,72 # (T[v[2]] + a[1]) % Modulo,73 # (T[v[3]] + a[2]) % Modulo,74 # (T[v[0]] + a[3]) % Modulo)...
migration.py
Source:migration.py
...15 newly_arrived['location_details'] = [extract_location_details(detail, district=district) for detail in details_list]16 newly_arrived['location_details'] = newly_arrived['location_details'] + ' ' + newly_arrived['location_name'] + ' ' + 'Sweden'17 pandas_gbq.to_gbq(newly_arrived, f'crime_statistics_polisenapi.{destination_tableid}', project_id=project_id, if_exists='append')18 print(f'{newly_arrived.shape[0]} rows added to table: crime_statistics_polisenapi.{destination_tableid}')19def move_tables(project_id: str, config_source: dict=config_us, config_destination: dict=config_eu,20 table_ids:List[str]=['raw', 'cities_refined_en', 'cities_refined','dim_district' ]):21 source_dataset_id = config_source['dataset_id']22 destination_dataset_id = config_destination['dataset_id']23 for table_id in table_ids:24 df = pandas_gbq.read_gbq(25 f"""26 SELECT * 27 FROM `{project_id}.{source_dataset_id}.{table_id}`28 """)29 pandas_gbq.to_gbq(df, f'{destination_dataset_id}.{table_id}', project_id=project_id, location=config_destination['location'],30 if_exists='replace')31def main():32 bq_client = bigquery.Client()33 project_id = bq_client.project34 move_tables(project_id=project_id)35if __name__=='__main__':...
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!!