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 get_count_query(self): """ Copies the query object and alters the field list and order by to do a more efficient count """
query_copy = self.copy() if not query_copy.tables: raise Exception('No tables specified to do a count') for table in query_copy.tables: del table.fields[:] query_copy.tables[0].add_field(CountField('*')) del query_copy.sorters[:] return query_copy
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count(self, field='*'): """ Returns a COUNT of the query by wrapping the query and performing a COUNT aggregate of the specified field :param field: the field to pass to the COUNT aggregate. Defaults to '*' :type field: str :return: The number of rows that the query will return :rtype: int """
rows = self.get_count_query().select(bypass_safe_limit=True) return list(rows[0].values())[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 _fetch_all_as_dict(self, cursor): """ Iterates over the result set and converts each row to a dictionary :return: A list of dictionaries where each row is a dictionary :rtype: list of dict """
desc = cursor.description return [ dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall() ]
<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_sql(self, debug=False, use_cache=True): """ Generates the sql for this query window and returns the sql as a string. :type debug: bool :param debug: If True, the sql will be returned in a format that is easier to read and debug. Defaults to False :type use_cache: bool :param use_cache: If True, the query will returned the cached sql if it exists rather then generating the sql again. If False, the sql will be generated again. Defaults to True. :rtype: str :return: The generated sql for this query window """
# TODO: implement caching and debug sql = '' sql += self.build_partition_by_fields() sql += self.build_order_by(use_alias=False) sql += self.build_limit() sql = sql.strip() sql = 'OVER ({0})'.format(sql) self.sql = sql return self.sql
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def value_for_keypath(dict, keypath): """ Returns the value of a keypath in a dictionary if the keypath exists or None if the keypath does not exist. """
if len(keypath) == 0: return dict keys = keypath.split('.') value = dict for key in keys: if key in value: value = value[key] else: return None return 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 set_value_for_keypath(item, keypath, value, create_if_needed=False, delimeter='.'): """ Sets the value for a keypath in a dictionary if the keypath exists. This modifies the original dictionary. """
if len(keypath) == 0: return None keys = keypath.split(delimeter) if len(keys) > 1: key = keys[0] if create_if_needed: item[key] = item.get(key, {}) if key in item: if set_value_for_keypath(item[key], delimeter.join(keys[1:]), value, create_if_needed=create_if_needed, delimeter=delimeter): return item return None if create_if_needed: item[keypath] = item.get(keypath, {}) if keypath in item: item[keypath] = value return item 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 get_alias(self): """ Gets the alias for the field or the auto_alias if one is set. If there isn't any kind of alias, None is returned. :return: The field alias, auto_alias, or None :rtype: str or None """
alias = None if self.alias: alias = self.alias elif self.auto_alias: alias = self.auto_alias if self.table and self.table.prefix_fields: field_prefix = self.table.get_field_prefix() if alias: alias = '{0}__{1}'.format(field_prefix, alias) else: alias = '{0}__{1}'.format(field_prefix, self.name) return alias
<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_select_sql(self): """ Gets the SELECT field portion for the field without the alias. If the field has a table, it will be included here like table.field :return: Gets the SELECT field portion for the field without the alias :rtype: str """
if self.table: return '{0}.{1}'.format(self.table.get_identifier(), self.name) return '{0}'.format(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 set_table(self, table): """ Setter for the table of this field. Also sets the inner field's table. """
super(MultiField, self).set_table(table) if self.field and self.field.table is None: self.field.set_table(self.table)
<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_to_table(self, field, alias, add_group=False): """ Adds this field to the field's table and optionally group by it :param field: The field to add to the table :type field: str or :class:`Field <querybuilder.fields.Field>` :param alias: The alias for the field :type alias: str :param add_group: Whether or not the table should group by this field :type: bool """
self.table.add_field({ alias: field }) if add_group: self.table.owner.group_by(alias)
<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_alias(self): """ Gets the alias for the table or the auto_alias if one is set. If there isn't any kind of alias, None is returned. :returns: The table alias, auto_alias, or None :rtype: str or None """
alias = None if self.alias: alias = self.alias elif self.auto_alias: alias = self.auto_alias return alias
<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, field): """ Adds a field to this table :param field: This can be a string of a field name, a dict of {'alias': field}, or a ``Field`` instance :type field: str or dict or Field """
field = FieldFactory( field, ) field.set_table(self) # make sure field is not already added field_name = field.get_name() for existing_field in self.fields: if existing_field.get_name() == field_name: return None self.before_add_field(field) field.before_add() if field.ignore is False: self.fields.append(field) return field
<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_field(self, field): """ Removes a field from this table :param field: This can be a string of a field name, a dict of {'alias': field}, or a ``Field`` instance :type field: str or dict or :class:`Field <querybuilder.fields.Field>` """
new_field = FieldFactory( field, ) new_field.set_table(self) new_field_identifier = new_field.get_identifier() for field in self.fields: if field.get_identifier() == new_field_identifier: self.fields.remove(field) return field 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 add_fields(self, fields): """ Adds all of the passed fields to the table's current field list :param fields: The fields to select from ``table``. This can be a single field, a tuple of fields, or a list of fields. Each field can be a string or ``Field`` instance :type fields: str or tuple or list of str or list of Field or :class:`Field <querybuilder.fields.Field>` """
if isinstance(fields, string_types): fields = [fields] elif type(fields) is tuple: fields = list(fields) field_objects = [self.add_field(field) for field in fields] return field_objects
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_field(self, field=None, alias=None): """ Finds a field by name or alias. :param field: string of the field name or alias, dict of {'alias': field}, or a Field instance :type field: str or dict or Field :returns: The field if it is found, otherwise None :rtype: :class:`Field <querybuilder.fields.Field>` or None """
if alias: field = alias field = FieldFactory(field, table=self, alias=alias) identifier = field.get_identifier() for field in self.fields: if field.get_identifier() == identifier: return field 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 init_defaults(self): """ Sets the name of the table to the passed in table value """
super(SimpleTable, self).init_defaults() self.name = self.table
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_defaults(self): """ Sets a model instance variable to the table value and sets the name to the table name as determined from the model class """
super(ModelTable, self).init_defaults() self.model = self.table self.name = self.model._meta.db_table
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_defaults(self): """ Sets a query instance variable to the table value """
super(QueryTable, self).init_defaults() self.query = self.table self.query.is_inner = 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 run_command(cmd_to_run): """ Wrapper around subprocess that pipes the stderr and stdout from `cmd_to_run` to temporary files. Using the temporary files gets around subprocess.PIPE's issues with handling large buffers. Note: this command will block the python process until `cmd_to_run` has completed. Returns a tuple, containing the stderr and stdout as strings. """
with tempfile.TemporaryFile() as stdout_file, tempfile.TemporaryFile() as stderr_file: # Run the command popen = subprocess.Popen(cmd_to_run, stdout=stdout_file, stderr=stderr_file) popen.wait() stderr_file.seek(0) stdout_file.seek(0) stderr = stderr_file.read() stdout = stdout_file.read() if six.PY3: stderr = stderr.decode() stdout = stdout.decode() return stderr, stdout
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log(self, level, prefix = ''): """Writes the contents of the Extension to the logging system. """
logging.log(level, "%sname: %s", prefix, self.__name) logging.log(level, "%soptions: %s", prefix, self.__options)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def specbits(self): """Returns the array of arguments that would be given to iptables for the current Extension. """
bits = [] for opt in sorted(self.__options): # handle the case where this is a negated option m = re.match(r'^! (.*)', opt) if m: bits.extend(['!', "--%s" % m.group(1)]) else: bits.append("--%s" % opt) optval = self.__options[opt] if isinstance(optval, list): bits.extend(optval) else: bits.append(optval) return bits
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log(self, level, prefix = ''): """Writes the contents of the Rule to the logging system. """
logging.log(level, "%sin interface: %s", prefix, self.in_interface) logging.log(level, "%sout interface: %s", prefix, self.out_interface) logging.log(level, "%ssource: %s", prefix, self.source) logging.log(level, "%sdestination: %s", prefix, self.destination) logging.log(level, "%smatches:", prefix) for match in self.matches: match.log(level, prefix + ' ') if self.jump: logging.log(level, "%sjump:", prefix) self.jump.log(level, prefix + ' ')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def specbits(self): """Returns the array of arguments that would be given to iptables for the current Rule. """
def host_bits(opt, optval): # handle the case where this is a negated value m = re.match(r'^!\s*(.*)', optval) if m: return ['!', opt, m.group(1)] else: return [opt, optval] bits = [] if self.protocol: bits.extend(host_bits('-p', self.protocol)) if self.in_interface: bits.extend(host_bits('-i', self.in_interface)) if self.out_interface: bits.extend(host_bits('-o', self.out_interface)) if self.source: bits.extend(host_bits('-s', self.source)) if self.destination: bits.extend(host_bits('-d', self.destination)) for mod in self.matches: bits.extend(['-m', mod.name()]) bits.extend(mod.specbits()) if self.goto: bits.extend(['-g', self.goto.name()]) bits.extend(self.goto.specbits()) elif self.jump: bits.extend(['-j', self.jump.name()]) bits.extend(self.jump.specbits()) return bits
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_chains(data): """ Parse the chain definitions. """
chains = odict() for line in data.splitlines(True): m = re_chain.match(line) if m: policy = None if m.group(2) != '-': policy = m.group(2) chains[m.group(1)] = { 'policy': policy, 'packets': int(m.group(3)), 'bytes': int(m.group(4)), } return chains
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_rules(data, chain): """ Parse the rules for the specified chain. """
rules = [] for line in data.splitlines(True): m = re_rule.match(line) if m and m.group(3) == chain: rule = parse_rule(m.group(4)) rule.packets = int(m.group(1)) rule.bytes = int(m.group(2)) rules.append(rule) return rules
<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_new_connection(self, conn_params): """Opens a connection to the database."""
self.__connection_string = conn_params.get('connection_string', '') conn = self.Database.connect(**conn_params) return conn
<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_connection_params(self): """Returns a dict of parameters suitable for get_new_connection."""
from django.conf import settings settings_dict = self.settings_dict options = settings_dict.get('OPTIONS', {}) autocommit = options.get('autocommit', False) conn_params = { 'server': settings_dict['HOST'], 'database': settings_dict['NAME'], 'user': settings_dict['USER'], 'port': settings_dict.get('PORT', '1433'), 'password': settings_dict['PASSWORD'], 'timeout': self.command_timeout, 'autocommit': autocommit, 'use_mars': options.get('use_mars', False), 'load_balancer': options.get('load_balancer', None), 'failover_partner': options.get('failover_partner', None), 'use_tz': utc if getattr(settings, 'USE_TZ', False) else None, } for opt in _SUPPORTED_OPTIONS: if opt in options: conn_params[opt] = options[opt] self.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None return conn_params
<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_cursor(self, name=None): """Creates a cursor. Assumes that a connection is established."""
cursor = self.connection.cursor() cursor.tzinfo_factory = self.tzinfo_factory return cursor
<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_dbms_version(self, make_connection=True): """ Returns the 'DBMS Version' string """
major, minor, _, _ = self.get_server_version(make_connection=make_connection) return '{}.{}'.format(major, minor)
<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_buffer(self): """Get the change buffers."""
buffer = [] for table in self.__tables: buffer.extend(table.get_buffer()) return buffer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """Start the firewall."""
self.clear() self.setDefaultPolicy() self.acceptIcmp() self.acceptInput('lo')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_rules(self, chainname): """Returns a list of Rules in the specified chain. """
data = self.__run([self.__iptables_save, '-t', self.__name, '-c']) return netfilter.parser.parse_rules(data, chainname)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def commit(self): """Commits any buffered commands. This is only useful if auto_commit is False. """
while len(self.__buffer) > 0: self.__run(self.__buffer.pop(0))
<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 numbered_page(self): """lets you type a page number to go to"""
to_delete = [] to_delete.append(await self.bot.send_message(self.message.channel, 'What page do you want to go to?')) msg = await self.bot.wait_for_message(author=self.author, channel=self.message.channel, check=lambda m: m.content.isdigit(), timeout=30.0) if msg is not None: page = int(msg.content) to_delete.append(msg) if page != 0 and page <= self.maximum_pages: await self.show_page(page) else: to_delete.append(await self.bot.say('Invalid page given. (%s/%s)' % (page, self.maximum_pages))) await asyncio.sleep(5) else: to_delete.append(await self.bot.send_message(self.message.channel, 'Took too long.')) await asyncio.sleep(5) try: await self.bot.delete_messages(to_delete) except Exception: pass
<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 show_help(self): """shows this message"""
e = discord.Embed() messages = ['Welcome to the interactive paginator!\n'] messages.append('This interactively allows you to see pages of text by navigating with ' \ 'reactions. They are as follows:\n') for (emoji, func) in self.reaction_emojis: messages.append('%s %s' % (emoji, func.__doc__)) e.description = '\n'.join(messages) e.colour = 0x738bd7 # blurple e.set_footer(text='We were on page %s before this message.' % self.current_page) await self.bot.edit_message(self.message, embed=e) async def go_back_to_current_page(): await asyncio.sleep(60.0) await self.show_current_page() self.bot.loop.create_task(go_back_to_current_page())
<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 stop_pages(self): """stops the interactive pagination session"""
await self.bot.delete_message(self.message) self.paginating = False
<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 paginate(self): """Actually paginate the entries and run the interactive loop if necessary."""
await self.show_page(1, first=True) while self.paginating: react = await self.bot.wait_for_reaction(message=self.message, check=self.react_check, timeout=120.0) if react is None: self.paginating = False try: await self.bot.clear_reactions(self.message) except: pass finally: break try: await self.bot.remove_reaction(self.message, react.reaction.emoji, react.user) except: pass # can't remove it so don't bother doing so await self.match()
<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 _senddms(self): """Toggles sending DMs to owner."""
data = self.bot.config.get("meta", {}) tosend = data.get('send_dms', True) data['send_dms'] = not tosend await self.bot.config.put('meta', data) await self.bot.responses.toggle(message="Forwarding of DMs to owner has been {status}.", success=data['send_dms'])
<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 _quit(self): """Quits the bot."""
await self.bot.responses.failure(message="Bot shutting down") await self.bot.logout()
<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 _setcolor(self, *, color : discord.Colour): """Sets the default color of embeds."""
data = self.bot.config.get("meta", {}) data['default_color'] = str(color) await self.bot.config.put('meta', data) await self.bot.responses.basic(message="The default color has been updated.")
<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 _do(self, ctx, times: int, *, command): """Repeats a command a specified number of times."""
msg = copy.copy(ctx.message) msg.content = command for i in range(times): await self.bot.process_commands(msg)
<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 disable(self, ctx, *, command: str): """Disables a command for this server. You must have Manage Server permissions or the Bot Admin role to use this command. """
command = command.lower() if command in ('enable', 'disable'): return await self.bot.responses.failure(message='Cannot disable that command.') if command not in self.bot.commands: return await self.bot.responses.failure(message='Command "{}" was not found.'.format(command)) guild_id = ctx.message.server.id cmds = self.config.get('commands', {}) entries = cmds.get(guild_id, []) entries.append(command) cmds[guild_id] = entries await self.config.put('commands', cmds) await self.bot.responses.success(message='"%s" command disabled in this server.' % command)
<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 enable(self, ctx, *, command: str): """Enables a command for this server. You must have Manage Server permissions or the Bot Admin role to use this command. """
command = command.lower() guild_id = ctx.message.server.id cmds = self.config.get('commands', {}) entries = cmds.get(guild_id, []) try: entries.remove(command) except KeyError: await self.bot.responses.failure(message='The command does not exist or is not disabled.') else: cmds[guild_id] = entries await self.config.put('commands', cmds) await self.bot.responses.success(message='"%s" command enabled in this server.' % command)
<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 ignore(self, ctx): """Handles the bot's ignore lists. To use these commands, you must have the Bot Admin role or have Manage Channels permissions. These commands are not allowed to be used in a private message context. Users with Manage Roles or Bot Admin role can still invoke the bot in ignored channels. """
if ctx.invoked_subcommand is None: await self.bot.say('Invalid subcommand passed: {0.subcommand_passed}'.format(ctx))
<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 ignore_list(self, ctx): """Tells you what channels are currently ignored in this server."""
ignored = self.config.get('ignored', []) channel_ids = set(c.id for c in ctx.message.server.channels) result = [] for channel in ignored: if channel in channel_ids: result.append('<#{}>'.format(channel)) if result: await self.bot.responses.basic(title="Ignored Channels:", message='\n\n{}'.format(', '.join(result))) else: await self.bot.responses.failure(message='I am not ignoring any channels here.')
<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 channel_cmd(self, ctx, *, channel : discord.Channel = None): """Ignores a specific channel from being processed. If no channel is specified, the current channel is ignored. If a channel is ignored then the bot does not process commands in that channel until it is unignored. """
if channel is None: channel = ctx.message.channel ignored = self.config.get('ignored', []) if channel.id in ignored: await self.bot.responses.failure(message='That channel is already ignored.') return ignored.append(channel.id) await self.config.put('ignored', ignored) await self.bot.responses.success(message='Channel <#{}> will be ignored.'.format(channel.id))
<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 _all(self, ctx): """Ignores every channel in the server from being processed. This works by adding every channel that the server currently has into the ignore list. If more channels are added then they will have to be ignored by using the ignore command. To use this command you must have Manage Server permissions along with Manage Channels permissions. You could also have the Bot Admin role. """
ignored = self.config.get('ignored', []) channels = ctx.message.server.channels ignored.extend(c.id for c in channels if c.type == discord.ChannelType.text) await self.config.put('ignored', list(set(ignored))) # make unique await self.bot.responses.success(message='All channels ignored.')
<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 unignore(self, ctx, *channels: discord.Channel): """Unignores channels from being processed. If no channels are specified, it unignores the current channel. To use this command you must have the Manage Channels permission or have the Bot Admin role. """
if len(channels) == 0: channels = (ctx.message.channel,) # a set is the proper data type for the ignore list # however, JSON only supports arrays and objects not sets. ignored = self.config.get('ignored', []) result = [] for channel in channels: try: ignored.remove(channel.id) except ValueError: pass else: result.append('<#{}>'.format(channel.id)) await self.config.put('ignored', ignored) await self.bot.responses.success(message='Channel(s) {} will no longer be ignored.'.format(', '.join(result)))
<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 unignore_all(self, ctx): """Unignores all channels in this server from being processed. To use this command you must have the Manage Channels permission or have the Bot Admin role. """
channels = [c for c in ctx.message.server.channels if c.type is discord.ChannelType.text] await ctx.invoke(self.unignore, *channels)
<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 cleanup(self, ctx, search : int = 100): """Cleans up the bot's messages from the channel. If a search number is specified, it searches that many messages to delete. If the bot has Manage Messages permissions, then it will try to delete messages that look like they invoked the bot as well. After the cleanup is completed, the bot will send you a message with which people got their messages deleted and their count. This is useful to see which users are spammers. To use this command you must have Manage Messages permission or have the Bot Mod role. """
spammers = Counter() channel = ctx.message.channel prefixes = self.bot.command_prefix if callable(prefixes): prefixes = prefixes(self.bot, ctx.message) def is_possible_command_invoke(entry): valid_call = any(entry.content.startswith(prefix) for prefix in prefixes) return valid_call and not entry.content[1:2].isspace() can_delete = channel.permissions_for(channel.server.me).manage_messages if not can_delete: api_calls = 0 async for entry in self.bot.logs_from(channel, limit=search, before=ctx.message): if api_calls and api_calls % 5 == 0: await asyncio.sleep(1.1) if entry.author == self.bot.user: await self.bot.delete_message(entry) spammers['Bot'] += 1 api_calls += 1 if is_possible_command_invoke(entry): try: await self.bot.delete_message(entry) except discord.Forbidden: continue else: spammers[entry.author.display_name] += 1 api_calls += 1 else: predicate = lambda m: m.author == self.bot.user or is_possible_command_invoke(m) deleted = await self.bot.purge_from(channel, limit=search, before=ctx.message, check=predicate) spammers = Counter(m.author.display_name for m in deleted) deleted = sum(spammers.values()) messages = ['%s %s removed.' % (deleted, 'message was' if deleted == 1 else 'messages were')] if deleted: messages.append('') spammers = sorted(spammers.items(), key=lambda t: t[1], reverse=True) messages.extend(map(lambda t: '**{0[0]}**: {0[1]}'.format(t), spammers)) msg = await self.bot.responses.basic(title="Removed Messages:", message='\n'.join(messages)) await asyncio.sleep(10) await self.bot.delete_message(msg)
<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 plonk(self, ctx, *, member: discord.Member): """Bans a user from using the bot. This bans a person from using the bot in the current server. There is no concept of a global ban. This ban can be bypassed by having the Manage Server permission. To use this command you must have the Manage Server permission or have a Bot Admin role. """
plonks = self.config.get('plonks', {}) guild_id = ctx.message.server.id db = plonks.get(guild_id, []) if member.id in db: await self.bot.responses.failure(message='That user is already bot banned in this server.') return db.append(member.id) plonks[guild_id] = db await self.config.put('plonks', plonks) await self.bot.responses.success(message='%s has been banned from using the bot in this server.' % member)
<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 plonks(self, ctx): """Shows members banned from the bot."""
plonks = self.config.get('plonks', {}) guild = ctx.message.server db = plonks.get(guild.id, []) members = '\n'.join(map(str, filter(None, map(guild.get_member, db)))) if members: await self.bot.responses.basic(title="Plonked Users:", message=members) else: await self.bot.responses.failure(message='No members are banned in this server.')
<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 unplonk(self, ctx, *, member: discord.Member): """Unbans a user from using the bot. To use this command you must have the Manage Server permission or have a Bot Admin role. """
plonks = self.config.get('plonks', {}) guild_id = ctx.message.server.id db = plonks.get(guild_id, []) try: db.remove(member.id) except ValueError: await self.bot.responses.failure(message='%s is not banned from using the bot in this server.' % member) else: plonks[guild_id] = db await self.config.put('plonks', plonks) await self.bot.responses.success(message='%s has been unbanned from using the bot in this server.' % member)
<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): """Sends you the bot invite link."""
perms = discord.Permissions.none() perms.read_messages = True perms.send_messages = True perms.manage_messages = True perms.embed_links = True perms.read_message_history = True perms.attach_files = True perms.add_reactions = True await self.bot.send_message(ctx.message.author, discord.utils.oauth_url(self.bot.client_id, perms))
<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 info(self, ctx, *, member : discord.Member = None): """Shows info about a member. This cannot be used in private messages. If you don't specify a member then the info returned will be yours. """
channel = ctx.message.channel if member is None: member = ctx.message.author e = discord.Embed() roles = [role.name.replace('@', '@\u200b') for role in member.roles] shared = sum(1 for m in self.bot.get_all_members() if m.id == member.id) voice = member.voice_channel if voice is not None: other_people = len(voice.voice_members) - 1 voice_fmt = '{} with {} others' if other_people else '{} by themselves' voice = voice_fmt.format(voice.name, other_people) else: voice = 'Not connected.' e.set_author(name=str(member), icon_url=member.avatar_url or member.default_avatar_url) e.set_footer(text='Member since').timestamp = member.joined_at e.add_field(name='ID', value=member.id) e.add_field(name='Servers', value='%s shared' % shared) e.add_field(name='Voice', value=voice) e.add_field(name='Created', value=member.created_at) e.add_field(name='Roles', value=', '.join(roles)) e.colour = member.colour if member.avatar: e.set_image(url=member.avatar_url) await self.bot.say(embed=e)
<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 put(self, key, value, *args): """Edits a data entry."""
self._db[key] = value await self.save()
<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 addreaction(self, ctx, *, reactor=""): """Interactively adds a custom reaction"""
if not reactor: await self.bot.say("What should I react to?") response = await self.bot.wait_for_message(author=ctx.message.author) reactor = response.content data = self.config.get(ctx.message.server.id, {}) keyword = data.get(reactor, {}) if keyword: await self.bot.responses.failure(message="Reaction '{}' already exists.".format(reactor)) return await self.bot.say("Okay, I'll react to '{}'. What do you want me to say? (Type $none for no response)".format(reactor)) response = await self.bot.wait_for_message(author=ctx.message.author) reactions = [] def check(reaction, user): if str(reaction.emoji) != "\U000023f9": reactions.append(reaction.emoji) return False else: return user == ctx.message.author msg = await self.bot.say("Awesome! Now react to this message any reactions I should have to '{}'. (React \U000023f9 to stop)".format(reactor)) await self.bot.wait_for_reaction(message=msg, check=check) for i, reaction in enumerate(reactions): reaction = reaction if isinstance(reaction, str) else reaction.name + ":" + str(reaction.id) await self.bot.add_reaction(ctx.message, reaction) reactions[i] = reaction if response: keyword["response"] = response.content if response.content.lower() != "$none" else "" keyword["reaction"] = reactions data[reactor] = keyword await self.config.put(ctx.message.server.id, data) await self.bot.responses.success(message="Reaction '{}' has been added.".format(reactor))
<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 listreactions(self, ctx): """Lists all the reactions for the server"""
data = self.config.get(ctx.message.server.id, {}) if not data: await self.bot.responses.failure(message="There are no reactions on this server.") return try: pager = Pages(self.bot, message=ctx.message, entries=list(data.keys())) pager.embed.colour = 0x738bd7 # blurple pager.embed.set_author(name=ctx.message.server.name + " Reactions", icon_url=ctx.message.server.icon_url) await pager.paginate() except Exception as e: await self.bot.say(e)
<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 viewreaction(self, ctx, *, reactor : str): """Views a specific reaction"""
data = self.config.get(ctx.message.server.id, {}) keyword = data.get(reactor, {}) if not keyword: await self.bot.responses.failure(message="Reaction '{}' was not found.".format(reactor)) return response = data.get(reactor, {}).get("response", "") reacts = data.get(reactor, {}).get("reaction", []) for i, r in enumerate(reacts): if ":" in r: reacts[i] = "<:" + r + ">" reacts = " ".join(reacts) if reacts else "-" response = response if response else "-" string = "Here's what I say to '{reactor}': {response}\n"\ "I'll react to this message how I react to '{reactor}'.".format(reactor=reactor,response=response) await self.bot.responses.full(sections=[{"name": "Response", "value": response}, {"name": "Reactions", "value": reacts, "inline": False}])
<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 _default_help_command(ctx, *commands : str): """Shows this message."""
bot = ctx.bot destination = ctx.message.author if bot.pm_help else ctx.message.channel def repl(obj): return _mentions_transforms.get(obj.group(0), '') # help by itself just lists our own commands. if len(commands) == 0: pages = bot.formatter.format_help_for(ctx, bot) elif len(commands) == 1: # try to see if it is a cog name name = _mention_pattern.sub(repl, commands[0]) command = None if name in [x.lower() for x in bot.cogs]: command = bot.cogs[[x for x in bot.cogs if x.lower() == name][0]] else: command = bot.commands.get(name) if command is None: await bot.responses.failure(destination=destination, message=bot.command_not_found.format(name)) return pages = bot.formatter.format_help_for(ctx, command) else: name = _mention_pattern.sub(repl, commands[0]) command = bot.commands.get(name) if command is None: await bot.responses.failure(destination=destination, message=bot.command_not_found.format(name)) return for key in commands[1:]: try: key = _mention_pattern.sub(repl, key) command = command.commands.get(key) if command is None: await bot.responses.failure(destination=destination, message=bot.command_not_found.format(name)) return except AttributeError: await bot.responses.failure(destination=destination, message=bot.command_has_no_subcommands.format(command, key)) return pages = bot.formatter.format_help_for(ctx, command) if bot.pm_help is None: characters = sum(map(lambda l: len(l), pages.values())) if characters > 1000: destination = ctx.message.author await bot.responses.full(destination=destination, **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 nla_ok(nla, remaining): """Check if the attribute header and payload can be accessed safely. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L148 Verifies that the header and payload do not exceed the number of bytes left in the attribute stream. This function must be called before access the attribute header or payload when iterating over the attribute stream using nla_next(). Positional arguments: nla -- attribute of any kind (nlattr class instance). remaining -- number of bytes remaining in attribute stream (c_int). Returns: True if the attribute can be accessed safely, False otherwise. """
return remaining.value >= nla.SIZEOF and nla.SIZEOF <= nla.nla_len <= remaining.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 nla_next(nla, remaining): """Return next attribute in a stream of attributes. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L171 Calculates the offset to the next attribute based on the attribute given. The attribute provided is assumed to be accessible, the caller is responsible to use nla_ok() beforehand. The offset (length of specified attribute including padding) is then subtracted from the remaining bytes variable and a pointer to the next attribute is returned. nla_next() can be called as long as remaining is >0. Positional arguments: nla -- attribute of any kind (nlattr class instance). remaining -- number of bytes remaining in attribute stream (c_int). Returns: Next nlattr class instance. """
totlen = int(NLA_ALIGN(nla.nla_len)) remaining.value -= totlen return nlattr(bytearray_ptr(nla.bytearray, totlen))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nla_parse(tb, maxtype, head, len_, policy): """Create attribute index based on a stream of attributes. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L242 Iterates over the stream of attributes and stores a pointer to each attribute in the index array using the attribute type as index to the array. Attribute with a type greater than the maximum type specified will be silently ignored in order to maintain backwards compatibility. If `policy` is not None, the attribute will be validated using the specified policy. Positional arguments: tb -- dictionary to be filled (maxtype+1 elements). maxtype -- maximum attribute type expected and accepted (integer). head -- first nlattr with more in its bytearray payload (nlattr class instance). len_ -- length of attribute stream (integer). policy -- dictionary of nla_policy class instances as values, with nla types as keys. Returns: 0 on success or a negative error code. """
rem = c_int() for nla in nla_for_each_attr(head, len_, rem): type_ = nla_type(nla) if type_ > maxtype: continue if policy: err = validate_nla(nla, maxtype, policy) if err < 0: return err if type_ in tb and tb[type_]: _LOGGER.debug('Attribute of type %d found multiple times in message, previous attribute is being ignored.', type_) tb[type_] = nla if rem.value > 0: _LOGGER.debug('netlink: %d bytes leftover after parsing attributes.', rem.value) return 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 nla_for_each_attr(head, len_, rem): """Iterate over a stream of attributes. https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink/attr.h#L262 Positional arguments: head -- first nlattr with more in its bytearray payload (nlattr class instance). len_ -- length of attribute stream (integer). rem -- initialized to len, holds bytes currently remaining in stream (c_int). Returns: Generator yielding nlattr instances. """
pos = head rem.value = len_ while nla_ok(pos, rem): yield pos pos = nla_next(pos, rem)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nla_for_each_nested(nla, rem): """Iterate over a stream of nested attributes. https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink/attr.h#L274 Positional arguments: nla -- attribute containing the nested attributes (nlattr class instance). rem -- initialized to len, holds bytes currently remaining in stream (c_int). Returns: Generator yielding nlattr instances. """
pos = nlattr(nla_data(nla)) rem.value = nla_len(nla) while nla_ok(pos, rem): yield pos pos = nla_next(pos, rem)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nla_find(head, len_, attrtype): """Find a single attribute in a stream of attributes. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L323 Iterates over the stream of attributes and compares each type with the type specified. Returns the first attribute which matches the type. Positional arguments: head -- first nlattr with more in its bytearray payload (nlattr class instance). len_ -- length of attributes stream (integer). attrtype -- attribute type to look for (integer). Returns: Attribute found (nlattr class instance) or None. """
rem = c_int() for nla in nla_for_each_attr(head, len_, rem): if nla_type(nla) == attrtype: return nla 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 nla_reserve(msg, attrtype, attrlen): """Reserve space for an attribute. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L456 Reserves room for an attribute in the specified Netlink message and fills in the attribute header (type, length). Returns None if there is insufficient space for the attribute. Any padding between payload and the start of the next attribute is zeroed out. Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). attrlen -- length of payload (integer). Returns: nlattr class instance allocated to the new space or None on failure. """
tlen = NLMSG_ALIGN(msg.nm_nlh.nlmsg_len) + nla_total_size(attrlen) if tlen > msg.nm_size: return None nla = nlattr(nlmsg_tail(msg.nm_nlh)) nla.nla_type = attrtype nla.nla_len = nla_attr_size(attrlen) if attrlen: padlen = nla_padlen(attrlen) nla.bytearray[nla.nla_len:nla.nla_len + padlen] = bytearray(b'\0') * padlen msg.nm_nlh.nlmsg_len = tlen _LOGGER.debug('msg 0x%x: attr <0x%x> %d: Reserved %d (%d) bytes at offset +%d nlmsg_len=%d', id(msg), id(nla), nla.nla_type, nla_total_size(attrlen), attrlen, nla.bytearray.slice.start - nlmsg_data(msg.nm_nlh).slice.start, msg.nm_nlh.nlmsg_len) return nla
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nla_put(msg, attrtype, datalen, data): """Add a unspecific attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L497 Reserves room for an unspecific attribute and copies the provided data into the message as payload of the attribute. Returns an error if there is insufficient space for the attribute. Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). datalen -- length of data to be used as payload (integer). data -- data to be used as attribute payload (bytearray). Returns: 0 on success or a negative error code. """
nla = nla_reserve(msg, attrtype, datalen) if not nla: return -NLE_NOMEM if datalen <= 0: return 0 nla_data(nla)[:datalen] = data[:datalen] _LOGGER.debug('msg 0x%x: attr <0x%x> %d: Wrote %d bytes at offset +%d', id(msg), id(nla), nla.nla_type, datalen, nla.bytearray.slice.start - nlmsg_data(msg.nm_nlh).slice.start) return 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 nla_put_data(msg, attrtype, data): """Add abstract data as unspecific attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L527 Equivalent to nla_put() except that the length of the payload is derived from the bytearray data object. Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). data -- data to be used as attribute payload (bytearray). Returns: 0 on success or a negative error code. """
return nla_put(msg, attrtype, len(data), 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 nla_put_u8(msg, attrtype, value): """Add 8 bit integer attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L563 Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). value -- numeric value to store as payload (int() or c_uint8()). Returns: 0 on success or a negative error code. """
data = bytearray(value if isinstance(value, c_uint8) else c_uint8(value)) return nla_put(msg, attrtype, SIZEOF_U8, 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 nla_put_u16(msg, attrtype, value): """Add 16 bit integer attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L588 Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). value -- numeric value to store as payload (int() or c_uint16()). Returns: 0 on success or a negative error code. """
data = bytearray(value if isinstance(value, c_uint16) else c_uint16(value)) return nla_put(msg, attrtype, SIZEOF_U16, 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 nla_put_u32(msg, attrtype, value): """Add 32 bit integer attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L613 Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). value -- numeric value to store as payload (int() or c_uint32()). Returns: 0 on success or a negative error code. """
data = bytearray(value if isinstance(value, c_uint32) else c_uint32(value)) return nla_put(msg, attrtype, SIZEOF_U32, 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 nla_put_u64(msg, attrtype, value): """Add 64 bit integer attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L638 Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). value -- numeric value to store as payload (int() or c_uint64()). Returns: 0 on success or a negative error code. """
data = bytearray(value if isinstance(value, c_uint64) else c_uint64(value)) return nla_put(msg, attrtype, SIZEOF_U64, 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 nla_put_string(msg, attrtype, value): """Add string attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L674 Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). value -- bytes() or bytearray() value (e.g. 'Test'.encode('ascii')). Returns: 0 on success or a negative error code. """
data = bytearray(value) + bytearray(b'\0') return nla_put(msg, attrtype, len(data), 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 nla_put_msecs(msg, attrtype, msecs): """Add msecs Netlink attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L737 Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). msecs -- number of msecs (int(), c_uint64(), or c_ulong()). Returns: 0 on success or a negative error code. """
if isinstance(msecs, c_uint64): pass elif isinstance(msecs, c_ulong): msecs = c_uint64(msecs.value) else: msecs = c_uint64(msecs) return nla_put_u64(msg, attrtype, msecs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nla_put_nested(msg, attrtype, nested): """Add nested attributes to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L772 Takes the attributes found in the `nested` message and appends them to the message `msg` nested in a container of the type `attrtype`. The `nested` message may not have a family specific header. Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). nested -- message containing attributes to be nested (nl_msg class instance). Returns: 0 on success or a negative error code. """
_LOGGER.debug('msg 0x%x: attr <> %d: adding msg 0x%x as nested attribute', id(msg), attrtype, id(nested)) return nla_put(msg, attrtype, nlmsg_datalen(nested.nm_nlh), nlmsg_data(nested.nm_nlh))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nla_parse_nested(tb, maxtype, nla, policy): """Create attribute index based on nested attribute. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L885 Feeds the stream of attributes nested into the specified attribute to nla_parse(). Positional arguments: tb -- dictionary to be filled (maxtype+1 elements). maxtype -- maximum attribute type expected and accepted (integer). nla -- nested attribute (nlattr class instance). policy -- attribute validation policy. Returns: 0 on success or a negative error code. """
return nla_parse(tb, maxtype, nlattr(nla_data(nla)), nla_len(nla), policy)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def genl_send_simple(sk, family, cmd, version, flags): """Send a Generic Netlink message consisting only of a header. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/genl.c#L84 This function is a shortcut for sending a Generic Netlink message without any message payload. The message will only consist of the Netlink and Generic Netlink headers. The header is constructed based on the specified parameters and passed on to nl_send_simple() to send it on the specified socket. Positional arguments: sk -- Generic Netlink socket (nl_sock class instance). family -- numeric family identifier (integer). cmd -- numeric command identifier (integer). version -- interface version (integer). flags -- additional Netlink message flags (integer). Returns: 0 on success or a negative error code. """
hdr = genlmsghdr(cmd=cmd, version=version) return int(nl_send_simple(sk, family, flags, hdr, hdr.SIZEOF))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def genlmsg_valid_hdr(nlh, hdrlen): """Validate Generic Netlink message headers. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/genl.c#L117 Verifies the integrity of the Netlink and Generic Netlink headers by enforcing the following requirements: - Valid Netlink message header (`nlmsg_valid_hdr()`) - Presence of a complete Generic Netlink header - At least `hdrlen` bytes of payload included after the generic Netlink header. Positional arguments: nlh -- Netlink message header (nlmsghdr class instance). hdrlen -- length of user header (integer). Returns: True if the headers are valid or False if not. """
if not nlmsg_valid_hdr(nlh, GENL_HDRLEN): return False ghdr = genlmsghdr(nlmsg_data(nlh)) if genlmsg_len(ghdr) < NLMSG_ALIGN(hdrlen): return False return 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 genlmsg_parse(nlh, hdrlen, tb, maxtype, policy): """Parse Generic Netlink message including attributes. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/genl.c#L191 Verifies the validity of the Netlink and Generic Netlink headers using genlmsg_valid_hdr() and calls nla_parse() on the message payload to parse eventual attributes. Positional arguments: nlh -- Netlink message header (nlmsghdr class instance). hdrlen -- length of user header (integer). tb -- empty dict, to be updated with nlattr class instances to store parsed attributes. maxtype -- maximum attribute id expected (integer). policy -- dictionary of nla_policy class instances as values, with nla types as keys. Returns: 0 on success or a negative error code. """
if not genlmsg_valid_hdr(nlh, hdrlen): return -NLE_MSG_TOOSHORT ghdr = genlmsghdr(nlmsg_data(nlh)) return int(nla_parse(tb, maxtype, genlmsg_attrdata(ghdr, hdrlen), genlmsg_attrlen(ghdr, hdrlen), policy))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def genlmsg_len(gnlh): """Return length of message payload including user header. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/genl.c#L224 Positional arguments: gnlh -- Generic Netlink message header (genlmsghdr class instance). Returns: Length of user payload including an eventual user header in number of bytes. """
nlh = nlmsghdr(bytearray_ptr(gnlh.bytearray, -NLMSG_HDRLEN, oob=True)) return nlh.nlmsg_len - GENL_HDRLEN - NLMSG_HDRLEN
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def genlmsg_put(msg, port, seq, family, hdrlen, flags, cmd, version): """Add Generic Netlink headers to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/genl.c#L348 Calls nlmsg_put() on the specified message object to reserve space for the Netlink header, the Generic Netlink header, and a user header of specified length. Fills out the header fields with the specified parameters. Positional arguments: msg -- Netlink message object (nl_msg class instance). port -- Netlink port or NL_AUTO_PORT (c_uint32). seq -- sequence number of message or NL_AUTO_SEQ (c_uint32). family -- numeric family identifier (integer). hdrlen -- length of user header (integer). flags -- additional Netlink message flags (integer). cmd -- numeric command identifier (c_uint8). version -- interface version (c_uint8). Returns: bytearray starting at user header or None if an error occurred. """
hdr = genlmsghdr(cmd=cmd, version=version) nlh = nlmsg_put(msg, port, seq, family, GENL_HDRLEN + hdrlen, flags) if nlh is None: return None nlmsg_data(nlh)[:hdr.SIZEOF] = hdr.bytearray[:hdr.SIZEOF] _LOGGER.debug('msg 0x%x: Added generic netlink header cmd=%d version=%d', id(msg), cmd, version) return bytearray_ptr(nlmsg_data(nlh), GENL_HDRLEN)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nl_cb_call(cb, type_, msg): """Call a callback function. https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink-private/netlink.h#L136 Positional arguments: cb -- nl_cb class instance. type_ -- callback type integer (e.g. NL_CB_MSG_OUT). msg -- Netlink message (nl_msg class instance). Returns: Integer from the callback function (like NL_OK, NL_SKIP, etc). """
cb.cb_active = type_ ret = cb.cb_set[type_](msg, cb.cb_args[type_]) cb.cb_active = 10 + 1 # NL_CB_TYPE_MAX + 1 return int(ret)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nl_pad(self, value): """Pad setter."""
self.bytearray[self._get_slicers(1)] = bytearray(c_ushort(value or 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 nl_groups(self, value): """Group setter."""
self.bytearray[self._get_slicers(3)] = bytearray(c_uint32(value or 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 nlmsg_type(self, value): """Message content setter."""
self.bytearray[self._get_slicers(1)] = bytearray(c_uint16(value or 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 nlmsg_seq(self, value): """Sequence setter."""
self.bytearray[self._get_slicers(3)] = bytearray(c_uint32(value or 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 nl_socket_alloc(cb=None): """Allocate new Netlink socket. Does not yet actually open a socket. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L206 Also has code for generating local port once. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L123 Keyword arguments: cb -- custom callback handler. Returns: Newly allocated Netlink socket (nl_sock class instance) or None. """
# Allocate the callback. cb = cb or nl_cb_alloc(default_cb) if not cb: return None # Allocate the socket. sk = nl_sock() sk.s_cb = cb sk.s_local.nl_family = getattr(socket, 'AF_NETLINK', -1) sk.s_peer.nl_family = getattr(socket, 'AF_NETLINK', -1) sk.s_seq_expect = sk.s_seq_next = int(time.time()) sk.s_flags = NL_OWN_PORT # The port is 0 (unspecified), meaning NL_OWN_PORT. # Generate local port. nl_socket_get_local_port(sk) # I didn't find this in the C source, but during testing I saw this behavior. return sk
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nl_socket_add_memberships(sk, *group): """Join groups. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L417 Joins the specified groups using the modern socket option. The list of groups has to be terminated by 0. Make sure to use the correct group definitions as the older bitmask definitions for nl_join_groups() are likely to still be present for backward compatibility reasons. Positional arguments: sk -- Netlink socket (nl_sock class instance). group -- group identifier (integer). Returns: 0 on success or a negative error code. """
if sk.s_fd == -1: return -NLE_BAD_SOCK for grp in group: if not grp: break if grp < 0: return -NLE_INVAL try: sk.socket_instance.setsockopt(SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, grp) except OSError as exc: return -nl_syserr2nlerr(exc.errno) return 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 nl_socket_drop_memberships(sk, *group): """Leave groups. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L465 Leaves the specified groups using the modern socket option. The list of groups has to terminated by 0. Positional arguments: sk -- Netlink socket (nl_sock class instance). group -- group identifier (integer). Returns: 0 on success or a negative error code. """
if sk.s_fd == -1: return -NLE_BAD_SOCK for grp in group: if not grp: break if grp < 0: return -NLE_INVAL try: sk.socket_instance.setsockopt(SOL_NETLINK, NETLINK_DROP_MEMBERSHIP, grp) except OSError as exc: return -nl_syserr2nlerr(exc.errno) return 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 nl_socket_modify_cb(sk, type_, kind, func, arg): """Modify the callback handler associated with the socket. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L633 Sets specific callback functions in the existing nl_cb class instance stored in the nl_sock socket. Positional arguments: sk -- Netlink socket (nl_sock class instance). type_ -- which type callback to set (integer). kind -- kind of callback (integer). func -- callback function. arg -- argument to be passed to callback function. Returns: 0 on success or a negative error code. """
return int(nl_cb_set(sk.s_cb, type_, kind, func, arg))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nl_socket_modify_err_cb(sk, kind, func, arg): """Modify the error callback handler associated with the socket. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L649 Positional arguments: sk -- Netlink socket (nl_sock class instance). kind -- kind of callback (integer). func -- callback function. arg -- argument to be passed to callback function. Returns: 0 on success or a negative error code. """
return int(nl_cb_err(sk.s_cb, kind, func, arg))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nl_socket_set_buffer_size(sk, rxbuf, txbuf): """Set socket buffer size of Netlink socket. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L675 Sets the socket buffer size of a Netlink socket to the specified values `rxbuf` and `txbuf`. Providing a value of 0 assumes a good default value. Positional arguments: sk -- Netlink socket (nl_sock class instance). rxbuf -- new receive socket buffer size in bytes (integer). txbuf -- new transmit socket buffer size in bytes (integer). Returns: 0 on success or a negative error code. """
rxbuf = 32768 if rxbuf <= 0 else rxbuf txbuf = 32768 if txbuf <= 0 else txbuf if sk.s_fd == -1: return -NLE_BAD_SOCK try: sk.socket_instance.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, txbuf) except OSError as exc: return -nl_syserr2nlerr(exc.errno) try: sk.socket_instance.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, rxbuf) except OSError as exc: return -nl_syserr2nlerr(exc.errno) sk.s_flags |= NL_SOCK_BUFSIZE_SET return 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 cmd(self, value): """Command setter."""
self.bytearray[self._get_slicers(0)] = bytearray(c_uint8(value or 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 version(self, value): """Version setter."""
self.bytearray[self._get_slicers(1)] = bytearray(c_uint8(value or 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 reserved(self, value): """Reserved setter."""
self.bytearray[self._get_slicers(2)] = bytearray(c_uint16(value or 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 _get(out_parsed, in_bss, key, parser_func): """Handle calling the parser function to convert bytearray data into Python data types. Positional arguments: out_parsed -- dictionary to update with parsed data and string keys. in_bss -- dictionary of integer keys and bytearray values. key -- key string to lookup (must be a variable name in libnl.nl80211.nl80211). parser_func -- function to call, with the bytearray data as the only argument. """
short_key = key[12:].lower() key_integer = getattr(nl80211, key) if in_bss.get(key_integer) is None: return dict() data = parser_func(in_bss[key_integer]) if parser_func == libnl.attr.nla_data: data = data[:libnl.attr.nla_len(in_bss[key_integer])] out_parsed[short_key] = 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 _fetch(in_parsed, *keys): """Retrieve nested dict data from either information elements or beacon IES dicts. Positional arguments: in_parsed -- dictionary to read from. keys -- one or more nested dict keys to lookup. Returns: Found value or None. """
for ie in ('information_elements', 'beacon_ies'): target = in_parsed.get(ie, {}) for key in keys: target = target.get(key, {}) if target: return target 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 nl_cb_alloc(kind): """Allocate a new callback handle. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L201 Positional arguments: kind -- callback kind to be used for initialization. Returns: Newly allocated callback handle (nl_cb class instance) or None. """
if kind < 0 or kind > NL_CB_KIND_MAX: return None cb = nl_cb() cb.cb_active = NL_CB_TYPE_MAX + 1 for i in range(NL_CB_TYPE_MAX): nl_cb_set(cb, i, kind, None, None) nl_cb_err(cb, kind, None, None) return cb
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nl_cb_set(cb, type_, kind, func, arg): """Set up a callback. Updates `cb` in place. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L293 Positional arguments: cb -- nl_cb class instance. type_ -- callback to modify (integer). kind -- kind of implementation (integer). func -- callback function (NL_CB_CUSTOM). arg -- argument passed to callback. Returns: 0 on success or a negative error code. """
if type_ < 0 or type_ > NL_CB_TYPE_MAX or kind < 0 or kind > NL_CB_KIND_MAX: return -NLE_RANGE if kind == NL_CB_CUSTOM: cb.cb_set[type_] = func cb.cb_args[type_] = arg else: cb.cb_set[type_] = cb_def[type_][kind] cb.cb_args[type_] = arg return 0