Best Python code snippet using localstack_python
match.py
Source:match.py  
...48            self.player_one.player = input("\nEnter a nickname for yourself:\n\n")49            self.player_two = Computer("The God Bot")50            print(f"\nYou're currently up against {self.player_two.player}")51            #  Ask the user if they're ready to play. They can change their settings here52            self.is_user_ready(the_choice)53            #  If the user is ready, the sequence of the game will begin in self.is_user_ready()54            #  After user enters into self.is_user_ready(), the game will need to finish before55            #  the final method in self.run_game() occurs (self.display_outro). The outro msg56            #  will display the winner of the game.57        #  Option B: Human v. Human - self.player_two is a human58        elif the_choice.lower().strip() == "no bots":59            #  Instantiate players and give nicknames to them for clarity.60            self.player_one = Human("")61            self.player_two = Human("")62            self.player_one.player = input("\nPlayer one, enter a nickname:\n\n")63            self.player_two.player = input("\nPlayer two, enter a nickname:\n\n")64            #  Ask the user if they're ready to play. They can change their settings here65            self.is_user_ready(the_choice)66            #  If the user is ready, the sequence of the game will begin in self.is_user_ready()67            #  After user enters into self.is_user_ready(), the game will need to finish before68            #  the final method in self.run_game() occurs (self.display_outro). The outro msg69            #  will display the winner of the game.70        else:71            print("\n\nSorry, that's not an option. Please choose again.")72            #  If the user chooses anything other than "bots" or "no bots", they're re-prompted.73            self.story()74    #  endregion75    #  region Is_User_Ready76    def is_user_ready(self, human_or_bot):77        setting = input("\nAre you ready to play? Enter 'y' for yes, \n"78                        "or 'n' to change the settings for the game:\n\n")79        if setting.lower().strip() == 'y':80            #  Based off of the bots or no bots choice given in self.game_mode()81            #  human_or_bot will dictate whether they go against a human or bot.82            self.bots_or_not(human_or_bot)83        elif setting.lower().strip() == 'n':84            #  Prompt the user with settings to run specific story line85            self.story()86        else:87            #  If the user inputs anything other than 'y' or 'n', re-prompt88            print("\nThat's not an option. Please try again.\n")89            self.is_user_ready(human_or_bot)90    #  endregion91    #  region Bots_Or_Not92    def bots_or_not(self, decision):93        #  The outcome of self.option_human_v_computer() will dictate the winner so94        #  that the self.display_outro will actually have a winner to display95        #  to the users. The same goes for self.option_human_v_human().96        if decision.lower() == "bots":97            self.option_human_v_computer()98        elif decision.lower() == "no bots":99            self.option_human_v_human()100    #  endregion101    #  region Option_Human_V_Computer102    def option_human_v_computer(self):103        #  The human will go up against the computer...literally1984_bot.py
Source:literally1984_bot.py  
...50        self.users = dict()51        self.cooldown = cooldown52    def reset(self):53        self.users.clear()54    def is_user_ready(self, name):55        # remove if cooldown has expired56        curr_time = time.time()57        to_del = []58        for user, prev_time in self.users.items():59            if curr_time - prev_time >= self.cooldown:60                to_del.append(user)61        for user in to_del:62            del self.users[user]63        if name in self.users:64            return False65        self.users[name] = curr_time66        return True67def requested_quote(body, command):68    return body[0] == '!' and len(body) >= len(command) and body[:len(command)] == command69def requested_reply(body, trigger):70    return len(body) >= len(trigger) and trigger in body.lower()71class Bot:72    def __init__(self):73        self.qg = QuoteGen(QUOTE_FILENAME)74        self.uc = UserCooldown(COOLDOWN)75    def run(self):76        # make the reddit instance77        reddit = praw.Reddit("Literally1984_bot", config_interpolation="basic")78        # build subreddits79        subreddit_string = reddit.user.me().subreddit.display_name80        if len(ACTIVE_SUBREDDITS):81            subreddit_string += '+' + '+'.join(ACTIVE_SUBREDDITS)82        subreddits = reddit.subreddit(subreddit_string)83        # poll subreddits84        comments_count = 085        logging.info('Polling /r/' + subreddit_string)86        # reset cooldowns87        self.uc.reset()88        for comment in subreddits.stream.comments(pause_after=10, skip_existing=True):89            if comment == None:90                continue91            if comment.author.name in IGNORED_USERS:92                logging.info('User ignored: ' + comment.author.name)93                continue            94            if requested_quote(comment.body, QUOTE_COMMAND):95                if not self.uc.is_user_ready(comment.author.name):96                    logging.info('User on cooldown: ' + comment.author.name)97                    continue98                comments_count += 199                logging.info('#%s: Quote requested by u/%s in r/%s.' %100                             (str(comments_count), comment.author.name, comment.subreddit.display_name))101                quote = self.qg.get_next_quote()102                if quote and len(quote) != 0:103                    comment.reply(body = "\'" + quote + "\'")104            elif requested_reply(comment.body, SEARCH_TEXT):105                if not self.uc.is_user_ready(comment.author.name):106                    logging.info('User on cooldown: ' + comment.author.name)107                    continue108                comments_count += 1109                logging.info('#%s: Replying to u/%s in r/%s.' %110                             (str(comments_count), comment.author.name, comment.subreddit.display_name))111                comment.reply(body = ANSWER_TEXT)112def main():113    # setup logger114    logging.basicConfig(115        format='[%(asctime)s] %(levelname)-8s %(message)s', level=logging.INFO)116    bot = Bot()117    while True:118        try:119            logging.info('--- Literally 1984 bot started ---')120            bot.run()121        except Exception as e:122            logging.critical('!!Exception raised!!\n' + str(e))123            logging.info('--- Literally 1984 bot stopped ---')124            logging.info('Restarting in 30 seconds...')125            time.sleep(30)126        else:127            break128def test_quotes():129    qg = QuoteGen(QUOTE_FILENAME)130    for _ in range(10):131        print(qg.get_next_quote())132    print("---")133    for _ in range(10):134        print(qg.get_rand_quote())135def test_cooldowns():136    uc = UserCooldown(5)137    for i in range(20):138        n = random.choice(("Alice", "Bob", "Steve"))139        print(i, n, uc.is_user_ready(n))140        time.sleep(1)141if __name__ == "__main__":...views.py
Source:views.py  
1import datetime2import json3import operator4from dataclasses import dataclass5from typing import List6from django.conf import settings7from django.contrib.auth.decorators import login_required8from django.db.models import Q9from django.shortcuts import render, get_object_or_40410from django.urls import reverse11from apps.discord_login.models import DiscordGuild, DiscordUser12from ..user_profile.models import DynamicPlaylist13@dataclass14class Alert:15    message: str16    link: str = None17    css_class: str = "alert-primary"18def home(request):19    context = {}20    if request.user.is_authenticated:21        alerts = []22        if len(request.user.settings.get_enabled_tracks()) == 0:23            alerts.append(24                Alert(message="â  No tracks available for your profile, please review your playlists configuration",25                      link=reverse('user_profile:all_playlists'),26                      css_class='alert-warning'))27        for enabled_playlist in request.user.playlists.filter(enabled=True):28            deleted_or_unavailable_tracks_count = enabled_playlist.user_tracks.filter(29                Q(track_uri__deleted=True) | Q(track_uri__unavailable=True)).count()30            if deleted_or_unavailable_tracks_count:31                alerts.append(32                    Alert(33                        message=f'''â  {deleted_or_unavailable_tracks_count} tracks are unavailable or deleted from your playlist: "{enabled_playlist.title}"''',34                        link=reverse('user_profile:single_playlist', kwargs={'playlist_id': enabled_playlist.id}),35                        css_class='alert-danger'))36        context['alerts'] = alerts37    return render(request, 'core/home.html', context=context)38def about(request):39    context = {40        'version': f'v{settings.VERSION}'41    }42    return render(request, 'core/about.html', context=context)43def make_guild(guild: DiscordGuild, include_users: bool = False):44    guild_dict = {45        'name': guild.name,46        'id': str(guild.id),47        'image': guild.image,48        'default_image': guild.default_image,49        'is_ready': guild.is_ready,50        'users_ready_count': len(guild.users_ready)51    }52    if include_users:53        guild_dict["users"] = list(map(make_multiselect_user, guild.users.all()))54    return guild_dict55def make_user(discord_user: DiscordUser):56    return {57        'id': str(discord_user.id),58        'name': discord_user.username,59        'image': discord_user.image,60        'image_16': discord_user.image + '?size=16',61        'image_32': discord_user.image + '?size=32',62        'default_image': discord_user.default_image,63    }64def make_multiselect_user(discord_user: DiscordUser):65    is_user_ready = discord_user.is_ready66    multiselect_user = make_user(discord_user)67    multiselect_user['$isDisabled'] = not is_user_ready68    multiselect_user['inInitialSelection'] = is_user_ready69    return multiselect_user70def make_multiselect_guild(guild: DiscordGuild):71    return {72        'id': str(guild.id),73        'name': guild.name,74        'image': guild.image,75        'image_16': guild.image + '?size=16',76        'image_32': guild.image + '?size=32',77        'default_image': guild.default_image,78        '$isDisabled': not guild.is_ready,79    }80@login_required81def groups(request):82    user_query = Q(users__user=request.user)83    user_guilds = list(84        map(make_multiselect_guild,85            filter(lambda guild: guild.is_ready, DiscordGuild.objects.filter(user_query)))86    )87    other_guilds = list(88        map(make_multiselect_guild,89            filter(lambda guild: guild.is_ready, DiscordGuild.objects.filter(~user_query)))90    )91    get_name = operator.itemgetter('name')92    user_guilds.sort(key=get_name)93    other_guilds.sort(key=get_name)94    context = {95        'json_context': json.dumps({96            'user_guilds': user_guilds,97            'other_guilds': other_guilds,98            'create_playlist_url': reverse("core:create_dynamic_playlist")99        }),100    }101    return render(request, 'core/groups.html', context)102def subtitles(request):103    duration = datetime.timedelta(seconds=int(request.GET.get('duration')))104    ending_start_delta = duration - datetime.timedelta(seconds=15)105    ending_end_delta = duration - datetime.timedelta(seconds=5)106    ending_start = '{0:02d}:{1:02d}'.format(*divmod(ending_start_delta.seconds, 60))107    ending_end = '{0:02d}:{1:02d}'.format(*divmod(ending_end_delta.seconds, 60))108    context = {109        'ending_start': ending_start,110        'ending_end': ending_end,111        'title': request.GET.get('title'),112    }113    return render(request, 'core/subtitles.webvtt', context, content_type="text/vtt")114def get_guilds_without_duplicate_users(guilds: List[DiscordGuild]):115    # Remove users appearing in a guild from subsequent guilds116    already_appeared_users = set()117    guild_dicts = [make_guild(guild, include_users=True) for guild in guilds]118    for guild_dict in guild_dicts:119        user_ids_in_guild = set(map(lambda user: user["id"], guild_dict["users"]))120        guild_dict["users"] = list(filter(lambda user: user["id"] not in already_appeared_users, guild_dict["users"]))121        already_appeared_users.update(user_ids_in_guild)122    return guild_dicts123@login_required124def create_dynamic_playlist(request):125    selected_guilds = request.POST.get('selectedGuilds').split(',')126    guilds = [get_object_or_404(DiscordGuild, id=guild_id) for guild_id in selected_guilds]127    context = {128        'json_context': json.dumps({129            'guilds': get_guilds_without_duplicate_users(guilds),130        }),131        'title': "Create new playlist",132    }133    return render(request, 'core/create_dynamic_playlist.html', context)134# No authentication is required for watching playlists, it allows to have guests and is less cumbersome for users135def play_dynamic_playlist(request, playlist_id):136    playlist = get_object_or_404(DynamicPlaylist, id=playlist_id)137    guilds = get_guilds_without_duplicate_users(playlist.groups.all())138    active_users = list(139        map(lambda user: str(user.discord.id), playlist.users.filter(dynamicplaylistuser__is_active=True)))140    for guild in guilds:141        for multiselect_user in guild["users"]:142            multiselect_user["inInitialSelection"] = \143                multiselect_user["inInitialSelection"] and multiselect_user["id"] in active_users144    context = {145        'json_context': json.dumps({146            'guilds': guilds,147            'playlistId': playlist.id,148            'websocketProtocol': 'ws' if settings.DEBUG else 'wss',149            'isMobile': request.user_agent.is_mobile150        }),151        'title': f"ðµ {playlist.title}",152        'is_host': playlist.users.get(dynamicplaylistuser__is_author=True) == request.user153    }...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!!
