Best Python code snippet using slash
ui.py
Source:ui.py  
1"""2A Module which is responsible for the user interface3"""4from __future__ import annotations5import tkinter as tk6from tkinter.font import BOLD7from graphs import SongGraph89# Constants10BG_COLOUR = 'gray10'11WINDOW_WIDTH = 90012WINDOW_HEIGHT = 600131415class _Page:16    """ A private abstract class representing a single page in the application1718    This class is only meant to be used by the UserInterface class19    """2021    # Private Instance Attributes:22    #   - _frame: the object which the page will be displayed on23    #   - _ui: the user interface object which will be mutated by the page2425    _frame: tk.Tk26    _ui: UserInterface2728    def __init__(self, frame: tk.Tk, user_interface: UserInterface) -> None:29        """Initialize the page"""30        self._frame = frame31        self._ui = user_interface3233    def show_page(self, truth: bool) -> None:34        """Make the current page visible or invisible based on truth3536        the page is visible if and only if truth == true37        """38        raise NotImplementedError394041class UserInterface:42    """A class representing the main user interface4344    Instance Attributes:45    '   - mainframe: the main frame which all graphical elements will be displayed on46        - search_variable: the StringVar object representing the name of the song being47                           searched for48        - graph: the SongGraph which will be used to search for the songs and49                 get recommendations50        - home_page: the homepage of the user interface51        - results_page: the page which will display the results of the search52        - recommend_page: the page which is responsible for displaying the recommendations53                          for the given song and artist combination54    """55    mainframe: tk.Tk56    search_variable: tk.StringVar57    graph: SongGraph58    home_page: _HomePage59    results_page: _ResultsPage60    recommend_page: _RecommendationsPage6162    # Private Attributes:63    #   -_current_page: the current page which is being displayed64    _current_page: _Page6566    def __init__(self, root: tk.Tk, graph: SongGraph) -> None:67        """Initialize the user interface"""68        self.mainframe = root69        self.mainframe.title('Spotify Song Recommender')70        self.graph = graph7172        # Initializing the pages73        self.search_variable = tk.StringVar()74        self.home_page = _HomePage(self.mainframe, self, self.search_variable)75        self.results_page = _ResultsPage(self.mainframe, self, self.search_variable)76        self.recommend_page = _RecommendationsPage(self.mainframe, self)7778        self._current_page = self.home_page79        self._current_page.show_page(True)8081    def change_current_page(self, page: _Page) -> None:82        """Change the current page to <page> and display it"""83        self._current_page.show_page(False)84        self._current_page = page85        self._current_page.show_page(True)868788class _HomePage(_Page):89    """A class representing the Homepage of the application"""9091    # Private Instance Attributes:92    #   - _frame: the object which the page will be displayed on93    #   - _ui: the user interface object which will be mutated by the page94    #   -_search_variable: a tk.StringVar representing the name of the song95    #   -_text: a element of the page which displays the main text96    #   -_search_field: a element of the page which allows the user97    #                   to enter song names98    #   - _submit_button: a button on the page which allows the user to submit99    #                     their song name100    #   -_error_message: an error message which will be displayed when the101    #                    song is not found102103    _frame: tk.Tk104    _ui: UserInterface105    _search_variable: tk.StringVar106    _text: tk.Label107    _search_field: tk.Entry108    _submit_button: tk.Button109    _error_message: tk.Label110111    def __init__(self,112                 frame: tk.Tk,113                 user_interface: UserInterface,114                 search_variable: tk.StringVar) -> None:115        """Initialize the homepage and all it's elements"""116        _Page.__init__(self, frame, user_interface)117        self._search_variable = search_variable118119        # Page Elements120        self._text = tk.Label(self._frame,121                              text='Search for a Song!',122                              bg=BG_COLOUR,123                              fg='gray95',124                              font=('arialnarrow', 50))125126        self._submit_button = tk.Button(self._frame,127                                        text='Submit',128                                        command=self._search,129                                        font=('arialnarrow', 20),130                                        bg='forest green',131                                        fg='white')132133        self._search_field = tk.Entry(self._frame,134                                      textvariable=self._search_variable,135                                      font=('Verdana', 50),136                                      bg='gray95')137138        self._error_message = tk.Label(self._frame,139                                       text='Sorry, that song is not in our database\n Try Again',140                                       bg=BG_COLOUR,141                                       fg='Red',142                                       font=('arialnarrow', 38))143144    def _search(self) -> None:145        """Search for the song name represented by self._search_variable in the song graph146147        If the song is not in graph, display an error message148        """149        song_name = self._search_variable.get()150        artist_list = self._ui.graph.get_artists_by_song(song_name.lower())151152        if artist_list == []:153            self._text.place_forget()154            self._error_message.place(x=WINDOW_WIDTH // 2,155                                      y=WINDOW_HEIGHT // 4,156                                      anchor='center')157        else:158            self._ui.change_current_page(self._ui.results_page)159160    def show_page(self, truth: bool) -> None:161        """Make the current page visible or invisible based on truth"""162        if truth:163            self._text.place(x=(WINDOW_WIDTH) // 2, y=(WINDOW_HEIGHT) // 4, anchor='center')164165            self._search_field.place(x=WINDOW_WIDTH // 2,166                                     y=WINDOW_HEIGHT // 2,167                                     width=WINDOW_WIDTH * 0.75,168                                     height=100,169                                     anchor='center')170171            self._submit_button.place(x=WINDOW_WIDTH // 2,172                                      y=WINDOW_HEIGHT // 1.25,173                                      anchor='center',174                                      width=WINDOW_WIDTH // 4,175                                      height=100)176        else:177            self._text.place_forget()178            self._search_field.place_forget()179            self._submit_button.place_forget()180            self._error_message.place_forget()181182183class _ResultsPage(_Page):184    """A page representing the search results page in the application from the give graph185186    This page is responsible for providing a graphical interface which displays the search results187    """188    # Private Instance Attributes:189    #   - _frame: the object which the page will be displayed on190    #   - _ui: the user interface object which will be mutated by the page191    #   -_search_variable: a tk.StringVar representing the name of the song192    #   -_search_field: a element of the page which allows the user193    #                   to enter song names194    #   - _submit_button: a button on the page which allows the user to submit195    #                     their song name196    #   -_home_button: a button that allows the user to return to the homepage197    #   -_search_results: an instance of SearchResults which is responsible for displaying198    #                     all the artists which the song could be by199200    _frame: tk.Tk201    _ui: UserInterface202    _search_variable: tk.StringVar203    _search_field: tk.Entry204    _submit_button: tk.Button205    _home_button: tk.Button206    _search_results: _SearchResults207208    def __init__(self,209                 frame: tk.Tk,210                 user_interface: UserInterface,211                 search_variable: tk.StringVar) -> None:212        """Initialize the Search results page and all it's elements"""213        _Page.__init__(self, frame, user_interface)214        self._search_variable = search_variable215        self._search_results = _SearchResults(self._frame, user_interface)216217        # Page Elements218        self._search_field = tk.Entry(self._frame,219                                      textvariable=self._search_variable,220                                      font=('Verdana', 20),221                                      bg='gray95')222223        self._submit_button = tk.Button(self._frame,224                                        text='Submit',225                                        command=self._show_results,226                                        font=('arialnarrow', 15),227                                        bg='forest green',228                                        fg='white')229230        self._home_button = tk.Button(self._frame,231                                      text='Home',232                                      command=lambda:233                                      self._ui.change_current_page(self._ui.home_page),234                                      font=('arialnarrow', 15),235                                      bg='gray60',236                                      fg='white')237238    def _show_results(self) -> None:239        """Show the results of the search on the page240241        That is, display all the names of the artists which the song could be by242        """243        song_name = self._search_variable.get()244        artist_list = self._ui.graph.get_artists_by_song(song_name.lower())245        self._search_results.update_search(artist_list, song_name.lower())246        self._search_results.show_artists(True)247248    def show_page(self, truth: bool) -> None:249        """Make the current page visible/invisble based on truth250251        If truth is true then make the page visible, otherwise, make it invisible252        """253        if truth:254            self._search_field.place(x=WINDOW_WIDTH // 2,255                                     y=(WINDOW_HEIGHT // 15),256                                     width=WINDOW_WIDTH * 0.75,257                                     height=50, anchor='center')258259            self._submit_button.place(x=WINDOW_WIDTH - 10,260                                      y=WINDOW_HEIGHT // 15,261                                      width=WINDOW_WIDTH // 10,262                                      height=50, anchor='e',)263264            self._home_button.place(x=10,265                                    y=WINDOW_HEIGHT // 15,266                                    width=WINDOW_WIDTH // 10,267                                    height=50, anchor='w')268            self._show_results()269        else:270            self._search_field.place_forget()271            self._submit_button.place_forget()272            self._home_button.place_forget()273            self._search_results.show_artists(False)274275276class _RecommendationsPage(_Page):277    """A class respresenting a page which will display the song recommendations from graph"""278279    # Private Attributes:280    #   - _frame: the object which the page will be displayed on281    #   - _ui: the user interface object which will be mutated by the page282    #   -_home_button: a button which will change the current page to the homepage283    #   -_back_button: a button which will change the current page to the previous page284    #   -_recommendation_labels: a list of Label objects which will display the recommendations285    #                            on the page286    #   -_title: a Label object responsible for displaying the 'We Recommend Listening To' message287288    _frame: tk.Tk289    _ui: UserInterface290    _home_button: tk.Button291    _back_button: tk.Button292    _recommendation_labels: list[tk.Label]293    _title: tk.Label294295    def __init__(self, frame: tk.Tk, user_interface: UserInterface) -> None:296        """Initialize the RecommendationsPage and all it's graphical elements"""297        _Page.__init__(self, frame, user_interface)298299        # initializing the recommendations300        recommendation1 = tk.Label(self._frame,301                                   bg=BG_COLOUR,302                                   fg='white',303                                   font=('Verdana', 18),304                                   pady=10)305306        recommendation2 = tk.Label(self._frame,307                                   bg=BG_COLOUR,308                                   fg='white',309                                   font=('Verdana', 18),310                                   pady=10)311312        recommendation3 = tk.Label(self._frame,313                                   bg=BG_COLOUR,314                                   fg='white',315                                   font=('Verdana', 18),316                                   pady=10)317318        recommendation4 = tk.Label(self._frame,319                                   bg=BG_COLOUR,320                                   fg='white',321                                   font=('Verdana', 18),322                                   pady=10)323324        recommendation5 = tk.Label(self._frame,325                                   bg=BG_COLOUR,326                                   fg='white',327                                   font=('Verdana', 18),328                                   pady=10)329330        self._recommendation_labels = [recommendation1,331                                       recommendation2,332                                       recommendation3,333                                       recommendation4,334                                       recommendation5]335336        self._title = tk.Label(self._frame,337                               text='We Recommend Listening To',338                               font=('Verdana', 40, BOLD),339                               bg=BG_COLOUR,340                               fg='deep sky blue',341                               pady=30)342343        self._home_button = tk.Button(self._frame,344                                      text='Home',345                                      font=('verdana', 20),346                                      fg='white',347                                      bg='gray60',348                                      width=20,349                                      height=5,350                                      command=lambda:351                                      self._ui.change_current_page(self._ui.home_page))352353        self._back_button = tk.Button(self._frame,354                                      text='Back',355                                      font=('verdana', 20),356                                      fg='white',357                                      bg='gray60',358                                      width=20,359                                      height=5,360                                      command=lambda:361                                      self._ui.change_current_page(self._ui.results_page))362363    def update_recommended(self, song_name: str, song_artist: str) -> None:364        """Update the recommendations based on the CURRENT song name and artist"""365        recommendations_list = self._ui.graph.get_recommendations(song_name, song_artist, 5, 80)366367        recommendation_count = len(recommendations_list)368369        if recommendation_count < 5:370            rest = self._recommendation_labels[recommendation_count:]371            for text in rest:372                text.config(text='')373374        for i in range(recommendation_count):375            label = self._recommendation_labels[i]376            recommended_name, recommended_artist = recommendations_list[i]377            label.config(text=f'{recommended_name.title()} by {recommended_artist.title()}')378379    def show_page(self, truth: bool) -> None:380        """Make the current page visible/invisble based on the value of truth"""381        if truth:382            self._title.pack(side='top')383384            for recommendation in self._recommendation_labels:385                recommendation.pack(side='top')386387            self._home_button.place(x=30, y=WINDOW_HEIGHT - 130,388                                    width=200,389                                    height=100)390391            self._back_button.place(x=WINDOW_WIDTH - 230,392                                    y=WINDOW_HEIGHT - 130,393                                    width=200,394                                    height=100)395        else:396            self._title.pack_forget()397398            for recommendation in self._recommendation_labels:399                recommendation.pack_forget()400401            self._home_button.place_forget()402            self._back_button.place_forget()403404405class _SearchResults:406    """A private class respresenting the search result element of a page407408    This class is responsible for displaying the search results on the ResultsPage409    as well as the artist selection, and should only be used by ResultsPage410    """411    # Private Attributes:412    #   - _frame: the object which the page will be displayed on413    #   - _ui: the user interface object which will be mutated by the page414    #   -_artist_list: a list of all the artist which the song searched for415    #                  could be by416    #   -_artist_listbox: a Listbox object which is responsible for displaying all417    #                     the artists which the current song could be by418    #   -_artist_variable: a StringVar object which will be passed into _artist_listbox which419    #                      represents all the plausible artists the song could be by420    #   -_song_info: a Label object which will display the song name421    #   -_song_name: the name of the song being searched for422    #   -_confirm_button: a button which will allow the user to confirm their selection of artist423    #   -_error_message: an error message which will inform the user that the song being searched424    #                    for was not found425    #   -_empty_selection: an error message which will inform the user that they have not selected426    #                      an artist yet427428    _frame: tk.Tk429    _ui: UserInterface430    _artist_list: list[str]431    _artist_listbox: tk.Listbox432    _artist_variable: tk.StringVar433    _song_info: tk.Label434    _song_name: str435    _confrim_button: tk.Button436    _error_message: tk.Label437    _empty_selection: tk.Label438439    def __init__(self, frame: tk.Tk, user_interface: UserInterface) -> None:440        """Initialize the Search results and all it's graphical elements"""441        self._frame = frame442        self._ui = user_interface443        self._artist_list = []444        self._song_name = ''445        self._artist_variable = tk.StringVar()446447        self._artist_listbox = tk.Listbox(self._frame,448                                          listvariable=self._artist_variable,449                                          height=3,450                                          width=WINDOW_WIDTH - 100,451                                          bg=BG_COLOUR,452                                          fg='white',453                                          borderwidth=0,454                                          font=('arialnarrow', 40),455                                          relief='flat',456                                          selectmode='SINGLE',457                                          highlightthickness=0,458                                          activestyle='none')459        self._artist_listbox.configure(justify='center')460461        self._song_info = tk.Label(self._frame,462                                   text='',463                                   font=('arialnarrow', 20),464                                   bg=BG_COLOUR,465                                   fg='white')466467        self._error_message = tk.Label(self._frame,468                                       text="No Songs Found\nTry Again",469                                       fg='red',470                                       bg=BG_COLOUR,471                                       font=('arialnarrow', 38))472473        self._confrim_button = tk.Button(self._frame,474                                         text='Confirm Selection',475                                         bg='forest green',476                                         fg='white',477                                         font=('arial narrow', 20),478                                         command=self._update_recommendedpage)479480        self._empty_selection = tk.Label(self._frame,481                                         text='No Artist Was Selected',482                                         font=('arialnarrow', 20),483                                         bg=BG_COLOUR,484                                         fg='red')485486    def update_search(self, artist_list: list[str], song_name: str) -> None:487        """Update the old song name and artists being displayed to the CURRENT song"""488        self._empty_selection.place_forget()489        self._artist_list = artist_list490        self._song_name = song_name491        self._artist_variable.set([artist.title() for artist in artist_list])492        self._song_info.config(text=f'{song_name.title()} by')493494    def _update_recommendedpage(self) -> None:495        """Update the current page to display recommendations for the CURRENT496        song and artist497498        Display the empty_selection error message if user has no selected an artist499        """500        selection = self._artist_listbox.curselection()501        if selection != ():502            song_name = self._song_name503            artist = self._artist_list[selection[0]]504            self._ui.recommend_page.update_recommended(song_name, artist)505            self._ui.change_current_page(self._ui.recommend_page)506        else:507            self._empty_selection.place(x=WINDOW_WIDTH // 2,508                                        y=WINDOW_HEIGHT - 100,509                                        anchor='center')510511    def show_artists(self, truth: bool) -> None:512        """Display all the artists which the song could be by based on truth513514        make the SearchResults visible if and only if truth == True515        """516        if truth:517            self._artist_listbox.place(x=WINDOW_WIDTH // 2,518                                       y=WINDOW_HEIGHT // 2,519                                       anchor='center',520                                       width=WINDOW_WIDTH - 50,521                                       height=200)522523            if len(self._artist_list) == 0:524                self._song_info.place_forget()525                self._confrim_button.place_forget()526                self._error_message.place(x=WINDOW_WIDTH // 2,527                                          y=WINDOW_HEIGHT // 2,528                                          anchor='center')529            else:530                self._error_message.place_forget()531                self._song_info.place(x=WINDOW_WIDTH // 2,532                                      y=WINDOW_HEIGHT // 4,533                                      anchor='center')534535                self._confrim_button.place(x=WINDOW_WIDTH // 2,536                                           y=WINDOW_HEIGHT - 50,537                                           anchor='center')538        else:539            self._artist_listbox.place_forget()540            self._error_message.place_forget()541            self._song_info.place_forget()542            self._confrim_button.place_forget()543            self._empty_selection.place_forget()544545546if __name__ == '__main__':547    root = tk.Tk()548    root.configure(background=BG_COLOUR)549550    root.resizable(width=False, height=False)551    root.geometry(f'{WINDOW_WIDTH}x{WINDOW_HEIGHT}')552553    from graphs import build_graph554    graph = build_graph('data/data_large.csv')555556    UserInterface(root, graph)557    root.mainloop()558559    # import python_ta560    # python_ta.check_all(config={561    # 'extra-imports': [],  # the names (strs) of imported modules562    # 'allowed-io': [],     # the names (strs) of functions that call print/open/input563    # 'max-line-length': 100,564    # 'disable': ['E1136']
...test_add_error.py
Source:test_add_error.py  
...88    res = suite.run()89    result = res[suite_test]90    with open(result.get_log_path()) as f:91        lines = f.readlines()92    def _search_variable(variable_name, variable_value):93        found = False94        for line in lines:95            if variable_name in line and variable_value in line:96                found = True97                break98        assert found == log_variables, 'Variable {!r} not found in traceback log!'.format(variable_name)99    _search_variable('x_variable', 'xxx')100    _search_variable('self.property_value', 'yyy')101def test_add_error_log_traceback_variables_self_none(suite, suite_test, config_override, tmpdir):102    config_override('log.core_log_level', logbook.TRACE)103    config_override('log.traceback_variables', True)104    config_override('log.root', str(tmpdir.join('logs')))105    @suite_test.prepend_body106    def __code__():          # pylint: disable=unused-variable107        # to avoid the line itself from being detected108        self = None # pylint: disable=unused-variable109    suite_test.when_run.error()110    res = suite.run()111    result = res[suite_test]112    with open(result.get_log_path()) as f:113        lines = f.read()114    assert 'self: None' in lines...makefile.bzl
Source:makefile.bzl  
...18        x = name[i]19        if x not in _VALID_IDENTIFIERS:20            return False21    return True22def _search_variable(line):23    line = line.strip()24    if not '=' in line:25        return None26    if line.startswith('#'):27        return None28    maybe_var, maybe_value = [x.strip() for x in line.split('=', 1)]29    result = {}30    if maybe_var.endswith('+'):31        maybe_var = maybe_var[:-1].strip()32        result['concat'] = True33    else:34        result['concat'] = False35    if not _is_valid_identifier(maybe_var):36        return None37    result['name'] = maybe_var38    result['value'] = None39    stripped_value = maybe_value.strip(" \\")40    if len(stripped_value):41        result['value'] = stripped_value42    return result43def makefile_parse(contents):44    """Parse variable like entities from Makefiles.45    Returns a dictionary mapping make variables to their contents.46    """47    result = {}48    current_name = None49    current_list = None50    for line in contents.split("\n"):51        hash = line.find('#')52        if hash != -1:53            line = line[0:hash]54        if current_name:55            current_list += line.strip(" \\").split(' ')56        else:57            match = _search_variable(line)58            if match:59                current_name = match['name']60                if match['concat']:61                    current_list = result.get(current_name, [])62                else:63                    current_list = []64                if match['value']:65                    current_list += match['value'].split(' ')66        if current_name:67            if not line.endswith("\\"):68                result[current_name] = [69                    x.strip() for x in current_list70                    if x.strip() != "" and x.strip() != "$(NULL)"]71                current_name = 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!!
