Best Python code snippet using avocado_python
CustomHelpCommand.py
Source:CustomHelpCommand.py
1from discord import Embed, Colour2from discord.ext.commands import HelpCommand, MissingPermissions3from esportsbot.DiscordReactableMenus.EmojiHandler import MultiEmoji4from esportsbot.DiscordReactableMenus.ReactableMenu import ReactableMenu5class CustomHelpCommand(HelpCommand):6 """7 A Custom Help Command implementation that uses reactable menus so that each Cog has its own page and improves readability8 of the help commands.9 """10 def __init__(self, **options):11 self.help_strings = options.pop("help_strings")12 super().__init__(**options)13 async def send_bot_help(self, mapping):14 """15 This function runs when the bare `help` command is run without any groups or commands specified.16 :param mapping: The mapping of Cogs -> Union [Command Groups, Commands]17 """18 embeds = []19 # Get an embed for each cog that has more than 1 field. Some cogs may have no fields if the user requesting20 # does not have permissions to use a given command. Eg: Command needs admin permissions and user is not an admin21 for cog, commands in mapping.items():22 embed = await self.get_cog_help(cog, commands)23 if len(embed.fields) > 0:24 embeds.append(embed)25 help_menu = HelpMenu(embeds=embeds)26 await help_menu.finalise_and_send(self.context.bot, self.context.channel)27 async def get_cog_help(self, cog, commands):28 """29 Gets the help embed for a given cog and its commands.30 :param cog: The cog to get the help embed of.31 :param commands: The commands and command groups in the given cog.32 :return: An embed for the cog.33 """34 embed = Embed(35 title=getattr(cog,36 "qualified_name",37 self.help_strings.get("empty_category")),38 description="â",39 colour=Colour.random()40 )41 for command in commands:42 await self.add_command_field(embed, command)43 embed.set_footer(text=self.help_strings.get("embed_footer"))44 return embed45 async def add_command_field(self, embed, command):46 """47 Adds the embed field for a given command to an embed. If the command does not pass the checks, it is not added.48 Eg: Command needs admin but user is not an admin.49 :param embed: THe embed to add the field to.50 :param command: The command to add the help field of.51 """52 if command.hidden and not self.context.author.guild_permissions.administrator:53 return54 checks = command.checks55 checks_to_add = []56 for check in checks:57 # Remove any custom checks. Checks such as admin will not be removed.58 if check.__name__ != "predicate":59 command.remove_check(check)60 checks_to_add.append(check)61 try:62 # For some reason instead of returning False, this will just raise an error if the user is not able to run63 # the command.64 await command.can_run(self.context)65 except MissingPermissions:66 return67 for check in checks_to_add:68 command.add_check(check)69 fully_qualified_name = command.name70 if command.full_parent_name:71 fully_qualified_name = f"{command.full_parent_name} {fully_qualified_name}"72 fully_qualified_name = fully_qualified_name.strip()73 # name = <prefix><fully qualified name>74 # value = Short help string \n Alias String \n Help command string75 help_dict = self.help_strings.get(fully_qualified_name.replace(" ", "_").replace("-", "_"))76 name = self.help_strings["usage_string"].format(prefix=self.clean_prefix, fqn=fully_qualified_name)77 if not help_dict:78 # If the command is missing help string definition in the user_strings file, try and default to the defined79 # help string in the command definition.80 value = ""81 if command.help:82 value += self.help_strings["command_help_short"].format(help_string=command.help) + "\n"83 else:84 value += self.help_strings["command_help_short"].format(85 help_string=self.help_strings["missing_help_string"]86 ) + "\n"87 else:88 value = self.help_strings["command_help_short"].format(help_string=help_dict["help_string"]) + "\n"89 if command.aliases:90 alias_string = str(command.aliases).replace("]", "").replace("[", "").replace("'", "")91 value += self.help_strings["command_alias"].format(aliases=alias_string) + "\n"92 value += self.help_strings["command_help"].format(prefix=self.clean_prefix, fqn=fully_qualified_name) + "\n"93 value += "â"94 embed.add_field(name=f"**{name}**", value=value, inline=False)95 async def send_command_help(self, command):96 """97 Runs when the help command is run with a parameter that is a command. This can be a subcommand of a group or a98 command that is not in a group.99 :param command: The command to get the help information of.100 """101 fully_qualified_name = command.name102 if command.full_parent_name:103 fully_qualified_name = f"{command.full_parent_name} {fully_qualified_name}"104 fully_qualified_name = fully_qualified_name.strip()105 title = self.help_strings["embed_title"].format(prefix=self.clean_prefix, fqn=fully_qualified_name)106 usage = self.help_strings["usage_string"].format(prefix=self.clean_prefix, fqn=fully_qualified_name)107 help_dict = self.help_strings.get(fully_qualified_name.replace(" ", "_").replace("-", "_"))108 if not help_dict:109 short = command.help if command.help else self.help_strings["missing_help_string"]110 long_string = command.description if command.description else ""111 usage += command.usage if command.usage else ""112 else:113 short = help_dict.get("help_string", self.help_strings["missing_help_string"])114 long_string = help_dict.get("description", "")115 usage += help_dict.get("usage", "")116 description = self.help_strings["command_description"].format(short_string=short, long_string=long_string)117 embed = Embed(title=title, description=description, colour=Colour.random())118 if help_dict and help_dict.get("readme_url"):119 embed.__setattr__("url", help_dict.get("readme_url"))120 embed.add_field(name="Usage:", value=usage, inline=False)121 embed.add_field(name="â", value=self.help_strings["command_footer"])122 embed.set_footer(text=self.help_strings["embed_footer"])123 await self.context.send(embed=embed)124 async def send_group_help(self, group):125 """126 Runs when the help command is run with a parameter that is a command group.127 :param group: The command group to send the help information about.128 """129 fully_qualified_name = group.name130 if group.full_parent_name:131 fully_qualified_name = f"{group.full_parent_name} {fully_qualified_name}"132 fully_qualified_name = fully_qualified_name.strip()133 title = self.help_strings["embed_title"].format(prefix=self.clean_prefix, fqn=fully_qualified_name)134 help_dict = self.help_strings.get(fully_qualified_name.replace(" ", "_").replace("-", "_"))135 if not help_dict:136 description = "â" if not group.help else group.help137 else:138 description = help_dict.get("help_string", "â")139 if help_dict.get('description'):140 description += f"\n\n{help_dict.get('description')}\nâ"141 else:142 description += f"\nâ"143 embed = Embed(title=title, description=description, colour=Colour.random())144 if help_dict and help_dict.get("readme_url"):145 embed.__setattr__("url", help_dict.get("readme_url"))146 for command in group.commands:147 await self.add_command_field(embed, command)148 embed.set_footer(text=self.help_strings["embed_footer"])149 await self.context.send(embed=embed)150 async def send_cog_help(self, cog):151 """152 Send the help for a given cog.153 :param cog: The cog to get the help about.154 """155 await self.context.send(embed=await self.get_cog_help(cog, cog.get_commands()))156class HelpMenu(ReactableMenu):157 """158 The Reactable Menu used to implement the custom help command.159 """160 def __init__(self, **kwargs):161 if kwargs.get("add_func") is None:162 kwargs["add_func"] = self.react_add_func163 super().__init__(**kwargs)164 self.embeds = kwargs.get("embeds", None)165 if self.embeds is None:166 raise ValueError("No embeds supplied to the help menu!")167 self.auto_enable = True168 self.show_ids = False169 self.current_index = 0170 self.max_index = len(self.embeds)171 self.add_option("â¬
", "-1")172 self.add_option("â¡", "+1")173 self.add_option("â", "exit")174 async def react_add_func(self, payload):175 """176 The function to run when the help menu is reacted to.177 :param payload: The payload information of the reaction event.178 """179 emoji_triggered = payload.emoji180 channel_id: int = payload.channel_id181 message_id: int = payload.message_id182 guild = self.message.guild183 if emoji_triggered not in self:184 channel = guild.get_channel(channel_id)185 message = await channel.fetch_message(message_id)186 await message.clear_reaction(emoji_triggered)187 return False188 formatted_emoji = MultiEmoji(emoji_triggered)189 option = self.options.get(formatted_emoji.emoji_id).get("descriptor")190 try:191 # Bit scuffed, but if the conversion to an int fails, the "exit" option was chosen and therefore just delete192 # the help menu.193 self.current_index += int(option)194 if self.current_index >= self.max_index:195 self.current_index = 0196 if self.current_index < 0:197 self.current_index = self.max_index - 1198 await self.update_message()199 channel = guild.get_channel(channel_id)200 message = await channel.fetch_message(message_id)201 await message.remove_reaction(emoji_triggered, payload.member)202 except ValueError:203 await self.message.delete()204 def generate_embed(self) -> Embed:205 """206 Generate the embed that is sent to the channel based on the current page index.207 :return: A discord Embed object.208 """...
constants.py
Source:constants.py
1# coding=utf-82# Copyright 2019 Google LLC.3# Copyright 2021 Shortest Path RL Authors.4#5# Licensed under the Apache License, Version 2.0 (the "License");6# you may not use this file except in compliance with the License.7# You may obtain a copy of the License at8#9# http://www.apache.org/licenses/LICENSE-2.010#11# Unless required by applicable law or agreed to in writing, software12# distributed under the License is distributed on an "AS IS" BASIS,13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14# See the License for the specific language governing permissions and15# limitations under the License.16"""Constants for episodic curiosity."""17from __future__ import absolute_import18from __future__ import division19from __future__ import print_function20from enum import Enum21class Level(object):22 """Represents a DMLab level, possibly with additional non-standard settings.23 Attributes:24 dmlab_level_name: Name of the DMLab level25 fully_qualified_name: Unique name used to distinguish between multiple DMLab26 levels with the same name but different settings.27 extra_env_settings: dict, additional DMLab environment settings for this28 level.29 random_maze: Whether the geometry of the maze is supposed to change when we30 change the seed.31 use_r_net_from_level: If provided, don't train a R-net for this level, but32 instead, use the trained R-net from another level33 (identified by its fully qualified name).34 include_in_paper: Whether this level is included in the paper.35 scenarios: Optional list of scenarios this level is used for.36 """37 def __init__(self,38 dmlab_level_name,39 fully_qualified_name = None,40 extra_env_settings = None,41 random_maze = False,42 use_r_net_from_level = None,43 include_in_paper = False,44 scenarios = None):45 self.dmlab_level_name = dmlab_level_name46 self.fully_qualified_name = fully_qualified_name or dmlab_level_name47 self.extra_env_settings = extra_env_settings or {}48 self.random_maze = random_maze49 self.use_r_net_from_level = use_r_net_from_level50 self.include_in_paper = include_in_paper51 self.scenarios = scenarios52 def asdict(self):53 return vars(self)54class SplitType(Enum):55 R_TRAINING = 056 POLICY_TRAINING = 357 VALIDATION = 158 TEST = 259class Const(object):60 """Constants"""61 # env62 OBSERVATION_HEIGHT = 8463 OBSERVATION_WIDTH = 8464 assert OBSERVATION_HEIGHT%4 == 065 assert OBSERVATION_WIDTH%4 == 066 OBSERVATION_CHANNELS = 367 OBSERVATION_SHAPE = (OBSERVATION_HEIGHT, OBSERVATION_WIDTH,68 OBSERVATION_CHANNELS)69 # model and training70 BATCH_SIZE = 6471 EDGE_CLASSES = 272 DUMP_AFTER_BATCHES = 10073 EDGE_MAX_EPOCHS = 15074 ADAM_PARAMS = {75 'lr': 1e-04,76 'beta_1': 0.9,77 'beta_2': 0.999,78 'epsilon': 1e-08,79 'decay': 0.080 }81 ACTION_REPEAT = 482 STORE_CHECKPOINT_EVERY_N_EPOCHS = 3083 LEVELS = [84 # Levels on which we evaluate episodic curiosity.85 # Corresponds to 'Sparse' setting in the paper86 # (arxiv.org/pdf/1810.02274.pdf).87 Level('contributed/dmlab30/explore_goal_locations_large',88 fully_qualified_name='explore_goal_locations_large',89 random_maze=True,90 include_in_paper=True,91 scenarios=['sparse', 'noreward', 'norewardnofire']),92 # WARNING!! For explore_goal_locations_large_sparse and93 # explore_goal_locations_large_verysparse to work properly (i.e. taking94 # into account minGoalDistance), you need to use the dmlab MPM:95 # learning/brain/research/dune/rl/dmlab_env_package.96 # Corresponds to 'Very Sparse' setting in the paper.97 Level(98 'contributed/dmlab30/explore_goal_locations_large',99 fully_qualified_name='explore_goal_locations_large_verysparse',100 extra_env_settings={101 # Forces the spawn and goals to be further apart.102 # Unfortunately, we cannot go much higher, because we need to103 # guarantee that for any goal location, we can at least find one104 # spawn location that is further than this number (the goal105 # location might be in the middle of the map...).106 'minGoalDistance': 10,107 },108 use_r_net_from_level='explore_goal_locations_large',109 random_maze=True, include_in_paper=True,110 scenarios=['verysparse']),111 # Corresponds to 'Sparse+Doors' setting in the paper.112 Level('contributed/dmlab30/explore_obstructed_goals_large',113 fully_qualified_name='explore_obstructed_goals_large',114 random_maze=True,115 include_in_paper=True,116 scenarios=['sparseplusdoors']),117 Level('contributed/dmlab30/explore_goal_locations_small',118 fully_qualified_name='explore_goal_locations_small',119 random_maze=True,120 include_in_paper=True,121 scenarios=['goal_small']),122 # Two levels where we expect to show episodic curiosity does not hurt.123 # Corresponds to 'Dense 1' setting in the paper.124 Level('contributed/dmlab30/explore_object_rewards_many',125 fully_qualified_name='explore_object_rewards_many',126 include_in_paper=True,127 scenarios=['dense_explore']),128 Level('contributed/dmlab30/explore_object_rewards_few',129 fully_qualified_name='explore_object_rewards_few',130 include_in_paper=True,131 scenarios=['sparse_explore']),132 Level('contributed/dmlab30/rooms_keys_doors_puzzle',133 fully_qualified_name='rooms_keys_doors_puzzle',134 include_in_paper=True,135 scenarios=['dense1']),136 # Corresponds to 'Dense 2' setting in the paper.137 Level('contributed/dmlab30/rooms_collect_good_objects_train',138 fully_qualified_name='rooms_collect_good_objects_train',139 include_in_paper=True,140 scenarios=['dense2']),141 ]142 MIXER_SEEDS = {143 # Equivalent to not setting a mixer seed. Mixer seed to train the144 # R-network.145 SplitType.R_TRAINING: 0,146 # Mixer seed for training the policy.147 SplitType.POLICY_TRAINING: 0x3D23BE66,148 SplitType.VALIDATION: 0x2B79ED94, # Invented.149 SplitType.TEST: 0x600D5EED, # Same as DM's.150 }151 @staticmethod152 def find_level(fully_qualified_name):153 """Finds a DMLab level by fully qualified name."""154 for level in Const.LEVELS:155 if level.fully_qualified_name == fully_qualified_name:156 return level157 # Fallback to the DMLab level with the corresponding name.158 return Level(fully_qualified_name,159 extra_env_settings = {160 'allowHoldOutLevels': True161 })162 @staticmethod163 def find_level_by_scenario(scenario):164 """Finds a DMLab level by scenario name."""165 for level in Const.LEVELS:166 if level.scenarios and scenario in level.scenarios:167 return level168 raise ValueError('Scenario "{}" not found.'.format(scenario))169 @staticmethod170 def get_max_episode_len_by_envname(env_name):171 if env_name.startswith('dmlab'):172 return 1350173 else:174 return None175 @staticmethod176 def is_episode_identical(environment_engine, env_name):177 if environment_engine == 'dmlab':178 return False179 else:...
wittgenstein.py
Source:wittgenstein.py
1from functools import partial2from importlib import import_module3import collections4'''5Who's your favourite Metaphysician?6'''7def create_instance(fully_qualified_name, **kwargs):8 module_name, class_name = fully_qualified_name.rsplit('.', 1)9 module = import_module(module_name)10 class_ = getattr(module, class_name)11 instance = class_(**kwargs)12 return instance13def create_function(fully_qualified_name):14 if (isinstance(fully_qualified_name, collections.Callable)) :return fully_qualified_name15 if (fully_qualified_name.count('.') < 1): # Its a builtin!16 # Its a shame really do not use this, but I found sth more elegant17 #fn_ = getattr(globals()['__builtin__'], fully_qualified_name)18 fn_ = eval(fully_qualified_name)19 else:20 module_name, function_name = fully_qualified_name.rsplit('.', 1)21 module = import_module(module_name)22 fn_ = getattr(module, function_name)23 return fn_24def create_partial_function(fully_qualified_name, **kwargs):25 fn_ = create_function(fully_qualified_name=fully_qualified_name)26 if (len(kwargs) <= 0): return fn_ # Return if no kwargs have been passed27 fn_ = partial(fn_, **kwargs) # Partially apply kwargs28 return fn_29def prepare_invocation_on_obj(obj, function_name):30 fn_ = getattr(obj, function_name)31 return fn_32def getattr_from_module(fully_qualified_name, attr):33 module = import_module(fully_qualified_name)34 attr_ = getattr(module, attr)35 return attr_36def get_staticmethod_from_class(fully_qualified_name, static_method):37 cls_ = getattr_from_module(*fully_qualified_name.rsplit('.', 1))38 m_ = getattr(cls_, static_method)...
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!!