Best Python code snippet using robotframework
com_handler.py
Source:com_handler.py
1import win32com.client2import re3from typing import Set4from logger import Logger5def get_found_via_str(found_via_type, songs, release):6 found_releases: Set[str] = set([])7 result_str = ''8 for i in range(len(songs)):9 if release['release_type'] == 'single':10 if str.lower(release['release_title']).startswith(str.lower(songs[i].Title)) \11 and str.lower(release['artist']) == str.lower(songs[i].Artist.Name):12 continue13 else:14 found_releases.add(f"{songs[i].Artist.Name} - {songs[i].Title}")15 else:16 if str.lower(release['release_title']) == str.lower(songs[i].Album.Name) \17 and str.lower(release['artist']) == str.lower(songs[i].Artist.Name):18 continue19 else:20 found_releases.add(f"{songs[i].Artist.Name} - {songs[i].Album.Name}")21 if found_releases:22 result_str += f"{found_via_type} as:"23 for rel in found_releases:24 result_str += f"\n\t\t\t{rel}"25 return result_str if result_str else found_via_type26def print_songs_iterator(songs):27 print("print songs of iterator")28 while not songs.EOF:29 print(30 f"ID: {songs.Item.ID}, Artist: {songs.Item.Artist.Name}, Album: {songs.Item.Album.Name}, Track: {songs.Item.TrackOrder}, Title: {songs.Item.Title}")31 songs.next()32def print_song_list(song_list):33 print("print songs of song list")34 for i in range(song_list.Count):35 song = song_list.Item(i)36 print(37 f"ID: {song.ID}, Artist: {song.Artist.Name}, Album: {song.Album.Name}, Track: {song.TrackOrder}, Title: {song.Title}")38class ComHandler(object):39 def __init__(self, config):40 self.found_first_time = 041 self.found = 042 self.SDB = None43 self.db = None44 self.config = config45 self.logger = Logger()46 def open_com(self):47 self.SDB = win32com.client.Dispatch("SongsDB.SDBApplication")48 self.db = self.SDB.Database49 print("COM initialization successful")50 def close_com(self):51 self.SDB = None52 self.db = None53 def process_rym_list(self, parsed_list, playlist_name):54 playlist_name = f"rym-{playlist_name}"55 playlist = self.__get_playlist_by_name(self.__get_parent_playlist(), playlist_name)56 total_releases = len(parsed_list.items())57 releases_per_sub_list = self.config['releases_per_sub_list']58 start_from_entry = self.config['start_from_entry']59 self.found_first_time = 060 self.found = 061 if 0 < releases_per_sub_list < total_releases:62 sub_list_count = total_releases // releases_per_sub_list63 for i in range(sub_list_count):64 if start_from_entry > (i + 1) * releases_per_sub_list:65 continue66 list_name_begin = str(i * releases_per_sub_list + 1).zfill(len(str(total_releases)))67 list_name_end = str((i + 1) * releases_per_sub_list).zfill(len(str(total_releases)))68 sub_playlist = self.__get_playlist_by_name(playlist,69 f"{list_name_begin}-{list_name_end} ({playlist_name})")70 songs = self.__get_songs_from_rym_playlist(parsed_list, i * releases_per_sub_list + 1,71 (i + 1) * releases_per_sub_list)72 self.__write_songs_to_playlist(songs, sub_playlist)73 if total_releases % releases_per_sub_list:74 list_name_begin = str(sub_list_count * releases_per_sub_list + 1).zfill(len(str(total_releases)))75 list_name_end = str(total_releases).zfill(len(str(total_releases)))76 sub_playlist = self.__get_playlist_by_name(playlist,77 f"{list_name_begin}-{list_name_end} ({playlist_name})")78 songs = self.__get_songs_from_rym_playlist(parsed_list,79 sub_list_count * releases_per_sub_list + 1, total_releases)80 self.__write_songs_to_playlist(songs, sub_playlist)81 else:82 songs = self.__get_songs_from_rym_playlist(parsed_list, 1, total_releases)83 self.__write_songs_to_playlist(songs, playlist)84 self.logger.log(f"Found: {self.found} ({self.found_first_time} for the first time) of {total_releases}")85 self.logger.close()86 return True87 def __get_songs_from_rym_playlist(self, parsed_list, start, end):88 songs = self.SDB.NewSongList89 for i, release in list(parsed_list.items())[start - 1: end]:90 songs_release, found_via_type = self.__get_songs_from_release(release)91 if songs_release.Count > 0:92 found_via_str = get_found_via_str(found_via_type, songs_release, release)93 self.logger.log(f"Found: {i}. {release['artist']} - {release['release_title']} | "94 f"found via {found_via_str}")95 self.found += 196 if found_via.startswith('name'):97 songs_release.UpdateAll()98 self.found_first_time += 199 self.__merge_song_lists(songs, songs_release)100 else:101 self.logger.log(102 f"Not found: {i}. {release['artist']} - {release['release_title']}\n\t{release['rym_id']}: "103 f"{release['release_link']}")104 return songs105 def __write_songs_to_playlist(self, songs, playlist):106 playlist.Clear()107 playlist.AddTracks(songs)108 def __get_playlist_by_name(self, parent, name):109 return parent.CreateChildPlaylist(name)110 def __get_parent_playlist(self):111 return self.SDB.PlaylistByTitle(self.config['parent_list_name'])112 def __merge_song_lists(self, song_list, song_list_release):113 for i in range(song_list_release.Count):114 song_list.Add(song_list_release.Item(i))115 def __write_rym_to_db(self, song_list, release):116 for i in range(song_list.Count):117 if song_list.Item(i).Comment:118 song_list.Item(i).Comment += '\n'119 song_list.Item(i).Comment += f"{release['rym_id']}: {release['release_link']}"120 def __convert_to_song_list(self, songs):121 song_list = self.SDB.NewSongList122 while not songs.EOF:123 song_list.Add(songs.Item)124 songs.next()125 songs = None126 return song_list127 def __get_songs_from_release(self, release):128 rym_id = release['rym_id']129 found_via = None130 songs = self.__get_songs_by_rym_id(rym_id)131 if songs.Count:132 found_via = 'id'133 else:134 songs = self.__get_all_songs_by_string(release)135 if songs.Count:136 found_via = 'name'137 self.__write_rym_to_db(songs, release)138 return songs, found_via139 def __get_songs_by_rym_id(self, rym_id):140 songs = self.db.QuerySongs(f"Songs.Comment LIKE '%{rym_id}%'")141 return self.__order_songs(self.__convert_to_song_list(songs))142 def __get_all_songs_by_string(self, release):143 artist = release['artist']144 artist_from_link = release['artist_from_link']145 search_parameter, search_variable = self.__get_search_parameter_and_variable(release)146 if type(artist) != list:147 songs = self.db.QuerySongs(148 f"Songs.Artist LIKE '{self.__escape_string(artist)}' AND Songs.{search_parameter} "149 f"LIKE '{self.__escape_string(search_variable)}'")150 if songs.EOF and not self.config['exact_matches_only']:151 for i in range(3):152 if i == 0:153 songs = self.db.QuerySongs(154 f"Songs.Artist LIKE '%{self.__escape_string(artist)}%' AND Songs.{search_parameter} "155 f"LIKE '%{self.__escape_string(search_variable)}%'")156 if i == 1:157 if artist.lower() != artist_from_link:158 songs = self.db.QuerySongs(159 f"Songs.Artist LIKE '%{self.__escape_string(artist_from_link)}%' "160 f"AND Songs.{search_parameter} LIKE '%{self.__escape_string(search_variable)}%'")161 if i == 2:162 temp_songs = self.__get_songs_from_split_artist_string(release)163 if temp_songs:164 songs = temp_songs165 temp_songs = None166 if not songs.EOF:167 break168 else:169 for artist_i in artist:170 songs = self.db.QuerySongs(171 f"Songs.Artist LIKE '%{self.__escape_string(artist_i)}%' AND Songs.{search_parameter} "172 f"LIKE '{self.__escape_string(search_variable)}'")173 if not songs.EOF:174 break175 return self.__order_songs(self.__convert_to_song_list(songs))176 def __get_songs_from_split_artist_string(self, release):177 songs = None178 search_parameter, search_variable = self.__get_search_parameter_and_variable(release)179 artists = self.__split_string_by_delimiters(release['artist'],180 delimiters=(" / ", ";", " and ", " & ", "The ", " Group",181 " Quartet", " Quintet", " Sextet"))182 artists = list(filter(None, artists))183 if len(artists) > 1:184 for j in range(len(artists)):185 songs = self.db.QuerySongs(186 f"Songs.Artist LIKE '%{self.__escape_string(artists[j])}%' AND Songs.{search_parameter} LIKE '%{self.__escape_string(search_variable)}%'")187 if not songs.EOF:188 break189 return songs190 def __get_search_parameter_and_variable(self, release):191 release_title = release['release_title']192 if release['release_type'] == 'single':193 search_variable = release_title.split(" / ")[0]194 search_parameter = "SongTitle"195 else:196 search_variable = release_title197 search_parameter = "Album"198 return search_parameter, search_variable199 def __get_songs_by_mm_id(self, ids):200 id_string = self.__build_array_string(ids)201 return self.db.QuerySongs(f"Songs.ID IN {id_string}")202 def __order_songs(self, songs):203 song_list = []204 for i in range(songs.Count):205 song_list.append((songs.Item(i).DiscNumber, songs.Item(i).TrackOrder, i))206 song_list.sort()207 ordered_ids = [v[2] for _, v in enumerate(song_list)]208 for i in range(len(ordered_ids)):209 songs.Add(songs.Item(ordered_ids[i]))210 for i in range(len(ordered_ids)):211 songs.Delete(0)212 return songs213 def __escape_string(self, my_string):214 return my_string.replace("'", "''")215 def __build_array_string(self, elements):216 return f"({','.join([self.__escape_string(str(x)) for x in elements])})"217 def __split_string_by_delimiters(self, my_string, delimiters):218 regexPattern = '|'.join(map(re.escape, delimiters))219 return re.split(regexPattern, my_string)220if __name__ == "__main__":221 config = {222 "parent_list_name": "RYMtoMM",223 "partial_match": True,224 }225 release = {226 'artist': 'Depeche Mode',227 'release_title': 'Previously Unreleased Rehearsal Recordings',228 'rym_id': '[Album0]'229 }230 playlist_name = "2019"231 ComHandler = ComHandler(config)232 artist = "Depeche Mode"233 album = "Violator"234 rym_id = "[Album996]"235 songs, found_via = ComHandler.get_songs_from_release(release)236 # ComHandler.print_song_list(songs)237 songs = None238 print(f"found by {found_via}")239# print(ComHandler.escape_string("Let's Dance"))240# songs = ComHandler.get_songs_by_string(artist, album)241# ComHandler.print_songs(songs)242# songs = None243# 244# songs = ComHandler.get_songs_by_rym_id(rym_id)245# ComHandler.print_songs(songs)246# songs = None...
com.py
Source:com.py
...7 self.author = author8 self.description = description9 self.areas = areas10 11def search_variable(lis,name,typ,arr=False):12 variables = []13 for x in range(len(lis)):14 if (lis[x].title == name and lis[x].TYPE == typ):15 variables.append(lis[x])16 if not arr:17 if len(variables) >= 1:18 return variables[0]19 else:20 return None21 else:22 return variables23 24def separate(s):25 lis = [""]26 for x in range(len(s)):27 if (s[x] == " "):28 lis.append([""])29 else:30 lis[len(lis)-1] += s[x]31 for x in range(len(lis)):32 if (lis[x] == "" or lis[x] == " "):33 del lis[x]34 return lis35 36def svs(lis,name,typ):37 elements = []38 for x in range(len(lis)):39 if (lis[x].title == name and lis[x].TYPE == typ):40 elements.append(lis[x])41 return elements42def create_level(s,player):43 lvl = search_variable(s,"level","draw")44 data = search_variable(lvl.content,"name","dec").content45 name = ""46 for q in data:47 name += q48 data = ""49 for q in name:50 if q != "'":51 data += q52 name = data53 author = search_variable(lvl.content,"author","dec").content[0]54 description = search_variable(lvl.content,"description","dec").content[0]55 areasn = search_variable(lvl.content,"arenas","dec").content56 areas = []57 for x in range(len(areasn)):58 areas.append(search_variable(s,areasn[x],"draw"))59 interpretador = tran.inte()60 elm = []61 for x in range(len(areas)):62 players = []63 b = 164 while True:65 p = search_variable(areas[x].content,"player"+str(b),"dec")66 if (p == None):67 break68 else:69 players.append(p)70 b+=171 luces = search_variable(areas[x].content,"luz","dec",True)72 for w in range(len(luces)):73 for q in range(len(areas[x].content)):74 if areas[x].content[q].title == "luz":75 del areas[x].content[q]76 break77 elements = []78 for y in range(len(areas[x].content)):79 el = interpretador.transform(areas[x].content[y] )80 if (el != None):81 for a in range(len(el)):82 elements.append( el[a] )83 for z in range(len(players)):84 p = players[z].content85 for a in range(len(p)):...
views.py
Source:views.py
1from django.shortcuts import render2# Create your views here.3from django.utils import timezone4from django.shortcuts import render5from django.views.generic import TemplateView, ListView6from django.http import HttpResponse, HttpResponseNotFound, Http404, HttpResponseRedirect7from django.db.models import Q8from django.shortcuts import render, get_object_or_4049from django.contrib.auth import login, authenticate10from django.contrib.auth.forms import UserCreationForm11from django.utils.html import strip_tags12from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank13from django.db.models import Q14from django.core.paginator import Paginator 15import django.contrib.sessions16from qcc_project.settings import company_field_names, searchform_null17from mainsite.models import company, individual, position,company_relation18link_text = '''https://uploads-ssl.webflow.com/6101e896e784d553fe534908/css/china-nlp.webflow.9eb1fed3c.css'''19def company_detail(request, company_name):20 company_object = company.objects.get(ä¼ä¸å称__icontains=company_name)21 related_positions = position.objects.filter(position_company=company_object).all()22 company_links = company_relation.objects.filter(origin_company=company_object).all()23 company_links_target= company_relation.objects.filter(target_company=company_object).all()24 context = {25 'company_links' : company_links,26 'related_positions' : related_positions,27 'company_object' : company_object,28 'style_sheet' : link_text,29 'company_field_names' : company_field_names,30 }31 return render(request, 'company_detail.html', context)32def index_page(request):33 context = {34 'style_sheet' : link_text,35 }36 return render(request, 'index.html', context)37def company_search(request):38 if request.method == "POST":39 query_construction = company.objects.all()40 41 search_variables = ['ä¼ä¸å称__icontains', 'backend_string', 'è±æå__icontains'] 42 search_codex = {} 43 for search_variable in search_variables:44 if type(request.POST.get(search_variable)) is not None:45 if len(request.POST.get(search_variable)) != 0 and request.POST.get(search_variable) != searchform_null:46 search_codex[search_variable] = request.POST.get(search_variable) 47 for key in list(search_codex):48 query_construction = query_construction.filter(**{key: search_codex[key]})49 print("Added query constraint {} = {}".format(key, search_codex[key]))50 search_results = query_construction.all()51 52 context = {53 'style_sheet' : link_text,54 'result_item_list' : search_results,55 }...
main.py
Source:main.py
1from typing import Optional2from fastapi import FastAPI3from bs4 import BeautifulSoup4import requests5from fastapi.middleware.cors import CORSMiddleware6app = FastAPI()7origins = [8 "http://localhost",9 "http://localhost:8080",10]11app.add_middleware(12 CORSMiddleware,13 allow_origins=origins,14 allow_credentials=True,15 allow_methods=["*"],16 allow_headers=["*"],17)18@app.get("/{search_variable}")19def read_root(search_variable: str):20 headers = {21 "Access-Control-Allow-Origin": "*",22 "Access-Control-Allow-Methods": "GET",23 "Access-Control-Allow-Headers": "Content-Type",24 "Access-Control-Max-Age": "3600",25 "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0",26 }27 url = "https://www.cimri.com/" + search_variable28 req = requests.get(url, headers)29 soup = BeautifulSoup(req.content, "html.parser")30 myscdivs = ""31 if soup.find_all("div", {"class": "z7ntrt-0 cLlfW s1a29zcm-9 jvSenz"}):32 myscdivs = soup.find_all("div", {"class": "z7ntrt-0 cLlfW s1a29zcm-9 jvSenz"})33 else:34 myscdivs = soup.find_all("div", {"class": "z7ntrt-0 cfoZhx s1a29zcm-9 jvSenz"})35 title = ""36 price = ""37 products = {}38 for text in myscdivs:39 title = text.find("h3", {"class": "product-title"}).text40 price = text.find("div", {"class": "top-offers"}).text41 products.update({title: price.split("TL")[0]})42 return products43@app.get("/items/{item_id}")44def read_item(item_id: int, q: Optional[str] = None):...
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!!