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_co...
<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 fiel...
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 ...
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 T...
# 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. T...
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, ...
<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 ali...
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(fiel...
<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 ...
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 ...
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 al...
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`` instanc...
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.bef...
<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``...
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 fi...
<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...
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...
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 ...
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() ...
<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) ...
<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, ...
<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: ...
<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)), ...
<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'], 'u...
<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(), timeou...
<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: mess...
<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.cle...
<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 c...
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(comm...
<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 com...
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 ...
<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. Thes...
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.respons...
<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 curren...
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.c...
<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...
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...
<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 cha...
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: ...
<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 permissio...
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 messag...
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 i...
<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 n...
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) pl...
<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: ...
<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 h...
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) ...
<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.se...
<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 membe...
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.voic...
<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 keywo...
<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.colou...
<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...
<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...
<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#L14...
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 th...
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/...
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_]: ...
<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 Pos...
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 P...
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 Itera...
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 a...
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:nl...
<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 Re...
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.bytearra...
<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/att...
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 Positi...
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 Posi...
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 Posi...
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 Posi...
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 Positiona...
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 Pos...
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 t...
_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...
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/libnl...
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 ...
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...
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 Position...
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/li...
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, versi...
<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 ...
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...
# 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_...
<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 t...
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_syserr2...
<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 usin...
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_syserr...
<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...
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...
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...
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...
<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...
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...
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 -- cal...
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 Pos...
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