text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def composite( background_image, foreground_image, foreground_width_ratio=0.25, foreground_position=(0.0, 0.0), ): """Takes two images and composites them."""
if foreground_width_ratio <= 0: return background_image composite = background_image.copy() width = int(foreground_width_ratio * background_image.shape[1]) foreground_resized = resize(foreground_image, width) size = foreground_resized.shape x = int(foreground_position[1] * (backgroun...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lowres_tensor(shape, underlying_shape, offset=None, sd=None): """Produces a tensor paramaterized by a interpolated lower resolution tensor. This is like what...
sd = sd or 0.01 init_val = sd * np.random.randn(*underlying_shape).astype("float32") underlying_t = tf.Variable(init_val) t = resize_bilinear_nd(underlying_t, shape) if offset is not None: # Deal with non-list offset if not isinstance(offset, list): offset = len(shape) *...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def create_session(target='', timeout_sec=10): '''Create an intractive TensorFlow session. Helper function that creates TF session that uses growing GPU memory allocation and opration timeout. 'allow_growth' flag prevents TF from allocating the whole GPU memory an once, which is useful when having multiple p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(url, encoding=None, cache=None, mode="rb"): """Read from any URL. Internally differentiates between URLs supported by tf.gfile, such as URLs URLs. This ...
with read_handle(url, cache, mode=mode) as handle: data = handle.read() if encoding: data = data.decode(encoding) return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_handle(url, cache=None, mode="rb"): """Read from any URL with a file handle. Use this to get a handle to a file rather than eagerly load the data: ``` w...
scheme = urlparse(url).scheme if cache == 'purge': _purge_cached(url) cache = None if _is_remote(scheme) and cache is None: cache = True log.debug("Cache not specified, enabling because resource is remote.") if cache: handle = _read_and_cache(url, mode=mode) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def local_cache_path(remote_url): """Returns the path that remote_url would be cached at locally."""
local_name = RESERVED_PATH_CHARS.sub("_", remote_url) return os.path.join(gettempdir(), local_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cppn( width, batch=1, num_output_channels=3, num_hidden_channels=24, num_layers=8, activation_func=_composite_activation, normalize=False, ): """Compositiona...
r = 3.0 ** 0.5 # std(coord_range) == 1.0 coord_range = tf.linspace(-r, r, width) y, x = tf.meshgrid(coord_range, coord_range, indexing="ij") net = tf.stack([tf.stack([x, y], -1)] * batch, 0) with slim.arg_scope( [slim.conv2d], kernel_size=[1, 1], activation_fn=None, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def activation_atlas( model, layer, grid_size=10, icon_size=96, number_activations=NUMBER_OF_AVAILABLE_SAMPLES, icon_batch_size=32, verbose=False, ): """Renders ...
activations = layer.activations[:number_activations, ...] layout, = aligned_umap(activations, verbose=verbose) directions, coordinates, _ = bin_laid_out_activations( layout, activations, grid_size ) icons = [] for directions_batch in chunked(directions, icon_batch_size): icon_b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def aligned_activation_atlas( model1, layer1, model2, layer2, grid_size=10, icon_size=80, num_steps=1024, whiten_layers=True, number_activations=NUMBER_OF_AVAILAB...
combined_activations = _combine_activations( layer1, layer2, number_activations=number_activations ) layouts = aligned_umap(combined_activations, verbose=verbose) for model, layer, layout in zip((model1, model2), (layer1, layer2), layouts): directions, coordinates, densities = bin_laid...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _combine_activations( layer1, layer2, activations1=None, activations2=None, mode=ActivationTranslation.BIDIRECTIONAL, number_activations=NUMBER_OF_AVAILABLE_S...
activations1 = activations1 or layer1.activations[:number_activations, ...] activations2 = activations2 or layer2.activations[:number_activations, ...] if mode is ActivationTranslation.ONE_TO_TWO: acts_1_to_2 = push_activations(activations1, layer1, layer2) return acts_1_to_2, activations...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bin_laid_out_activations(layout, activations, grid_size, threshold=5): """Given a layout and activations, overlays a grid on the layout and returns averaged ...
assert layout.shape[0] == activations.shape[0] # calculate which grid cells each activation's layout position falls into # first bin stays empty because nothing should be < 0, so we add an extra bin bins = np.linspace(0, 1, num=grid_size + 1) bins[-1] = np.inf # last bin should include all highe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def frozen_default_graph_def(input_node_names, output_node_names): """Return frozen and simplified graph_def of default graph."""
sess = tf.get_default_session() input_graph_def = tf.get_default_graph().as_graph_def() pruned_graph = tf.graph_util.remove_training_nodes( input_graph_def, protected_nodes=(output_node_names + input_node_names) ) pruned_graph = tf.graph_util.extract_sub_graph(pruned_graph, output_node_names) # re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def infuse_metadata(graph_def, info): """Embed meta data as a string constant in a TF graph. This function takes info, converts it into json, and embeds it in gr...
temp_graph = tf.Graph() with temp_graph.as_default(): tf.constant(json.dumps(info, cls=NumpyJSONEncoder), name=metadata_node_name) meta_node = temp_graph.as_graph_def().node[0] graph_def.node.extend([meta_node])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_metadata(graph_def): """Attempt to extract meta data hidden in graph_def. Looks for a `__lucid_metadata_json` constant string op. If present, extract...
meta_matches = [n for n in graph_def.node if n.name==metadata_node_name] if meta_matches: assert len(meta_matches) == 1, "found more than 1 lucid metadata node!" meta_tensor = meta_matches[0].attr['value'].tensor return json.loads(meta_tensor.string_val[0]) else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def neighborhood(self, node, degree=4): """Am I really handcoding graph traversal please no"""
assert self.by_name[node.name] == node already_visited = frontier = set([node.name]) for _ in range(degree): neighbor_names = set() for node_name in frontier: outgoing = set(n.name for n in self.by_input[node_name]) incoming = set(self.by_name[node_name].input) neighbor_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def _retrieve_messages_before_strategy(self, retrieve): """Retrieve messages using before parameter."""
before = self.before.id if self.before else None data = await self.logs_from(self.channel.id, retrieve, before=before) if len(data): if self.limit is not None: self.limit -= retrieve self.before = Object(id=int(data[-1]['id'])) return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def _retrieve_messages_after_strategy(self, retrieve): """Retrieve messages using after parameter."""
after = self.after.id if self.after else None data = await self.logs_from(self.channel.id, retrieve, after=after) if len(data): if self.limit is not None: self.limit -= retrieve self.after = Object(id=int(data[0]['id'])) return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def _retrieve_messages_around_strategy(self, retrieve): """Retrieve messages using around parameter."""
if self.around: around = self.around.id if self.around else None data = await self.logs_from(self.channel.id, retrieve, around=around) self.around = None return data return []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def _retrieve_guilds_before_strategy(self, retrieve): """Retrieve guilds using before parameter."""
before = self.before.id if self.before else None data = await self.get_guilds(retrieve, before=before) if len(data): if self.limit is not None: self.limit -= retrieve self.before = Object(id=int(data[-1]['id'])) return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def _retrieve_guilds_after_strategy(self, retrieve): """Retrieve guilds using after parameter."""
after = self.after.id if self.after else None data = await self.get_guilds(retrieve, after=after) if len(data): if self.limit is not None: self.limit -= retrieve self.after = Object(id=int(data[0]['id'])) return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def walk_commands(self): """An iterator that recursively walks through this cog's commands and subcommands."""
from .core import GroupMixin for command in self.__cog_commands__: if command.parent is None: yield command if isinstance(command, GroupMixin): yield from command.walk_commands()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listener(cls, name=None): """A decorator that marks a function as a listener. This is the cog equivalent of :meth:`.Bot.listen`. Parameters name: :class:`str...
if name is not None and not isinstance(name, str): raise TypeError('Cog.listener expected str but received {0.__class__.__name__!r} instead.'.format(name)) def decorator(func): actual = func if isinstance(actual, staticmethod): actual = actual.__fun...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_footer(self, *, text=EmptyEmbed, icon_url=EmptyEmbed): """Sets the footer for the embed content. This function returns the class instance to allow for fl...
self._footer = {} if text is not EmptyEmbed: self._footer['text'] = str(text) if icon_url is not EmptyEmbed: self._footer['icon_url'] = str(icon_url) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_author(self, *, name, url=EmptyEmbed, icon_url=EmptyEmbed): """Sets the author for the embed content. This function returns the class instance to allow f...
self._author = { 'name': str(name) } if url is not EmptyEmbed: self._author['url'] = str(url) if icon_url is not EmptyEmbed: self._author['icon_url'] = str(icon_url) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_field(self, *, name, value, inline=True): """Adds a field to the embed object. This function returns the class instance to allow for fluent-style chainin...
field = { 'inline': inline, 'name': str(name), 'value': str(value) } try: self._fields.append(field) except AttributeError: self._fields = [field] return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_field_at(self, index, *, name, value, inline=True): """Modifies a field to the embed object. The index must point to a valid pre-existing field. This fun...
try: field = self._fields[index] except (TypeError, IndexError, AttributeError): raise IndexError('field index out of range') field['name'] = str(name) field['value'] = str(value) field['inline'] = inline return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def avatar_url_as(self, *, format=None, static_format='webp', size=1024): """Returns a friendly URL version of the avatar the user has. If the user does not have...
return Asset._from_avatar(self._state, self, format=format, static_format=static_format, size=size)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mentioned_in(self, message): """Checks if the user is mentioned in the specified message. Parameters message: :class:`Message` The message to check if you're...
if message.mention_everyone: return True for user in message.mentions: if user.id == self.id: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def time_snowflake(datetime_obj, high=False): """Returns a numeric snowflake pretending to be created at the given date. When using as the lower end of a range, ...
unix_seconds = (datetime_obj - type(datetime_obj)(1970, 1, 1)).total_seconds() discord_millis = int(unix_seconds * 1000 - DISCORD_EPOCH) return (discord_millis << 22) + (2**22-1 if high else 0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _string_width(string, *, _IS_ASCII=_IS_ASCII): """Returns string's width."""
match = _IS_ASCII.match(string) if match: return match.endpos UNICODE_WIDE_CHAR_TYPE = 'WFA' width = 0 func = unicodedata.east_asian_width for char in string: width += 2 if func(char) in UNICODE_WIDE_CHAR_TYPE else 1 return width
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def escape_markdown(text, *, as_needed=False, ignore_links=True): r"""A helper function that escapes Discord's markdown. Parameters text: :class:`str` The text t...
if not as_needed: url_regex = r'(?P<url>(?:https?|steam)://(?:-\.)?(?:[^\s/?\.#-]+\.?)+(?:/[^\s]*)?)' def replacement(match): groupdict = match.groupdict() is_url = groupdict.get('url') if is_url: return is_url return '\\' + groupdict...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def add(ctx, left: int, right: int): """Adds two numbers together."""
await ctx.send(left + right)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def roll(ctx, dice: str): """Rolls a dice in NdN format."""
try: rolls, limit = map(int, dice.split('d')) except Exception: await ctx.send('Format has to be in NdN!') return result = ', '.join(str(random.randint(1, limit)) for r in range(rolls)) await ctx.send(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: """Repeats a message multiple times."""
for i in range(times): await ctx.send(content)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def join(self, ctx, *, channel: discord.VoiceChannel): """Joins a voice channel"""
if ctx.voice_client is not None: return await ctx.voice_client.move_to(channel) await channel.connect()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def play(self, ctx, *, query): """Plays a file from the local filesystem"""
source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query)) ctx.voice_client.play(source, after=lambda e: print('Player error: %s' % e) if e else None) await ctx.send('Now playing: {}'.format(query))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def volume(self, ctx, volume: int): """Changes the player's volume"""
if ctx.voice_client is None: return await ctx.send("Not connected to a voice channel.") ctx.voice_client.source.volume = volume / 100 await ctx.send("Changed volume to {}%".format(volume))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def duration(self): """Queries the duration of the call. If the call has not ended then the current duration will be returned. Returns --------- datetime.timedel...
if self.ended_timestamp is None: return datetime.datetime.utcnow() - self.message.created_at else: return self.ended_timestamp - self.message.created_at
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def avatar_url_as(self, *, format=None, size=1024): """Returns a friendly URL version of the avatar the webhook has. If the webhook does not have a traditional a...
if self.avatar is None: # Default is always blurple apparently return Asset(self._state, 'https://cdn.discordapp.com/embed/avatars/0.png') if not utils.valid_icon_size(size): raise InvalidArgument("size must be a power of 2 between 16 and 1024") format = fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def overwrites_for(self, obj): """Returns the channel-specific overwrites for a member or a role. Parameters obj The :class:`Role` or :class:`abc.User` denoting ...
if isinstance(obj, User): predicate = lambda p: p.type == 'member' elif isinstance(obj, Role): predicate = lambda p: p.type == 'role' else: predicate = lambda p: True for overwrite in filter(predicate, self._overwrites): if overwrite.id ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def overwrites(self): """Returns all of the channel's overwrites. This is returned as a dictionary where the key contains the target which can be either a :class...
ret = {} for ow in self._overwrites: allow = Permissions(ow.allow) deny = Permissions(ow.deny) overwrite = PermissionOverwrite.from_pair(allow, deny) if ow.type == 'role': target = self.guild.get_role(ow.id) elif ow.type == 'm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loop(*, seconds=0, minutes=0, hours=0, count=None, reconnect=True, loop=None): """A decorator that schedules a task in the background for you with optional r...
def decorator(func): return Loop(func, seconds=seconds, minutes=minutes, hours=hours, count=count, reconnect=reconnect, loop=loop) return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_exception_type(self, exc): """Removes an exception type from being handled during the reconnect logic. Parameters exc: Type[:class:`BaseException`] Th...
old_length = len(self._valid_exception) self._valid_exception = tuple(x for x in self._valid_exception if x is not exc) return len(self._valid_exception) != old_length
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def after_loop(self, coro): """A function that also acts as a decorator to register a coroutine to be called after the loop finished running. Parameters coro: :t...
if not (inspect.iscoroutinefunction(coro) or inspect.isawaitable(coro)): raise TypeError('Expected coroutine or awaitable, received {0.__name__!r}.'.format(type(coro))) self._after_loop = coro
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delay(self): """Compute the next delay Returns the next delay to wait according to the exponential backoff algorithm. This is a value between 0 and base * 2^...
invocation = time.monotonic() interval = invocation - self._last_invocation self._last_invocation = invocation if interval > self._reset_time: self._exp = 0 self._exp = min(self._exp + 1, self._max) return self._randfunc(0, self._base * 2 ** self._exp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_subset(self, other): """Returns True if self has the same or fewer permissions as other."""
if isinstance(other, Permissions): return (self.value & other.value) == self.value else: raise TypeError("cannot compare {} with {}".format(self.__class__.__name__, other.__class__.__name__))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, **kwargs): r"""Bulk updates this permission object. Allows you to set multiple attributes by using keyword arguments. The names must be equivale...
for key, value in kwargs.items(): try: is_property = isinstance(getattr(self.__class__, key), property) except AttributeError: continue if is_property: setattr(self, key, value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_params(self): """Retrieves the parameter OrderedDict without the context or self parameters. Useful for inspecting signature. """
result = self.params.copy() if self.cog is not None: # first parameter is self result.popitem(last=False) try: # first/second parameter is context result.popitem(last=False) except Exception: raise ValueError('Missing context ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def full_parent_name(self): """Retrieves the fully qualified parent command name. This the base command name required to execute it. For example, in ``?one two t...
entries = [] command = self while command.parent is not None: command = command.parent entries.append(command.name) return ' '.join(reversed(entries))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parents(self): """Retrieves the parents of this command. If the command has no parents then it returns an empty :class:`list`. For example in commands ``?a b...
entries = [] command = self while command.parent is not None: command = command.parent entries.append(command) return entries
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def qualified_name(self): """Retrieves the fully qualified command name. This is the full parent name with the command name as well. For example, in ``?one two t...
parent = self.full_parent_name if parent: return parent + ' ' + self.name else: return self.name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_on_cooldown(self, ctx): """Checks whether the command is currently on cooldown. Parameters ctx: :class:`.Context.` The invocation context to use when chec...
if not self._buckets.valid: return False bucket = self._buckets.get_bucket(ctx.message) return bucket.get_tokens() == 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_cooldown(self, ctx): """Resets the cooldown on this command. Parameters ctx: :class:`.Context` The invocation context to reset the cooldown under. """
if self._buckets.valid: bucket = self._buckets.get_bucket(ctx.message) bucket.reset()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def error(self, coro): """A decorator that registers a coroutine as a local error handler. A local error handler is an :func:`.on_command_error` event limited to...
if not asyncio.iscoroutinefunction(coro): raise TypeError('The error handler must be a coroutine.') self.on_error = coro return coro
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def before_invoke(self, coro): """A decorator that registers a coroutine as a pre-invoke hook. A pre-invoke hook is called directly before the command is called....
if not asyncio.iscoroutinefunction(coro): raise TypeError('The pre-invoke hook must be a coroutine.') self._before_invoke = coro return coro
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def after_invoke(self, coro): """A decorator that registers a coroutine as a post-invoke hook. A post-invoke hook is called directly after the command is called....
if not asyncio.iscoroutinefunction(coro): raise TypeError('The post-invoke hook must be a coroutine.') self._after_invoke = coro return coro
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def short_doc(self): """Gets the "short" documentation of a command. By default, this is the :attr:`brief` attribute. If that lookup leads to an empty string the...
if self.brief is not None: return self.brief if self.help is not None: return self.help.split('\n', 1)[0] return ''
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def signature(self): """Returns a POSIX-like signature useful for help command output."""
if self.usage is not None: return self.usage params = self.clean_params if not params: return '' result = [] for name, param in params.items(): greedy = isinstance(param.annotation, converters._Greedy) if param.default is not p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def walk_commands(self): """An iterator that recursively walks through all commands and subcommands."""
for command in tuple(self.all_commands.values()): yield command if isinstance(command, GroupMixin): yield from command.walk_commands()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_for(self, event, predicate, result=None): """Waits for a DISPATCH'd event that meets the predicate. Parameters event: :class:`str` The event name in all...
future = self.loop.create_future() entry = EventListener(event=event, predicate=predicate, result=result, future=future) self._dispatch_listeners.append(entry) return future
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def identify(self): """Sends the IDENTIFY packet."""
payload = { 'op': self.IDENTIFY, 'd': { 'token': self.token, 'properties': { '$os': sys.platform, '$browser': 'discord.py', '$device': 'discord.py', '$referrer': '', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def resume(self): """Sends the RESUME packet."""
payload = { 'op': self.RESUME, 'd': { 'seq': self.sequence, 'session_id': self.session_id, 'token': self.token } } await self.send_as_json(payload) log.info('Shard ID %s has sent the RESUME payload.', s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def poll_event(self): """Polls for a DISPATCH event and handles the general gateway loop. Raises ------ ConnectionClosed The websocket connection was termi...
try: msg = await self.recv() await self.received_message(msg) except websockets.exceptions.ConnectionClosed as exc: if self._can_handle_close(exc.code): log.info('Websocket closed with %s (%s), attempting a reconnect.', exc.code, exc.reason) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear(self): """Clears the paginator to have no pages."""
if self.prefix is not None: self._current_page = [self.prefix] self._count = len(self.prefix) + 1 # prefix + newline else: self._current_page = [] self._count = 0 self._pages = []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_line(self, line='', *, empty=False): """Adds a line to the current page. If the line exceeds the :attr:`max_size` then an exception is raised. Parameters...
max_page_size = self.max_size - self._prefix_len - 2 if len(line) > max_page_size: raise RuntimeError('Line exceeds maximum page size %s' % (max_page_size)) if self._count + len(line) + 1 > self.max_size: self.close_page() self._count += len(line) + 1 s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close_page(self): """Prematurely terminate a page."""
if self.suffix is not None: self._current_page.append(self.suffix) self._pages.append('\n'.join(self._current_page)) if self.prefix is not None: self._current_page = [self.prefix] self._count = len(self.prefix) + 1 # prefix + newline else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_prefix(self): """The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``."""
user = self.context.guild.me if self.context.guild else self.context.bot.user # this breaks if the prefix mention is not the bot itself but I # consider this to be an *incredibly* strange use case. I'd rather go # for this common use case rather than waste performance for the # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_command_signature(self, command): """Retrieves the signature portion of the help page. Parameters command: :class:`Command` The command to get the signat...
parent = command.full_parent_name if len(command.aliases) > 0: aliases = '|'.join(command.aliases) fmt = '[%s|%s]' % (command.name, aliases) if parent: fmt = parent + ' ' + fmt alias = fmt else: alias = command.name if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_mentions(self, string): """Removes mentions from the string to prevent abuse. This includes ``@everyone``, ``@here``, member mentions and role mention...
def replace(obj, *, transforms=self.MENTION_TRANSFORMS): return transforms.get(obj.group(0), '@invalid') return self.MENTION_PATTERN.sub(replace, string)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_max_size(self, commands): """Returns the largest name length of the specified command list. Parameters commands: Sequence[:class:`Command`] A sequence of...
as_lengths = ( discord.utils._string_width(c.name) for c in commands ) return max(as_lengths, default=0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_indented_commands(self, commands, *, heading, max_size=None): """Indents a list of commands after the specified heading. The formatting is added to the :...
if not commands: return self.paginator.add_line(heading) max_size = max_size or self.get_max_size(commands) get_width = discord.utils._string_width for command in commands: name = command.name width = max_size - (get_width(name) - len(name)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_bot_commands_formatting(self, commands, heading): """Adds the minified bot heading with commands to the output. The formatting should be added to the :at...
if commands: # U+2002 Middle Dot joined = '\u2002'.join(c.name for c in commands) self.paginator.add_line('__**%s**__' % heading) self.paginator.add_line(joined)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_subcommand_formatting(self, command): """Adds formatting information on a subcommand. The formatting should be added to the :attr:`paginator`. The defaul...
fmt = '{0}{1} \N{EN DASH} {2}' if command.short_doc else '{0}{1}' self.paginator.add_line(fmt.format(self.clean_prefix, command.qualified_name, command.short_doc))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_aliases_formatting(self, aliases): """Adds the formatting information on a command's aliases. The formatting should be added to the :attr:`paginator`. Th...
self.paginator.add_line('**%s** %s' % (self.aliases_heading, ', '.join(aliases)), empty=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_command_formatting(self, command): """A utility function to format commands and groups. Parameters command: :class:`Command` The command to format. """
if command.description: self.paginator.add_line(command.description, empty=True) signature = self.get_command_signature(command) if command.aliases: self.paginator.add_line(signature) self.add_aliases_formatting(command.aliases) else: se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_audio_packet(self, data, *, encode=True): """Sends an audio packet composed of the data. You must be connected to play audio. Parameters data: bytes The...
self.checked_add('sequence', 1, 65535) if encode: encoded_data = self.encoder.encode(data, self.encoder.SAMPLES_PER_FRAME) else: encoded_data = data packet = self._get_voice_packet(encoded_data) try: self.socket.sendto(packet, (self.endpoint_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear(self): """Clears the internal state of the bot. After this, the bot can be considered "re-opened", i.e. :meth:`.is_closed` and :meth:`.is_ready` both r...
self._closed = False self._ready.clear() self._connection.clear() self.http.recreate()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, *args, **kwargs): """A blocking call that abstracts away the event loop initialisation from you. If you want more control over the event loop then ...
async def runner(): try: await self.start(*args, **kwargs) finally: await self.close() try: self.loop.run_until_complete(runner()) except KeyboardInterrupt: log.info('Received signal to terminate bot and event loop...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def event(self, coro): """A decorator that registers an event to listen to. You can find more info about the events on the :ref:`documentation below <discord-api...
if not asyncio.iscoroutinefunction(coro): raise TypeError('event registered must be a coroutine function') setattr(self, coro.__name__, coro) log.debug('%s has successfully been registered as an event', coro.__name__) return coro
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def raw_role_mentions(self): """A property that returns an array of role IDs matched with the syntax of <@&role_id> in the message content. """
return [int(x) for x in re.findall(r'<@&([0-9]+)>', self.content)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def when_mentioned_or(*prefixes): """A callable that implements when mentioned or other prefixes provided. These are meant to be passed into the :attr:`.Bot.comm...
def inner(bot, msg): r = list(prefixes) r = when_mentioned(bot, msg) + r return r return inner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_check(self, func, *, call_once=False): """Adds a global check to the bot. This is the non-decorator interface to :meth:`.check` and :meth:`.check_once`. ...
if call_once: self._check_once.append(func) else: self._checks.append(func)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_check(self, func, *, call_once=False): """Removes a global check from the bot. This function is idempotent and will not raise an exception if the func...
l = self._check_once if call_once else self._checks try: l.remove(func) except ValueError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_listener(self, func, name=None): """Removes a listener from the pool of listeners. Parameters func The function that was used as a listener to remove....
name = func.__name__ if name is None else name if name in self.extra_events: try: self.extra_events[name].remove(func) except ValueError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_cog(self, cog): """Adds a "cog" to the bot. A cog is a class that has its own event listeners and commands. Parameters cog: :class:`.Cog` The cog to regi...
if not isinstance(cog, Cog): raise TypeError('cogs must derive from Cog') cog = cog._inject(self) self.__cogs[cog.__cog_name__] = cog
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_cog(self, name): """Removes a cog from the bot. All registered commands and event listeners that the cog has registered will be removed as well. If no...
cog = self.__cogs.pop(name, None) if cog is None: return help_command = self._help_command if help_command and help_command.cog is cog: help_command.cog = None cog._eject(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_extension(self, name): """Loads an extension. An extension is a python module that contains commands, cogs, or listeners. An extension must have a globa...
if name in self.__extensions: raise errors.ExtensionAlreadyLoaded(name) try: lib = importlib.import_module(name) except ImportError as e: raise errors.ExtensionNotFound(name, e) from e else: self._load_from_module_spec(lib, name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unload_extension(self, name): """Unloads an extension. When the extension is unloaded, all commands, listeners, and cogs are removed from the bot and the mod...
lib = self.__extensions.get(name) if lib is None: raise errors.ExtensionNotLoaded(name) self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reload_extension(self, name): """Atomically reloads an extension. This replaces the extension with the same extension, only refreshed. This is equivalent to ...
lib = self.__extensions.get(name) if lib is None: raise errors.ExtensionNotLoaded(name) # get the previous module states from sys modules modules = { name: module for name, module in sys.modules.items() if _is_submodule(lib.__name__, nam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chunked(self): """Returns a boolean indicating if the guild is "chunked". A chunked guild means that :attr:`member_count` is equal to the number of members s...
count = getattr(self, '_member_count', None) if count is None: return False return count == len(self._members)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shard_id(self): """Returns the shard ID for this guild if applicable."""
count = self._state.shard_count if count is None: return None return (self.id >> 22) % count
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_member_named(self, name): """Returns the first member found that matches the name provided. The name can have an optional discriminator argument, e.g. "J...
result = None members = self.members if len(name) > 5 and name[-5] == '#': # The 5 length is checking to see if #0000 is in the string, # as a#0000 has a length of 6, the minimum for a potential # discriminator lookup. potential_discriminator = n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def group(*blueprints, url_prefix=""): """ Create a list of blueprints, optionally grouping them under a general URL prefix. :param blueprints: blueprints to be ...
def chain(nested): """itertools.chain() but leaves strings untouched""" for i in nested: if isinstance(i, (list, tuple)): yield from chain(i) elif isinstance(i, BlueprintGroup): yield from i.blueprints ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, app, options): """ Register the blueprint to the sanic app. :param app: Instance of :class:`sanic.app.Sanic` class :param options: Options to ...
url_prefix = options.get("url_prefix", self.url_prefix) # Routes for future in self.routes: # attach the blueprint name to the handler so that it can be # prefixed properly in the router future.handler.__blueprintname__ = self.name # Prepend the...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def route( self, uri, methods=frozenset({"GET"}), host=None, strict_slashes=None, stream=False, version=None, name=None, ): """Create a blueprint route from a de...
if strict_slashes is None: strict_slashes = self.strict_slashes def decorator(handler): route = FutureRoute( handler, uri, methods, host, strict_slashes, stream, vers...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def websocket( self, uri, host=None, strict_slashes=None, version=None, name=None ): """Create a blueprint websocket route from a decorated function. :param uri:...
if strict_slashes is None: strict_slashes = self.strict_slashes def decorator(handler): route = FutureRoute( handler, uri, [], host, strict_slashes, False, version, name ) self.websocket_routes.append(route) return handler ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_websocket_route( self, handler, uri, host=None, version=None, name=None ): """Create a blueprint websocket route from a function. :param handler: functio...
self.websocket(uri=uri, host=host, version=version, name=name)(handler) return handler
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listener(self, event): """Create a listener from a decorated function. :param event: Event to listen to. """
def decorator(listener): self.listeners[event].append(listener) return listener return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def middleware(self, *args, **kwargs): """ Create a blueprint middleware from a decorated function. :param args: Positional arguments to be used while invoking t...
def register_middleware(_middleware): future_middleware = FutureMiddleware(_middleware, args, kwargs) self.middlewares.append(future_middleware) return _middleware # Detect which way this was called, @middleware or @middleware('AT') if len(args) == 1 and le...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exception(self, *args, **kwargs): """ This method enables the process of creating a global exception handler for the current blueprint under question. :param...
def decorator(handler): exception = FutureException(handler, args, kwargs) self.exceptions.append(exception) return handler return decorator