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 clear_notify(self, messages):
""" Clears notification popups. Call this to ged rid of messages that don't time out. :param messages: The popups to remove. This should be exactly what :meth:`notify` returned when creating the popup """ |
newpile = self._notificationbar.widget_list
for l in messages:
if l in newpile:
newpile.remove(l)
if newpile:
self._notificationbar = urwid.Pile(newpile)
else:
self._notificationbar = None
self.update() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def choice(self, message, choices=None, select=None, cancel=None, msg_position='above', choices_to_return=None):
""" prompt user to make a choice. :param message: string to display before list of choices :type message: unicode :param choices: dict of possible choices :type choices: dict: keymap->choice (both str) :param choices_to_return: dict of possible choices to return for the choices of the choices of paramter :type choices: dict: keymap->choice key is str and value is any obj) :param select: choice to return if enter/return is hit. Ignored if set to `None`. :type select: str :param cancel: choice to return if escape is hit. Ignored if set to `None`. :type cancel: str :param msg_position: determines if `message` is above or left of the prompt. Must be `above` or `left`. :type msg_position: str :rtype: asyncio.Future """ |
choices = choices or {'y': 'yes', 'n': 'no'}
assert select is None or select in choices.values()
assert cancel is None or cancel in choices.values()
assert msg_position in ['left', 'above']
fut = asyncio.get_event_loop().create_future() # Create a returned future
oldroot = self.mainloop.widget
def select_or_cancel(text):
"""Restore the main screen and invoce the callback (delayed return)
with the given text."""
self.mainloop.widget = oldroot
self._passall = False
fut.set_result(text)
# set up widgets
msgpart = urwid.Text(message)
choicespart = ChoiceWidget(choices,
choices_to_return=choices_to_return,
callback=select_or_cancel, select=select,
cancel=cancel)
# build widget
if msg_position == 'left':
both = urwid.Columns(
[
('fixed', len(message), msgpart),
('weight', 1, choicespart),
], dividechars=1)
else: # above
both = urwid.Pile([msgpart, choicespart])
att = settings.get_theming_attribute('global', 'prompt')
both = urwid.AttrMap(both, att, att)
# put promptwidget as overlay on main widget
overlay = urwid.Overlay(both, oldroot,
('fixed left', 0),
('fixed right', 0),
('fixed bottom', 1),
None)
self.mainloop.widget = overlay
self._passall = True
return fut |
<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 apply_command(self, cmd):
""" applies a command This calls the pre and post hooks attached to the command, as well as :meth:`cmd.apply`. :param cmd: an applicable command :type cmd: :class:`~alot.commands.Command` """ |
# FIXME: What are we guarding for here? We don't mention that None is
# allowed as a value fo cmd.
if cmd:
if cmd.prehook:
await cmd.prehook(ui=self, dbm=self.dbman, cmd=cmd)
try:
if asyncio.iscoroutinefunction(cmd.apply):
await cmd.apply(self)
else:
cmd.apply(self)
except Exception as e:
self._error_handler(e)
else:
if cmd.posthook:
logging.info('calling post-hook')
await cmd.posthook(ui=self, dbm=self.dbman, cmd=cmd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_signal(self, signum, frame):
""" handles UNIX signals This function currently just handles SIGUSR1. It could be extended to handle more :param signum: The signal number (see man 7 signal) :param frame: The execution frame (https://docs.python.org/2/reference/datamodel.html#frame-objects) """ |
# it is a SIGINT ?
if signum == signal.SIGINT:
logging.info('shut down cleanly')
asyncio.ensure_future(self.apply_command(globals.ExitCommand()))
elif signum == signal.SIGUSR1:
if isinstance(self.current_buffer, SearchBuffer):
self.current_buffer.rebuild()
self.update() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanup(self):
"""Do the final clean up before shutting down.""" |
size = settings.get('history_size')
self._save_history_to_file(self.commandprompthistory,
self._cmd_hist_file, size=size)
self._save_history_to_file(self.senderhistory, self._sender_hist_file,
size=size)
self._save_history_to_file(self.recipienthistory,
self._recipients_hist_file, size=size) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_history_from_file(path, size=-1):
"""Load a history list from a file and split it into lines. :param path: the path to the file that should be loaded :type path: str :param size: the number of lines to load (0 means no lines, < 0 means all lines) :type size: int :returns: a list of history items (the lines of the file) :rtype: list(str) """ |
if size == 0:
return []
if os.path.exists(path):
with codecs.open(path, 'r', encoding='utf-8') as histfile:
lines = [line.rstrip('\n') for line in histfile]
if size > 0:
lines = lines[-size:]
return lines
else:
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parser():
"""Parse command line arguments, validate them, and return them.""" |
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-r', '--read-only', action='store_true',
help='open notmuch database in read-only mode')
parser.add_argument('-c', '--config', metavar='FILENAME',
action=cargparse.ValidatedStoreAction,
validator=cargparse.require_file,
help='configuration file')
parser.add_argument('-n', '--notmuch-config', metavar='FILENAME',
default=os.environ.get(
'NOTMUCH_CONFIG',
os.path.expanduser('~/.notmuch-config')),
action=cargparse.ValidatedStoreAction,
validator=cargparse.require_file,
help='notmuch configuration file')
parser.add_argument('-C', '--colour-mode', metavar='COLOURS',
choices=(1, 16, 256), type=int,
help='number of colours to use')
parser.add_argument('-p', '--mailindex-path', metavar='PATH',
action=cargparse.ValidatedStoreAction,
validator=cargparse.require_dir,
help='path to notmuch index')
parser.add_argument('-d', '--debug-level', metavar='LEVEL', default='info',
choices=('debug', 'info', 'warning', 'error'),
help='debug level [default: %(default)s]')
parser.add_argument('-l', '--logfile', metavar='FILENAME',
default='/dev/null',
action=cargparse.ValidatedStoreAction,
validator=cargparse.optional_file_like,
help='log file [default: %(default)s]')
parser.add_argument('-h', '--help', action='help',
help='display this help and exit')
parser.add_argument('-v', '--version', action='version',
version=alot.__version__,
help='output version information and exit')
# We will handle the subcommands in a separate run of argparse as argparse
# does not support optional subcommands until now.
parser.add_argument('command', nargs=argparse.REMAINDER,
help='possible subcommands are {}'.format(
', '.join(_SUBCOMMANDS)))
options = parser.parse_args()
if options.command:
# We have a command after the initial options so we also parse that.
# But we just use the parser that is already defined for the internal
# command that will back this subcommand.
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='subcommand')
for subcommand in _SUBCOMMANDS:
subparsers.add_parser(subcommand,
parents=[COMMANDS['global'][subcommand][1]])
command = parser.parse_args(options.command)
else:
command = None
return options, command |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""The main entry point to alot. It parses the command line and prepares for the user interface main loop to run.""" |
options, command = parser()
# logging
root_logger = logging.getLogger()
for log_handler in root_logger.handlers:
root_logger.removeHandler(log_handler)
root_logger = None
numeric_loglevel = getattr(logging, options.debug_level.upper(), None)
logformat = '%(levelname)s:%(module)s:%(message)s'
logging.basicConfig(level=numeric_loglevel, filename=options.logfile,
filemode='w', format=logformat)
# locate alot config files
cpath = options.config
if options.config is None:
xdg_dir = get_xdg_env('XDG_CONFIG_HOME',
os.path.expanduser('~/.config'))
alotconfig = os.path.join(xdg_dir, 'alot', 'config')
if os.path.exists(alotconfig):
cpath = alotconfig
try:
settings.read_config(cpath)
settings.read_notmuch_config(options.notmuch_config)
except (ConfigError, OSError, IOError) as e:
print('Error when parsing a config file. '
'See log for potential details.')
sys.exit(e)
# store options given by config swiches to the settingsManager:
if options.colour_mode:
settings.set('colourmode', options.colour_mode)
# get ourselves a database manager
indexpath = settings.get_notmuch_setting('database', 'path')
indexpath = options.mailindex_path or indexpath
dbman = DBManager(path=indexpath, ro=options.read_only)
# determine what to do
if command is None:
try:
cmdstring = settings.get('initial_command')
except CommandParseError as err:
sys.exit(err)
elif command.subcommand in _SUBCOMMANDS:
cmdstring = ' '.join(options.command)
# set up and start interface
UI(dbman, cmdstring)
# run the exit hook
exit_hook = settings.get_hook('exit')
if exit_hook is not None:
exit_hook() |
<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 update_keys(ui, envelope, block_error=False, signed_only=False):
"""Find and set the encryption keys in an envolope. :param ui: the main user interface object :type ui: alot.ui.UI :param envolope: the envolope buffer object :type envolope: alot.buffers.EnvelopeBuffer :param block_error: wether error messages for the user should expire automatically or block the ui :type block_error: bool :param signed_only: only use keys whose uid is signed (trusted to belong to the key) :type signed_only: bool """ |
encrypt_keys = []
for header in ('To', 'Cc'):
if header not in envelope.headers:
continue
for recipient in envelope.headers[header][0].split(','):
if not recipient:
continue
match = re.search("<(.*@.*)>", recipient)
if match:
recipient = match.group(1)
encrypt_keys.append(recipient)
logging.debug("encryption keys: " + str(encrypt_keys))
keys = await _get_keys(ui, encrypt_keys, block_error=block_error,
signed_only=signed_only)
if keys:
envelope.encrypt_keys = keys
envelope.encrypt = True
if 'From' in envelope.headers:
try:
if envelope.account is None:
envelope.account = settings.account_matching_address(
envelope['From'])
acc = envelope.account
if acc.encrypt_to_self:
if acc.gpg_key:
logging.debug('encrypt to self: %s', acc.gpg_key.fpr)
envelope.encrypt_keys[acc.gpg_key.fpr] = acc.gpg_key
else:
logging.debug('encrypt to self: no gpg_key in account')
except NoMatchingAccount:
logging.debug('encrypt to self: no account found')
else:
envelope.encrypt = 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 _get_keys(ui, encrypt_keyids, block_error=False, signed_only=False):
"""Get several keys from the GPG keyring. The keys are selected by keyid and are checked if they can be used for encryption. :param ui: the main user interface object :type ui: alot.ui.UI :param encrypt_keyids: the key ids of the keys to get :type encrypt_keyids: list(str) :param block_error: wether error messages for the user should expire automatically or block the ui :type block_error: bool :param signed_only: only return keys whose uid is signed (trusted to belong to the key) :type signed_only: bool :returns: the available keys indexed by their OpenPGP fingerprint :rtype: dict(str->gpg key object) """ |
keys = {}
for keyid in encrypt_keyids:
try:
key = crypto.get_key(keyid, validate=True, encrypt=True,
signed_only=signed_only)
except GPGProblem as e:
if e.code == GPGCode.AMBIGUOUS_NAME:
tmp_choices = ['{} ({})'.format(k.uids[0].uid, k.fpr) for k in
crypto.list_keys(hint=keyid)]
choices = {str(i): t for i, t in enumerate(tmp_choices, 1)}
keys_to_return = {str(i): t for i, t in enumerate([k for k in
crypto.list_keys(hint=keyid)], 1)}
choosen_key = await ui.choice("ambiguous keyid! Which " +
"key do you want to use?",
choices=choices,
choices_to_return=keys_to_return)
if choosen_key:
keys[choosen_key.fpr] = choosen_key
continue
else:
ui.notify(str(e), priority='error', block=block_error)
continue
keys[key.fpr] = key
return keys |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_string(cls, address, case_sensitive=False):
"""Alternate constructor for building from a string. :param str address: An email address in <user>@<domain> form :param bool case_sensitive: passed directly to the constructor argument of the same name. :returns: An account from the given arguments :rtype: :class:`Account` """ |
assert isinstance(address, str), 'address must be str'
username, domainname = address.split('@')
return cls(username, domainname, case_sensitive=case_sensitive) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __cmp(self, other, comparitor):
"""Shared helper for rich comparison operators. This allows the comparison operators to be relatively simple and share the complex logic. If the username is not considered case sensitive then lower the username of both self and the other, and handle that the other can be either another :class:`~alot.account.Address`, or a `str` instance. :param other: The other address to compare against :type other: str or ~alot.account.Address :param callable comparitor: A function with the a signature (str, str) -> bool that will compare the two instance. The intention is to use functions from the operator module. """ |
if isinstance(other, str):
try:
ouser, odomain = other.split('@')
except ValueError:
ouser, odomain = '', ''
else:
ouser = other.username
odomain = other.domainname
if not self.case_sensitive:
ouser = ouser.lower()
username = self.username.lower()
else:
username = self.username
return (comparitor(username, ouser) and
comparitor(self.domainname.lower(), odomain.lower())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def matches_address(self, address):
"""returns whether this account knows about an email address :param str address: address to look up :rtype: bool """ |
if self.address == address:
return True
for alias in self.aliases:
if alias == address:
return True
if self._alias_regexp and self._alias_regexp.match(address):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def store_mail(mbx, mail):
""" stores given mail in mailbox. If mailbox is maildir, set the S-flag and return path to newly added mail. Oherwise this will return `None`. :param mbx: mailbox to use :type mbx: :class:`mailbox.Mailbox` :param mail: the mail to store :type mail: :class:`email.message.Message` or str :returns: absolute path of mail-file for Maildir or None if mail was successfully stored :rtype: str or None :raises: StoreMailError """ |
if not isinstance(mbx, mailbox.Mailbox):
logging.debug('Not a mailbox')
return False
mbx.lock()
if isinstance(mbx, mailbox.Maildir):
logging.debug('Maildir')
msg = mailbox.MaildirMessage(mail)
msg.set_flags('S')
else:
logging.debug('no Maildir')
msg = mailbox.Message(mail)
try:
message_id = mbx.add(msg)
mbx.flush()
mbx.unlock()
logging.debug('got mailbox msg id : %s', message_id)
except Exception as e:
raise StoreMailError(e)
path = None
# add new Maildir message to index and add tags
if isinstance(mbx, mailbox.Maildir):
# this is a dirty hack to get the path to the newly added file
# I wish the mailbox module were more helpful...
plist = glob.glob1(os.path.join(mbx._path, 'new'),
message_id + '*')
if plist:
path = os.path.join(mbx._path, 'new', plist[0])
logging.debug('path of saved msg: %s', path)
return path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def refresh(self, thread=None):
"""refresh thread metadata from the index""" |
if not thread:
thread = self._dbman._get_notmuch_thread(self._id)
self._total_messages = thread.get_total_messages()
self._notmuch_authors_string = thread.get_authors()
subject_type = settings.get('thread_subject')
if subject_type == 'notmuch':
subject = thread.get_subject()
elif subject_type == 'oldest':
try:
first_msg = list(thread.get_toplevel_messages())[0]
subject = first_msg.get_header('subject')
except IndexError:
subject = ''
self._subject = subject
self._authors = None
ts = thread.get_oldest_date()
try:
self._oldest_date = datetime.fromtimestamp(ts)
except ValueError: # year is out of range
self._oldest_date = None
try:
timestamp = thread.get_newest_date()
self._newest_date = datetime.fromtimestamp(timestamp)
except ValueError: # year is out of range
self._newest_date = None
self._tags = {t for t in thread.get_tags()}
self._messages = {} # this maps messages to its children
self._toplevel_messages = [] |
<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_tags(self, intersection=False):
""" returns tagsstrings attached to this thread :param intersection: return tags present in all contained messages instead of in at least one (union) :type intersection: bool :rtype: set of str """ |
tags = set(list(self._tags))
if intersection:
for m in self.get_messages().keys():
tags = tags.intersection(set(m.get_tags()))
return tags |
<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_tags(self, tags, afterwards=None, remove_rest=False):
""" add `tags` to all messages in this thread .. note:: This only adds the requested operation to this objects :class:`DBManager's <alot.db.DBManager>` write queue. You need to call :meth:`DBManager.flush <alot.db.DBManager.flush>` to actually write out. :param tags: a list of tags to be added :type tags: list of str :param afterwards: callback that gets called after successful application of this tagging operation :type afterwards: callable :param remove_rest: remove all other tags :type remove_rest: bool """ |
def myafterwards():
if remove_rest:
self._tags = set(tags)
else:
self._tags = self._tags.union(tags)
if callable(afterwards):
afterwards()
self._dbman.tag('thread:' + self._id, tags, afterwards=myafterwards,
remove_rest=remove_rest) |
<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_authors_string(self, own_accts=None, replace_own=None):
""" returns a string of comma-separated authors Depending on settings, it will substitute "me" for author name if address is user's own. :param own_accts: list of own accounts to replace :type own_accts: list of :class:`Account` :param replace_own: whether or not to actually do replacement :type replace_own: bool :rtype: str """ |
if replace_own is None:
replace_own = settings.get('thread_authors_replace_me')
if replace_own:
if own_accts is None:
own_accts = settings.get_accounts()
authorslist = []
for aname, aaddress in self.get_authors():
for account in own_accts:
if account.matches_address(aaddress):
aname = settings.get('thread_authors_me')
break
if not aname:
aname = aaddress
if aname not in authorslist:
authorslist.append(aname)
return ', '.join(authorslist)
else:
return self._notmuch_authors_string |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_messages(self):
""" returns all messages in this thread as dict mapping all contained messages to their direct responses. :rtype: dict mapping :class:`~alot.db.message.Message` to a list of :class:`~alot.db.message.Message`. """ |
if not self._messages: # if not already cached
query = self._dbman.query('thread:' + self._id)
thread = next(query.search_threads())
def accumulate(acc, msg):
M = Message(self._dbman, msg, thread=self)
acc[M] = []
r = msg.get_replies()
if r is not None:
for m in r:
acc[M].append(accumulate(acc, m))
return M
self._messages = {}
for m in thread.get_toplevel_messages():
self._toplevel_messages.append(accumulate(self._messages, m))
return self._messages |
<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_replies_to(self, msg):
""" returns all replies to the given message contained in this thread. :param msg: parent message to look up :type msg: :class:`~alot.db.message.Message` :returns: list of :class:`~alot.db.message.Message` or `None` """ |
mid = msg.get_message_id()
msg_hash = self.get_messages()
for m in msg_hash.keys():
if m.get_message_id() == mid:
return msg_hash[m]
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 matches(self, query):
""" Check if this thread matches the given notmuch query. :param query: The query to check against :type query: string :returns: True if this thread matches the given query, False otherwise :rtype: bool """ |
thread_query = 'thread:{tid} AND {subquery}'.format(tid=self._id,
subquery=query)
num_matches = self._dbman.count_messages(thread_query)
return num_matches > 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 lookup_command(cmdname, mode):
""" returns commandclass, argparser and forced parameters used to construct a command for `cmdname` when called in `mode`. :param cmdname: name of the command to look up :type cmdname: str :param mode: mode identifier :type mode: str :rtype: (:class:`Command`, :class:`~argparse.ArgumentParser`, dict(str->dict)) """ |
if cmdname in COMMANDS[mode]:
return COMMANDS[mode][cmdname]
elif cmdname in COMMANDS['global']:
return COMMANDS['global'][cmdname]
else:
return None, None, 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_selected_tag(self):
"""returns selected tagstring""" |
cols, _ = self.taglist.get_focus()
tagwidget = cols.original_widget.get_focus()
return tagwidget.tag |
<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_chart(chart, convert):
""" Convert string chart into text markup with the correct attributes. chart -- palette chart as a string convert -- function that converts a single palette entry to an (attr, text) tuple, or None if no match is found """ |
out = []
for match in re.finditer(ATTR_RE, chart):
if match.group('whitespace'):
out.append(match.group('whitespace'))
entry = match.group('entry')
entry = entry.replace("_", " ")
while entry:
# try the first four characters
attrtext = convert(entry[:SHORT_ATTR])
if attrtext:
elen = SHORT_ATTR
entry = entry[SHORT_ATTR:].strip()
else: # try the whole thing
attrtext = convert(entry.strip())
assert attrtext, "Invalid palette entry: %r" % entry
elen = len(entry)
entry = ""
attr, text = attrtext
out.append((attr, text.ljust(elen)))
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def foreground_chart(chart, background, colors):
""" Create text markup for a foreground colour chart chart -- palette chart as string background -- colour to use for background of chart colors -- number of colors (88 or 256) """ |
def convert_foreground(entry):
try:
attr = urwid.AttrSpec(entry, background, colors)
except urwid.AttrSpecError:
return None
return attr, entry
return parse_chart(chart, convert_foreground) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def background_chart(chart, foreground, colors):
""" Create text markup for a background colour chart chart -- palette chart as string foreground -- colour to use for foreground of chart colors -- number of colors (88 or 256) This will remap 8 <= colour < 16 to high-colour versions in the hopes of greater compatibility """ |
def convert_background(entry):
try:
attr = urwid.AttrSpec(foreground, entry, colors)
except urwid.AttrSpecError:
return None
# fix 8 <= colour < 16
if colors > 16 and attr.background_basic and \
attr.background_number >= 8:
# use high-colour with same number
entry = 'h%d'%attr.background_number
attr = urwid.AttrSpec(foreground, entry, colors)
return attr, entry
return parse_chart(chart, convert_background) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_string(partname, thread, maxw):
""" extract a content string for part 'partname' from 'thread' of maximal length 'maxw'. """ |
# map part names to function extracting content string and custom shortener
prep = {
'mailcount': (prepare_mailcount_string, None),
'date': (prepare_date_string, None),
'authors': (prepare_authors_string, shorten_author_string),
'subject': (prepare_subject_string, None),
'content': (prepare_content_string, None),
}
s = ' ' # fallback value
if thread:
# get extractor and shortener
content, shortener = prep[partname]
# get string
s = content(thread)
# sanitize
s = s.replace('\n', ' ')
s = s.replace('\r', '')
# shorten if max width is requested
if maxw:
if len(s) > maxw and shortener:
s = shortener(s, maxw)
else:
s = s[:maxw]
return s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reload(self):
"""Reload notmuch and alot config files""" |
self.read_notmuch_config(self._notmuchconfig.filename)
self.read_config(self._config.filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _expand_config_values(section, key):
""" Walker function for ConfigObj.walk Applies expand_environment_and_home to all configuration values that are strings (or strings that are elements of tuples/lists) :param section: as passed by ConfigObj.walk :param key: as passed by ConfigObj.walk """ |
def expand_environment_and_home(value):
"""
Expands environment variables and the home directory (~).
$FOO and ${FOO}-style environment variables are expanded, if they
exist. If they do not exist, they are left unchanged.
The exception are the following $XDG_* variables that are
expanded to fallback values, if they are empty or not set:
$XDG_CONFIG_HOME
$XDG_CACHE_HOME
:param value: configuration string
:type value: str
"""
xdg_vars = {'XDG_CONFIG_HOME': '~/.config',
'XDG_CACHE_HOME': '~/.cache'}
for xdg_name, fallback in xdg_vars.items():
if xdg_name in value:
xdg_value = get_xdg_env(xdg_name, fallback)
value = value.replace('$%s' % xdg_name, xdg_value)\
.replace('${%s}' % xdg_name, xdg_value)
return os.path.expanduser(os.path.expandvars(value))
value = section[key]
if isinstance(value, str):
section[key] = expand_environment_and_home(value)
elif isinstance(value, (list, tuple)):
new = list()
for item in value:
if isinstance(item, str):
new.append(expand_environment_and_home(item))
else:
new.append(item)
section[key] = new |
<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_accounts(config):
""" read accounts information from config :param config: valit alot config :type config: `configobj.ConfigObj` :returns: list of accounts """ |
accounts = []
if 'accounts' in config:
for acc in config['accounts'].sections:
accsec = config['accounts'][acc]
args = dict(config['accounts'][acc].items())
# create abook for this account
abook = accsec['abook']
logging.debug('abook defined: %s', abook)
if abook['type'] == 'shellcommand':
cmd = abook['command']
regexp = abook['regexp']
if cmd is not None and regexp is not None:
ef = abook['shellcommand_external_filtering']
args['abook'] = ExternalAddressbook(
cmd, regexp, external_filtering=ef)
else:
msg = 'underspecified abook of type \'shellcommand\':'
msg += '\ncommand: %s\nregexp:%s' % (cmd, regexp)
raise ConfigError(msg)
elif abook['type'] == 'abook':
contacts_path = abook['abook_contacts_file']
args['abook'] = AbookAddressBook(
contacts_path, ignorecase=abook['ignorecase'])
else:
del args['abook']
cmd = args['sendmail_command']
del args['sendmail_command']
newacc = SendmailAccount(cmd, **args)
accounts.append(newacc)
return accounts |
<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(self, key, fallback=None):
""" look up global config values from alot's config :param key: key to look up :type key: str :param fallback: fallback returned if key is not present :type fallback: str :returns: config value with type as specified in the spec-file """ |
value = None
if key in self._config:
value = self._config[key]
if isinstance(value, Section):
value = None
if value is None:
value = fallback
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 get_notmuch_setting(self, section, key, fallback=None):
""" look up config values from notmuch's config :param section: key is in :type section: str :param key: key to look up :type key: str :param fallback: fallback returned if key is not present :type fallback: str :returns: config value with type as specified in the spec-file """ |
value = None
if section in self._notmuchconfig:
if key in self._notmuchconfig[section]:
value = self._notmuchconfig[section][key]
if value is None:
value = fallback
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 get_theming_attribute(self, mode, name, part=None):
""" looks up theming attribute :type mode: str :param name: identifier of the atttribute :type name: str :rtype: urwid.AttrSpec """ |
colours = int(self._config.get('colourmode'))
return self._theme.get_attribute(colours, mode, name, part) |
<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_tagstring_representation(self, tag, onebelow_normal=None, onebelow_focus=None):
""" looks up user's preferred way to represent a given tagstring. :param tag: tagstring :type tag: str :param onebelow_normal: attribute that shines through if unfocussed :type onebelow_normal: urwid.AttrSpec :param onebelow_focus: attribute that shines through if focussed :type onebelow_focus: urwid.AttrSpec If `onebelow_normal` or `onebelow_focus` is given these attributes will be used as fallbacks for fg/bg values '' and 'default'. This returns a dictionary mapping :normal: to :class:`urwid.AttrSpec` used if unfocussed :focussed: to :class:`urwid.AttrSpec` used if focussed :translated: to an alternative string representation """ |
colourmode = int(self._config.get('colourmode'))
theme = self._theme
cfg = self._config
colours = [1, 16, 256]
def colourpick(triple):
""" pick attribute from triple (mono,16c,256c) according to current
colourmode"""
if triple is None:
return None
return triple[colours.index(colourmode)]
# global default attributes for tagstrings.
# These could contain values '' and 'default' which we interpret as
# "use the values from the widget below"
default_normal = theme.get_attribute(colourmode, 'global', 'tag')
default_focus = theme.get_attribute(colourmode, 'global', 'tag_focus')
# local defaults for tagstring attributes. depend on next lower widget
fallback_normal = resolve_att(onebelow_normal, default_normal)
fallback_focus = resolve_att(onebelow_focus, default_focus)
for sec in cfg['tags'].sections:
if re.match('^{}$'.format(sec), tag):
normal = resolve_att(colourpick(cfg['tags'][sec]['normal']),
fallback_normal)
focus = resolve_att(colourpick(cfg['tags'][sec]['focus']),
fallback_focus)
translated = cfg['tags'][sec]['translated']
translated = string_decode(translated, 'UTF-8')
if translated is None:
translated = tag
translation = cfg['tags'][sec]['translation']
if translation:
translated = re.sub(translation[0], translation[1], tag)
break
else:
normal = fallback_normal
focus = fallback_focus
translated = tag
return {'normal': normal, 'focussed': focus, 'translated': translated} |
<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_keybindings(self, mode):
"""look up keybindings from `MODE-maps` sections :param mode: mode identifier :type mode: str :returns: dictionaries of key-cmd for global and specific mode :rtype: 2-tuple of dicts """ |
globalmaps, modemaps = {}, {}
bindings = self._bindings
# get bindings for mode `mode`
# retain empty assignations to silence corresponding global mappings
if mode in bindings.sections:
for key in bindings[mode].scalars:
value = bindings[mode][key]
if isinstance(value, list):
value = ','.join(value)
modemaps[key] = value
# get global bindings
# ignore the ones already mapped in mode bindings
for key in bindings.scalars:
if key not in modemaps:
value = bindings[key]
if isinstance(value, list):
value = ','.join(value)
if value and value != '':
globalmaps[key] = value
# get rid of empty commands left in mode bindings
for k, v in list(modemaps.items()):
if not v:
del modemaps[k]
return globalmaps, modemaps |
<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_keybinding(self, mode, key):
"""look up keybinding from `MODE-maps` sections :param mode: mode identifier :type mode: str :param key: urwid-style key identifier :type key: str :returns: a command line to be applied upon keypress :rtype: str """ |
cmdline = None
bindings = self._bindings
if key in bindings.scalars:
cmdline = bindings[key]
if mode in bindings.sections:
if key in bindings[mode].scalars:
value = bindings[mode][key]
if value:
cmdline = value
else:
# to be sure it isn't mapped globally
cmdline = None
# Workaround for ConfigObj misbehaviour. cf issue #500
# this ensures that we get at least strings only as commandlines
if isinstance(cmdline, list):
cmdline = ','.join(cmdline)
return cmdline |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def computed(self):
""" Has the processes been computed since the last update of the kernel? """ |
return (
self._computed and
self.solver.computed and
(self.kernel is None or not self.kernel.dirty)
) |
<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_samples(self, t):
""" Parse a list of samples to make sure that it has the correct dimensions. :param t: ``(nsamples,)`` or ``(nsamples, ndim)`` The list of samples. If 1-D, this is assumed to be a list of one-dimensional samples otherwise, the size of the second dimension is assumed to be the dimension of the input space. Raises: ValueError: If the input dimension doesn't match the dimension of the kernel. """ |
t = np.atleast_1d(t)
# Deal with one-dimensional data.
if len(t.shape) == 1:
t = np.atleast_2d(t).T
# Double check the dimensions against the kernel.
if len(t.shape) != 2 or (self.kernel is not None and
t.shape[1] != self.kernel.ndim):
raise ValueError("Dimension mismatch")
return t |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute(self, x, yerr=0.0, **kwargs):
""" Pre-compute the covariance matrix and factorize it for a set of times and uncertainties. :param x: ``(nsamples,)`` or ``(nsamples, ndim)`` The independent coordinates of the data points. :param yerr: (optional) ``(nsamples,)`` or scalar The Gaussian uncertainties on the data points at coordinates ``x``. These values will be added in quadrature to the diagonal of the covariance matrix. """ |
# Parse the input coordinates and ensure the right memory layout.
self._x = self.parse_samples(x)
self._x = np.ascontiguousarray(self._x, dtype=np.float64)
try:
self._yerr2 = float(yerr)**2 * np.ones(len(x))
except TypeError:
self._yerr2 = self._check_dimensions(yerr) ** 2
self._yerr2 = np.ascontiguousarray(self._yerr2, dtype=np.float64)
# Set up and pre-compute the solver.
self.solver = self.solver_type(self.kernel, **(self.solver_kwargs))
# Include the white noise term.
yerr = np.sqrt(self._yerr2 + np.exp(self._call_white_noise(self._x)))
self.solver.compute(self._x, yerr, **kwargs)
self._const = -0.5 * (len(self._x) * np.log(2 * np.pi) +
self.solver.log_determinant)
self.computed = True
self._alpha = 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 recompute(self, quiet=False, **kwargs):
""" Re-compute a previously computed model. You might want to do this if the kernel parameters change and the kernel is labeled as ``dirty``. :param quiet: (optional) If ``True``, return false when the computation fails. Otherwise, throw an error if something goes wrong. (default: ``False``) """ |
if not self.computed:
if not (hasattr(self, "_x") and hasattr(self, "_yerr2")):
raise RuntimeError("You need to compute the model first")
try:
# Update the model making sure that we store the original
# ordering of the points.
self.compute(self._x, np.sqrt(self._yerr2), **kwargs)
except (ValueError, LinAlgError):
if quiet:
return False
raise
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 sample(self, t=None, size=1):
""" Draw samples from the prior distribution. :param t: ``(ntest, )`` or ``(ntest, ndim)`` (optional) The coordinates where the model should be sampled. If no coordinates are given, the precomputed coordinates and factorization are used. :param size: (optional) The number of samples to draw. (default: ``1``) Returns **samples** ``(size, ntest)``, a list of predictions at coordinates given by ``t``. If ``size == 1``, the result is a single sample with shape ``(ntest,)``. """ |
if t is None:
self.recompute()
n, _ = self._x.shape
# Generate samples using the precomputed factorization.
results = self.solver.apply_sqrt(np.random.randn(size, n))
results += self._call_mean(self._x)
return results[0] if size == 1 else results
x = self.parse_samples(t)
cov = self.get_matrix(x)
cov[np.diag_indices_from(cov)] += TINY
return multivariate_gaussian_samples(cov, size,
mean=self._call_mean(x)) |
<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_matrix(self, x1, x2=None):
""" Get the covariance matrix at a given set or two of independent coordinates. :param x1: ``(nsamples,)`` or ``(nsamples, ndim)`` A list of samples. :param x2: ``(nsamples,)`` or ``(nsamples, ndim)`` (optional) A second list of samples. If this is given, the cross covariance matrix is computed. Otherwise, the auto-covariance is evaluated. """ |
x1 = self.parse_samples(x1)
if x2 is None:
return self.kernel.get_value(x1)
x2 = self.parse_samples(x2)
return self.kernel.get_value(x1, x2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_library(compiler, libname):
"""Return a boolean indicating whether a library is found.""" |
with tempfile.NamedTemporaryFile("w", suffix=".cpp") as srcfile:
srcfile.write("int main (int argc, char **argv) { return 0; }")
srcfile.flush()
outfn = srcfile.name + ".so"
try:
compiler.link_executable(
[srcfile.name],
outfn,
libraries=[libname],
)
except setuptools.distutils.errors.LinkError:
return False
if not os.path.exists(outfn):
return False
os.remove(outfn)
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 compute(self, x, yerr):
""" Compute and factorize the covariance matrix. Args: x (ndarray[nsamples, ndim]):
The independent coordinates of the data points. yerr (ndarray[nsamples] or float):
The Gaussian uncertainties on the data points at coordinates ``x``. These values will be added in quadrature to the diagonal of the covariance matrix. """ |
# Compute the kernel matrix.
K = self.kernel.get_value(x)
K[np.diag_indices_from(K)] += yerr ** 2
# Factor the matrix and compute the log-determinant.
self._factor = (cholesky(K, overwrite_a=True, lower=False), False)
self.log_determinant = 2 * np.sum(np.log(np.diag(self._factor[0])))
self.computed = 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 apply_inverse(self, y, in_place=False):
r""" Apply the inverse of the covariance matrix to the input by solving .. math:: K\,x = y Args: y (ndarray[nsamples] or ndadrray[nsamples, nrhs]):
The vector or matrix :math:`y`. in_place (Optional[bool]):
Should the data in ``y`` be overwritten with the result :math:`x`? (default: ``False``) """ |
return cho_solve(self._factor, y, overwrite_b=in_place) |
<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_inverse(self):
""" Get the dense inverse covariance matrix. This is used for computing gradients, but it is not recommended in general. """ |
return self.apply_inverse(np.eye(len(self._factor[0])), in_place=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 get_parameter_dict(self, include_frozen=False):
""" Get an ordered dictionary of the parameters Args: include_frozen (Optional[bool]):
Should the frozen parameters be included in the returned value? (default: ``False``) """ |
return OrderedDict(zip(
self.get_parameter_names(include_frozen=include_frozen),
self.get_parameter_vector(include_frozen=include_frozen),
)) |
<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_parameter_names(self, include_frozen=False):
""" Get a list of the parameter names Args: include_frozen (Optional[bool]):
Should the frozen parameters be included in the returned value? (default: ``False``) """ |
if include_frozen:
return self.parameter_names
return tuple(p
for p, f in zip(self.parameter_names, self.unfrozen_mask)
if f) |
<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_parameter_bounds(self, include_frozen=False):
""" Get a list of the parameter bounds Args: include_frozen (Optional[bool]):
Should the frozen parameters be included in the returned value? (default: ``False``) """ |
if include_frozen:
return self.parameter_bounds
return list(p
for p, f in zip(self.parameter_bounds, self.unfrozen_mask)
if f) |
<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_parameter_vector(self, include_frozen=False):
""" Get an array of the parameter values in the correct order Args: include_frozen (Optional[bool]):
Should the frozen parameters be included in the returned value? (default: ``False``) """ |
if include_frozen:
return self.parameter_vector
return self.parameter_vector[self.unfrozen_mask] |
<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_parameter_vector(self, vector, include_frozen=False):
""" Set the parameter values to the given vector Args: vector (array[vector_size] or array[full_size]):
The target parameter vector. This must be in the same order as ``parameter_names`` and it should only include frozen parameters if ``include_frozen`` is ``True``. include_frozen (Optional[bool]):
Should the frozen parameters be included in the returned value? (default: ``False``) """ |
v = self.parameter_vector
if include_frozen:
v[:] = vector
else:
v[self.unfrozen_mask] = vector
self.parameter_vector = v
self.dirty = 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 freeze_parameter(self, name):
""" Freeze a parameter by name Args: name: The name of the parameter """ |
i = self.get_parameter_names(include_frozen=True).index(name)
self.unfrozen_mask[i] = False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def thaw_parameter(self, name):
""" Thaw a parameter by name Args: name: The name of the parameter """ |
i = self.get_parameter_names(include_frozen=True).index(name)
self.unfrozen_mask[i] = 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 get_parameter(self, name):
""" Get a parameter value by name Args: name: The name of the parameter """ |
i = self.get_parameter_names(include_frozen=True).index(name)
return self.get_parameter_vector(include_frozen=True)[i] |
<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_parameter(self, name, value):
""" Set a parameter value by name Args: name: The name of the parameter value (float):
The new value for the parameter """ |
i = self.get_parameter_names(include_frozen=True).index(name)
v = self.get_parameter_vector(include_frozen=True)
v[i] = value
self.set_parameter_vector(v, include_frozen=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 log_prior(self):
"""Compute the log prior probability of the current parameters""" |
for p, b in zip(self.parameter_vector, self.parameter_bounds):
if b[0] is not None and p < b[0]:
return -np.inf
if b[1] is not None and p > b[1]:
return -np.inf
return 0.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 multivariate_gaussian_samples(matrix, N, mean=None):
""" Generate samples from a multidimensional Gaussian with a given covariance. :param matrix: ``(k, k)`` The covariance matrix. :param N: The number of samples to generate. :param mean: ``(k,)`` (optional) The mean of the Gaussian. Assumed to be zero if not given. :returns samples: ``(k,)`` or ``(N, k)`` Samples from the given multivariate normal. """ |
if mean is None:
mean = np.zeros(len(matrix))
samples = np.random.multivariate_normal(mean, matrix, N)
if N == 1:
return samples[0]
return samples |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nd_sort_samples(samples):
""" Sort an N-dimensional list of samples using a KDTree. :param samples: ``(nsamples, ndim)`` The list of samples. This must be a two-dimensional array. :returns i: ``(nsamples,)`` The list of indices into the original array that return the correctly sorted version. """ |
# Check the shape of the sample list.
assert len(samples.shape) == 2
# Build a KD-tree on the samples.
tree = cKDTree(samples)
# Compute the distances.
d, i = tree.query(samples[0], k=len(samples))
return i |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def lookup_function(val):
"Look-up and return a pretty-printer that can print va."
type = val.type
if type.code == gdb.TYPE_CODE_REF:
type = type.target()
type = type.unqualified().strip_typedefs()
typename = type.tag
if typename == None:
return None
for function in pretty_printers_dict:
if function.search(typename):
return pretty_printers_dict[function](val)
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 serve_static(request, path, insecure=False, **kwargs):
"""Collect and serve static files. This view serves up static files, much like Django's :py:func:`~django.views.static.serve` view, with the addition that it collects static files first (if enabled). This allows images, fonts, and other assets to be served up without first loading a page using the ``{% javascript %}`` or ``{% stylesheet %}`` template tags. You can use this view by adding the following to any :file:`urls.py`:: urlpatterns += static('static/', view='pipeline.views.serve_static') """ |
# Follow the same logic Django uses for determining access to the
# static-serving view.
if not django_settings.DEBUG and not insecure:
raise ImproperlyConfigured("The staticfiles view can only be used in "
"debug mode or if the --insecure "
"option of 'runserver' is used")
if not settings.PIPELINE_ENABLED and settings.PIPELINE_COLLECTOR_ENABLED:
# Collect only the requested file, in order to serve the result as
# fast as possible. This won't interfere with the template tags in any
# way, as those will still cause Django to collect all media.
default_collector.collect(request, files=[path])
return serve(request, path, document_root=django_settings.STATIC_ROOT,
**kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compress_js(self, paths, templates=None, **kwargs):
"""Concatenate and compress JS files""" |
js = self.concatenate(paths)
if templates:
js = js + self.compile_templates(templates)
if not settings.DISABLE_WRAPPER:
js = settings.JS_WRAPPER % js
compressor = self.js_compressor
if compressor:
js = getattr(compressor(verbose=self.verbose), 'compress_js')(js)
return js |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compress_css(self, paths, output_filename, variant=None, **kwargs):
"""Concatenate and compress CSS files""" |
css = self.concatenate_and_rewrite(paths, output_filename, variant)
compressor = self.css_compressor
if compressor:
css = getattr(compressor(verbose=self.verbose), 'compress_css')(css)
if not variant:
return css
elif variant == "datauri":
return self.with_data_uri(css)
else:
raise CompressorError("\"%s\" is not a valid variant" % variant) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def template_name(self, path, base):
"""Find out the name of a JS template""" |
if not base:
path = os.path.basename(path)
if path == base:
base = os.path.dirname(path)
name = re.sub(r"^%s[\/\\]?(.*)%s$" % (
re.escape(base), re.escape(settings.TEMPLATE_EXT)
), r"\1", path)
return re.sub(r"[\/\\]", settings.TEMPLATE_SEPARATOR, 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 concatenate_and_rewrite(self, paths, output_filename, variant=None):
"""Concatenate together files and rewrite urls""" |
stylesheets = []
for path in paths:
def reconstruct(match):
quote = match.group(1) or ''
asset_path = match.group(2)
if NON_REWRITABLE_URL.match(asset_path):
return "url(%s%s%s)" % (quote, asset_path, quote)
asset_url = self.construct_asset_path(asset_path, path,
output_filename, variant)
return "url(%s)" % asset_url
content = self.read_text(path)
# content needs to be unicode to avoid explosions with non-ascii chars
content = re.sub(URL_DETECTOR, reconstruct, content)
stylesheets.append(content)
return '\n'.join(stylesheets) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def construct_asset_path(self, asset_path, css_path, output_filename, variant=None):
"""Return a rewritten asset URL for a stylesheet""" |
public_path = self.absolute_path(asset_path, os.path.dirname(css_path).replace('\\', '/'))
if self.embeddable(public_path, variant):
return "__EMBED__%s" % public_path
if not posixpath.isabs(asset_path):
asset_path = self.relative_path(public_path, output_filename)
return asset_path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def embeddable(self, path, variant):
"""Is the asset embeddable ?""" |
name, ext = os.path.splitext(path)
font = ext in FONT_EXTS
if not variant:
return False
if not (re.search(settings.EMBED_PATH, path.replace('\\', '/')) and self.storage.exists(path)):
return False
if ext not in EMBED_EXTS:
return False
if not (font or len(self.encoded_content(path)) < settings.EMBED_MAX_IMAGE_SIZE):
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 encoded_content(self, path):
"""Return the base64 encoded contents""" |
if path in self.__class__.asset_contents:
return self.__class__.asset_contents[path]
data = self.read_bytes(path)
self.__class__.asset_contents[path] = force_text(base64.b64encode(data))
return self.__class__.asset_contents[path] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mime_type(self, path):
"""Get mime-type from filename""" |
name, ext = os.path.splitext(path)
return MIME_TYPES[ext] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def absolute_path(self, path, start):
""" Return the absolute public path for an asset, given the path of the stylesheet that contains it. """ |
if posixpath.isabs(path):
path = posixpath.join(staticfiles_storage.location, path)
else:
path = posixpath.join(start, path)
return posixpath.normpath(path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def relative_path(self, absolute_path, output_filename):
"""Rewrite paths relative to the output stylesheet path""" |
absolute_path = posixpath.join(settings.PIPELINE_ROOT, absolute_path)
output_path = posixpath.join(settings.PIPELINE_ROOT, posixpath.dirname(output_filename))
return relpath(absolute_path, output_path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_bytes(self, path):
"""Read file content in binary mode""" |
file = staticfiles_storage.open(path)
content = file.read()
file.close()
return content |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_std_streams_blocking():
""" Set stdout and stderr to be blocking. This is called after Popen.communicate() to revert stdout and stderr back to be blocking (the default) in the event that the process to which they were passed manipulated one or both file descriptors to be non-blocking. """ |
if not fcntl:
return
for f in (sys.__stdout__, sys.__stderr__):
fileno = f.fileno()
flags = fcntl.fcntl(fileno, fcntl.F_GETFL)
fcntl.fcntl(fileno, fcntl.F_SETFL, flags & ~os.O_NONBLOCK) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute_command(self, command, cwd=None, stdout_captured=None):
"""Execute a command at cwd, saving its normal output at stdout_captured. Errors, defined as nonzero return code or a failure to start execution, will raise a CompilerError exception with a description of the cause. They do not write output. This is file-system safe (any valid file names are allowed, even with spaces or crazy characters) and OS agnostic (existing and future OSes that Python supports should already work). The only thing weird here is that any incoming command arg item may itself be a tuple. This allows compiler implementations to look clean while supporting historical string config settings and maintaining backwards compatibility. Thus, we flatten one layer deep. ((env, foocomp), infile, (-arg,)) -> (env, foocomp, infile, -arg) """ |
argument_list = []
for flattening_arg in command:
if isinstance(flattening_arg, string_types):
argument_list.append(flattening_arg)
else:
argument_list.extend(flattening_arg)
# The first element in argument_list is the program that will be executed; if it is '', then
# a PermissionError will be raised. Thus empty arguments are filtered out from argument_list
argument_list = list(filter(None, argument_list))
stdout = None
try:
# We always catch stdout in a file, but we may not have a use for it.
temp_file_container = cwd or os.path.dirname(stdout_captured or "") or os.getcwd()
with NamedTemporaryFile(delete=False, dir=temp_file_container) as stdout:
compiling = subprocess.Popen(argument_list, cwd=cwd,
stdout=stdout,
stderr=subprocess.PIPE)
_, stderr = compiling.communicate()
set_std_streams_blocking()
if compiling.returncode != 0:
stdout_captured = None # Don't save erroneous result.
raise CompilerError(
"{0!r} exit code {1}\n{2}".format(argument_list, compiling.returncode, stderr),
command=argument_list,
error_output=stderr)
# User wants to see everything that happened.
if self.verbose:
with open(stdout.name) as out:
print(out.read())
print(stderr)
except OSError as e:
stdout_captured = None # Don't save erroneous result.
raise CompilerError(e, command=argument_list,
error_output=text_type(e))
finally:
# Decide what to do with captured stdout.
if stdout:
if stdout_captured:
shutil.move(stdout.name, os.path.join(cwd or os.curdir, stdout_captured))
else:
os.remove(stdout.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 _get_css_files(cls, extra_files):
"""Return all CSS files from the Media class. Args: extra_files (dict):
The contents of the Media class's original :py:attr:`css` attribute, if one was provided. Returns: dict: The CSS media types and files to return for the :py:attr:`css` attribute. """ |
packager = Packager()
css_packages = getattr(cls, 'css_packages', {})
return dict(
(media_target,
cls._get_media_files(packager=packager,
media_packages=media_packages,
media_type='css',
extra_files=extra_files.get(media_target,
[])))
for media_target, media_packages in six.iteritems(css_packages)
) |
<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_js_files(cls, extra_files):
"""Return all JavaScript files from the Media class. Args: extra_files (list):
The contents of the Media class's original :py:attr:`js` attribute, if one was provided. Returns: list: The JavaScript files to return for the :py:attr:`js` attribute. """ |
return cls._get_media_files(
packager=Packager(),
media_packages=getattr(cls, 'js_packages', {}),
media_type='js',
extra_files=extra_files) |
<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_media_files(cls, packager, media_packages, media_type, extra_files):
"""Return source or output media files for a list of packages. This will go through the media files belonging to the provided list of packages referenced in a Media class and return the output files (if Pipeline is enabled) or the source files (if not enabled). Args: packager (pipeline.packager.Packager):
The packager responsible for media compilation for this type of package. media_packages (list of unicode):
The list of media packages referenced in Media to compile or return. extra_files (list of unicode):
The list of extra files to include in the result. This would be the list stored in the Media class's original :py:attr:`css` or :py:attr:`js` attributes. Returns: list: The list of media files for the given packages. """ |
source_files = list(extra_files)
if (not settings.PIPELINE_ENABLED and
settings.PIPELINE_COLLECTOR_ENABLED):
default_collector.collect()
for media_package in media_packages:
package = packager.package_for(media_type, media_package)
if settings.PIPELINE_ENABLED:
source_files.append(
staticfiles_storage.url(package.output_filename))
else:
source_files += packager.compile(package.paths)
return source_files |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_compressed(self, package, package_name, package_type):
"""Render HTML for the package. If ``PIPELINE_ENABLED`` is ``True``, this will render the package's output file (using :py:meth:`render_compressed_output`). Otherwise, this will render the package's source files (using :py:meth:`render_compressed_sources`). Subclasses can override this method to provide custom behavior for determining what to render. """ |
if settings.PIPELINE_ENABLED:
return self.render_compressed_output(package, package_name,
package_type)
else:
return self.render_compressed_sources(package, package_name,
package_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 render_compressed_output(self, package, package_name, package_type):
"""Render HTML for using the package's output file. Subclasses can override this method to provide custom behavior for rendering the output file. """ |
method = getattr(self, 'render_{0}'.format(package_type))
return method(package, package.output_filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_compressed_sources(self, package, package_name, package_type):
"""Render HTML for using the package's list of source files. Each source file will first be collected, if ``PIPELINE_COLLECTOR_ENABLED`` is ``True``. If there are any errors compiling any of the source files, an ``SHOW_ERRORS_INLINE`` is ``True``, those errors will be shown at the top of the page. Subclasses can override this method to provide custom behavior for rendering the source files. """ |
if settings.PIPELINE_COLLECTOR_ENABLED:
default_collector.collect(self.request)
packager = Packager()
method = getattr(self, 'render_individual_{0}'.format(package_type))
try:
paths = packager.compile(package.paths)
except CompilerError as e:
if settings.SHOW_ERRORS_INLINE:
method = getattr(self, 'render_error_{0}'.format(
package_type))
return method(package_name, e)
else:
raise
templates = packager.pack_templates(package)
return method(package, paths, templates=templates) |
<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(self, path, all=False):
""" Looks for files in PIPELINE.STYLESHEETS and PIPELINE.JAVASCRIPT """ |
matches = []
for elem in chain(settings.STYLESHEETS.values(), settings.JAVASCRIPT.values()):
if normpath(elem['output_filename']) == normpath(path):
match = safe_join(settings.PIPELINE_ROOT, path)
if not all:
return match
matches.append(match)
return matches |
<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(self, path, all=False):
""" Work out the uncached name of the file and look that up instead """ |
try:
start, _, extn = path.rsplit('.', 2)
except ValueError:
return []
path = '.'.join((start, extn))
return find(path, all=all) or [] |
<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(cls, attachment_public_uuid, custom_headers=None):
""" Get a specific attachment's metadata through its UUID. The Content-Type header of the response will describe the MIME type of the attachment file. :type api_context: context.ApiContext :type attachment_public_uuid: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseAttachmentPublic """ |
if custom_headers is None:
custom_headers = {}
api_client = client.ApiClient(cls._get_api_context())
endpoint_url = cls._ENDPOINT_URL_READ.format(attachment_public_uuid)
response_raw = api_client.get(endpoint_url, {}, custom_headers)
return BunqResponseAttachmentPublic.cast_from_bunq_response(
cls._from_json(response_raw, cls._OBJECT_TYPE_GET)
) |
<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(cls, tab_uuid, tab_attachment_tab_id, custom_headers=None):
""" Get a specific attachment. The header of the response contains the content-type of the attachment. :type api_context: context.ApiContext :type tab_uuid: str :type tab_attachment_tab_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseTabAttachmentTab """ |
if custom_headers is None:
custom_headers = {}
api_client = client.ApiClient(cls._get_api_context())
endpoint_url = cls._ENDPOINT_URL_READ.format(tab_uuid,
tab_attachment_tab_id)
response_raw = api_client.get(endpoint_url, {}, custom_headers)
return BunqResponseTabAttachmentTab.cast_from_bunq_response(
cls._from_json(response_raw, cls._OBJECT_TYPE_GET)
) |
<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(cls, amount, counterparty_alias, description, monetary_account_id=None, attachment=None, merchant_reference=None, allow_bunqto=None, custom_headers=None):
""" Create a new Payment. :type user_id: int :type monetary_account_id: int :param amount: The Amount to transfer with the Payment. Must be bigger than 0 and smaller than the MonetaryAccount's balance. :type amount: object_.Amount :param counterparty_alias: The Alias of the party we are transferring the money to. Can be an Alias of type EMAIL or PHONE_NUMBER (for bunq MonetaryAccounts or bunq.to payments) or IBAN (for external bank account). :type counterparty_alias: object_.Pointer :param description: The description for the Payment. Maximum 140 characters for Payments to external IBANs, 9000 characters for Payments to only other bunq MonetaryAccounts. Field is required but can be an empty string. :type description: str :param attachment: The Attachments to attach to the Payment. :type attachment: list[object_.AttachmentMonetaryAccountPayment] :param merchant_reference: Optional data to be included with the Payment specific to the merchant. :type merchant_reference: str :param allow_bunqto: Whether or not sending a bunq.to payment is allowed. :type allow_bunqto: bool :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ |
if custom_headers is None:
custom_headers = {}
request_map = {
cls.FIELD_AMOUNT: amount,
cls.FIELD_COUNTERPARTY_ALIAS: counterparty_alias,
cls.FIELD_DESCRIPTION: description,
cls.FIELD_ATTACHMENT: attachment,
cls.FIELD_MERCHANT_REFERENCE: merchant_reference,
cls.FIELD_ALLOW_BUNQTO: allow_bunqto
}
request_map_string = converter.class_to_json(request_map)
request_map_string = cls._remove_field_for_request(request_map_string)
api_client = client.ApiClient(cls._get_api_context())
request_bytes = request_map_string.encode()
endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(),
cls._determine_monetary_account_id(
monetary_account_id))
response_raw = api_client.post(endpoint_url, request_bytes,
custom_headers)
return BunqResponseInt.cast_from_bunq_response(
cls._process_for_id(response_raw)
) |
<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(cls, second_line, name_on_card, alias=None, type_=None, pin_code_assignment=None, monetary_account_id_fallback=None, custom_headers=None):
""" Create a new debit card request. :type user_id: int :param second_line: The second line of text on the card, used as name/description for it. It can contain at most 17 characters and it can be empty. :type second_line: str :param name_on_card: The user's name as it will be on the card. Check 'card-name' for the available card names for a user. :type name_on_card: str :param alias: The pointer to the monetary account that will be connected at first with the card. Its IBAN code is also the one that will be printed on the card itself. The pointer must be of type IBAN. :type alias: object_.Pointer :param type_: The type of card to order. Can be MAESTRO or MASTERCARD. :type type_: str :param pin_code_assignment: Array of Types, PINs, account IDs assigned to the card. :type pin_code_assignment: list[object_.CardPinAssignment] :param monetary_account_id_fallback: ID of the MA to be used as fallback for this card if insufficient balance. Fallback account is removed if not supplied. :type monetary_account_id_fallback: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseCardDebit """ |
if custom_headers is None:
custom_headers = {}
request_map = {
cls.FIELD_SECOND_LINE: second_line,
cls.FIELD_NAME_ON_CARD: name_on_card,
cls.FIELD_ALIAS: alias,
cls.FIELD_TYPE: type_,
cls.FIELD_PIN_CODE_ASSIGNMENT: pin_code_assignment,
cls.FIELD_MONETARY_ACCOUNT_ID_FALLBACK: monetary_account_id_fallback
}
request_map_string = converter.class_to_json(request_map)
request_map_string = cls._remove_field_for_request(request_map_string)
api_client = client.ApiClient(cls._get_api_context())
request_bytes = request_map_string.encode()
request_bytes = security.encrypt(cls._get_api_context(), request_bytes,
custom_headers)
endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id())
response_raw = api_client.post(endpoint_url, request_bytes,
custom_headers)
return BunqResponseCardDebit.cast_from_bunq_response(
cls._from_json(response_raw, cls._OBJECT_TYPE_POST)
) |
<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(cls, card_id, type_=None, custom_headers=None):
""" Generate a new CVC2 code for a card. :type user_id: int :type card_id: int :param type_: The type of generated cvc2. Can be STATIC or GENERATED. :type type_: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ |
if custom_headers is None:
custom_headers = {}
request_map = {
cls.FIELD_TYPE: type_
}
request_map_string = converter.class_to_json(request_map)
request_map_string = cls._remove_field_for_request(request_map_string)
api_client = client.ApiClient(cls._get_api_context())
request_bytes = request_map_string.encode()
request_bytes = security.encrypt(cls._get_api_context(), request_bytes,
custom_headers)
endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(),
card_id)
response_raw = api_client.post(endpoint_url, request_bytes,
custom_headers)
return BunqResponseInt.cast_from_bunq_response(
cls._process_for_id(response_raw)
) |
<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(cls, card_id, name_on_card=None, pin_code=None, second_line=None, custom_headers=None):
""" Request a card replacement. :type user_id: int :type card_id: int :param name_on_card: The user's name as it will be on the card. Check 'card-name' for the available card names for a user. :type name_on_card: str :param pin_code: The plaintext pin code. Requests require encryption to be enabled. :type pin_code: str :param second_line: The second line on the card. :type second_line: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ |
if custom_headers is None:
custom_headers = {}
request_map = {
cls.FIELD_NAME_ON_CARD: name_on_card,
cls.FIELD_PIN_CODE: pin_code,
cls.FIELD_SECOND_LINE: second_line
}
request_map_string = converter.class_to_json(request_map)
request_map_string = cls._remove_field_for_request(request_map_string)
api_client = client.ApiClient(cls._get_api_context())
request_bytes = request_map_string.encode()
request_bytes = security.encrypt(cls._get_api_context(), request_bytes,
custom_headers)
endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(),
card_id)
response_raw = api_client.post(endpoint_url, request_bytes,
custom_headers)
return BunqResponseInt.cast_from_bunq_response(
cls._process_for_id(response_raw)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(cls, card_id, pin_code=None, activation_code=None, status=None, card_limit=None, card_limit_atm=None, limit=None, mag_stripe_permission=None, country_permission=None, pin_code_assignment=None, primary_account_numbers_virtual=None, monetary_account_id_fallback=None, custom_headers=None):
""" Update the card details. Allow to change pin code, status, limits, country permissions and the monetary account connected to the card. When the card has been received, it can be also activated through this endpoint. :type user_id: int :type card_id: int :param pin_code: The plaintext pin code. Requests require encryption to be enabled. :type pin_code: str :param activation_code: DEPRECATED: Activate a card by setting status to ACTIVE when the order_status is ACCEPTED_FOR_PRODUCTION. :type activation_code: str :param status: The status to set for the card. Can be ACTIVE, DEACTIVATED, LOST, STOLEN or CANCELLED, and can only be set to LOST/STOLEN/CANCELLED when order status is ACCEPTED_FOR_PRODUCTION/DELIVERED_TO_CUSTOMER/CARD_UPDATE_REQUESTED/CARD_UPDATE_SENT/CARD_UPDATE_ACCEPTED. Can only be set to DEACTIVATED after initial activation, i.e. order_status is DELIVERED_TO_CUSTOMER/CARD_UPDATE_REQUESTED/CARD_UPDATE_SENT/CARD_UPDATE_ACCEPTED. Mind that all the possible choices (apart from ACTIVE and DEACTIVATED) are permanent and cannot be changed after. :type status: str :param card_limit: The spending limit for the card. :type card_limit: object_.Amount :param card_limit_atm: The ATM spending limit for the card. :type card_limit_atm: object_.Amount :param limit: DEPRECATED: The limits to define for the card, among CARD_LIMIT_CONTACTLESS, CARD_LIMIT_ATM, CARD_LIMIT_DIPPING and CARD_LIMIT_POS_ICC (e.g. 25 EUR for CARD_LIMIT_CONTACTLESS). All the limits must be provided on update. :type limit: list[object_.CardLimit] :param mag_stripe_permission: DEPRECATED: Whether or not it is allowed to use the mag stripe for the card. :type mag_stripe_permission: object_.CardMagStripePermission :param country_permission: The countries for which to grant (temporary) permissions to use the card. :type country_permission: list[object_.CardCountryPermission] :param pin_code_assignment: Array of Types, PINs, account IDs assigned to the card. :type pin_code_assignment: list[object_.CardPinAssignment] :param primary_account_numbers_virtual: Array of PANs, status, description and account id for online cards. :type primary_account_numbers_virtual: list[object_.CardVirtualPrimaryAccountNumber] :param monetary_account_id_fallback: ID of the MA to be used as fallback for this card if insufficient balance. Fallback account is removed if not supplied. :type monetary_account_id_fallback: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseCard """ |
if custom_headers is None:
custom_headers = {}
api_client = client.ApiClient(cls._get_api_context())
request_map = {
cls.FIELD_PIN_CODE: pin_code,
cls.FIELD_ACTIVATION_CODE: activation_code,
cls.FIELD_STATUS: status,
cls.FIELD_CARD_LIMIT: card_limit,
cls.FIELD_CARD_LIMIT_ATM: card_limit_atm,
cls.FIELD_LIMIT: limit,
cls.FIELD_MAG_STRIPE_PERMISSION: mag_stripe_permission,
cls.FIELD_COUNTRY_PERMISSION: country_permission,
cls.FIELD_PIN_CODE_ASSIGNMENT: pin_code_assignment,
cls.FIELD_PRIMARY_ACCOUNT_NUMBERS_VIRTUAL: primary_account_numbers_virtual,
cls.FIELD_MONETARY_ACCOUNT_ID_FALLBACK: monetary_account_id_fallback
}
request_map_string = converter.class_to_json(request_map)
request_map_string = cls._remove_field_for_request(request_map_string)
request_bytes = request_map_string.encode()
request_bytes = security.encrypt(cls._get_api_context(), request_bytes,
custom_headers)
endpoint_url = cls._ENDPOINT_URL_UPDATE.format(cls._determine_user_id(),
card_id)
response_raw = api_client.put(endpoint_url, request_bytes,
custom_headers)
return BunqResponseCard.cast_from_bunq_response(
cls._from_json(response_raw, cls._OBJECT_TYPE_PUT)
) |
<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(cls, card_id, custom_headers=None):
""" Return the details of a specific card. :type api_context: context.ApiContext :type user_id: int :type card_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseCard """ |
if custom_headers is None:
custom_headers = {}
api_client = client.ApiClient(cls._get_api_context())
endpoint_url = cls._ENDPOINT_URL_READ.format(cls._determine_user_id(),
card_id)
response_raw = api_client.get(endpoint_url, {}, custom_headers)
return BunqResponseCard.cast_from_bunq_response(
cls._from_json(response_raw, cls._OBJECT_TYPE_GET)
) |
<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(cls, name, status, avatar_uuid, monetary_account_id=None, location=None, notification_filters=None, tab_text_waiting_screen=None, custom_headers=None):
""" Create a new CashRegister. Only an UserCompany can create a CashRegisters. They need to be created with status PENDING_APPROVAL, an bunq admin has to approve your CashRegister before you can use it. In the sandbox testing environment an CashRegister will be automatically approved immediately after creation. :type user_id: int :type monetary_account_id: int :param name: The name of the CashRegister. Must be unique for this MonetaryAccount. :type name: str :param status: The status of the CashRegister. Can only be created or updated with PENDING_APPROVAL or CLOSED. :type status: str :param avatar_uuid: The UUID of the avatar of the CashRegister. Use the calls /attachment-public and /avatar to create a new Avatar and get its UUID. :type avatar_uuid: str :param location: The geolocation of the CashRegister. :type location: object_.Geolocation :param notification_filters: The types of notifications that will result in a push notification or URL callback for this CashRegister. :type notification_filters: list[object_.NotificationFilter] :param tab_text_waiting_screen: The tab text for waiting screen of CashRegister. :type tab_text_waiting_screen: list[object_.TabTextWaitingScreen] :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ |
if custom_headers is None:
custom_headers = {}
request_map = {
cls.FIELD_NAME: name,
cls.FIELD_STATUS: status,
cls.FIELD_AVATAR_UUID: avatar_uuid,
cls.FIELD_LOCATION: location,
cls.FIELD_NOTIFICATION_FILTERS: notification_filters,
cls.FIELD_TAB_TEXT_WAITING_SCREEN: tab_text_waiting_screen
}
request_map_string = converter.class_to_json(request_map)
request_map_string = cls._remove_field_for_request(request_map_string)
api_client = client.ApiClient(cls._get_api_context())
request_bytes = request_map_string.encode()
endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(),
cls._determine_monetary_account_id(
monetary_account_id))
response_raw = api_client.post(endpoint_url, request_bytes,
custom_headers)
return BunqResponseInt.cast_from_bunq_response(
cls._process_for_id(response_raw)
) |
<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(cls, cash_register_id, description, status, amount_total, monetary_account_id=None, allow_amount_higher=None, allow_amount_lower=None, want_tip=None, minimum_age=None, require_address=None, redirect_url=None, visibility=None, expiration=None, tab_attachment=None, custom_headers=None):
""" Create a TabUsageMultiple. On creation the status must be set to OPEN :type user_id: int :type monetary_account_id: int :type cash_register_id: int :param description: The description of the TabUsageMultiple. Maximum 9000 characters. Field is required but can be an empty string. :type description: str :param status: The status of the TabUsageMultiple. On creation the status must be set to OPEN. You can change the status from OPEN to PAYABLE. If the TabUsageMultiple gets paid the status will remain PAYABLE. :type status: str :param amount_total: The total amount of the Tab. Must be a positive amount. As long as the tab has the status OPEN you can change the total amount. This amount is not affected by the amounts of the TabItems. However, if you've created any TabItems for a Tab the sum of the amounts of these items must be equal to the total_amount of the Tab when you change its status to PAYABLE :type amount_total: object_.Amount :param allow_amount_higher: [DEPRECATED] Whether or not a higher amount can be paid. :type allow_amount_higher: bool :param allow_amount_lower: [DEPRECATED] Whether or not a lower amount can be paid. :type allow_amount_lower: bool :param want_tip: [DEPRECATED] Whether or not the user paying the Tab should be asked if he wants to give a tip. When want_tip is set to true, allow_amount_higher must also be set to true and allow_amount_lower must be false. :type want_tip: bool :param minimum_age: The minimum age of the user paying the Tab. :type minimum_age: int :param require_address: Whether a billing and shipping address must be provided when paying the Tab. Possible values are: BILLING, SHIPPING, BILLING_SHIPPING, NONE, OPTIONAL. Default is NONE. :type require_address: str :param redirect_url: The URL which the user is sent to after paying the Tab. :type redirect_url: str :param visibility: The visibility of a Tab. A Tab can be visible trough NearPay, the QR code of the CashRegister and its own QR code. :type visibility: object_.TabVisibility :param expiration: The moment when this Tab expires. Can be at most 365 days into the future. :type expiration: str :param tab_attachment: An array of attachments that describe the tab. Uploaded through the POST /user/{userid}/attachment-tab endpoint. :type tab_attachment: list[object_.BunqId] :type custom_headers: dict[str, str]|None :rtype: BunqResponseStr """ |
if custom_headers is None:
custom_headers = {}
request_map = {
cls.FIELD_DESCRIPTION: description,
cls.FIELD_STATUS: status,
cls.FIELD_AMOUNT_TOTAL: amount_total,
cls.FIELD_ALLOW_AMOUNT_HIGHER: allow_amount_higher,
cls.FIELD_ALLOW_AMOUNT_LOWER: allow_amount_lower,
cls.FIELD_WANT_TIP: want_tip,
cls.FIELD_MINIMUM_AGE: minimum_age,
cls.FIELD_REQUIRE_ADDRESS: require_address,
cls.FIELD_REDIRECT_URL: redirect_url,
cls.FIELD_VISIBILITY: visibility,
cls.FIELD_EXPIRATION: expiration,
cls.FIELD_TAB_ATTACHMENT: tab_attachment
}
request_map_string = converter.class_to_json(request_map)
request_map_string = cls._remove_field_for_request(request_map_string)
api_client = client.ApiClient(cls._get_api_context())
request_bytes = request_map_string.encode()
endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(),
cls._determine_monetary_account_id(
monetary_account_id),
cash_register_id)
response_raw = api_client.post(endpoint_url, request_bytes,
custom_headers)
return BunqResponseStr.cast_from_bunq_response(
cls._process_for_uuid(response_raw)
) |
<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(cls, device_server_id, custom_headers=None):
""" Get one of your DeviceServers. :type api_context: context.ApiContext :type device_server_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseDeviceServer """ |
if custom_headers is None:
custom_headers = {}
api_client = client.ApiClient(cls._get_api_context())
endpoint_url = cls._ENDPOINT_URL_READ.format(device_server_id)
response_raw = api_client.get(endpoint_url, {}, custom_headers)
return BunqResponseDeviceServer.cast_from_bunq_response(
cls._from_json(response_raw, cls._OBJECT_TYPE_GET)
) |
<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(cls, device_id, custom_headers=None):
""" Get a single Device. A Device is either a DevicePhone or a DeviceServer. :type api_context: context.ApiContext :type device_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseDevice """ |
if custom_headers is None:
custom_headers = {}
api_client = client.ApiClient(cls._get_api_context())
endpoint_url = cls._ENDPOINT_URL_READ.format(device_id)
response_raw = api_client.get(endpoint_url, {}, custom_headers)
return BunqResponseDevice.cast_from_bunq_response(
cls._from_json(response_raw)
) |
<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(cls, entries, number_of_required_accepts, monetary_account_id=None, status=None, previous_updated_timestamp=None, custom_headers=None):
""" Create a new DraftPayment. :type user_id: int :type monetary_account_id: int :param entries: The list of entries in the DraftPayment. Each entry will result in a payment when the DraftPayment is accepted. :type entries: list[object_.DraftPaymentEntry] :param number_of_required_accepts: The number of accepts that are required for the draft payment to receive status ACCEPTED. Currently only 1 is valid. :type number_of_required_accepts: int :param status: The status of the DraftPayment. :type status: str :param previous_updated_timestamp: The last updated_timestamp that you received for this DraftPayment. This needs to be provided to prevent race conditions. :type previous_updated_timestamp: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ |
if custom_headers is None:
custom_headers = {}
request_map = {
cls.FIELD_STATUS: status,
cls.FIELD_ENTRIES: entries,
cls.FIELD_PREVIOUS_UPDATED_TIMESTAMP: previous_updated_timestamp,
cls.FIELD_NUMBER_OF_REQUIRED_ACCEPTS: number_of_required_accepts
}
request_map_string = converter.class_to_json(request_map)
request_map_string = cls._remove_field_for_request(request_map_string)
api_client = client.ApiClient(cls._get_api_context())
request_bytes = request_map_string.encode()
endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(),
cls._determine_monetary_account_id(
monetary_account_id))
response_raw = api_client.post(endpoint_url, request_bytes,
custom_headers)
return BunqResponseInt.cast_from_bunq_response(
cls._process_for_id(response_raw)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(cls, draft_share_invite_api_key_id, status=None, sub_status=None, expiration=None, custom_headers=None):
""" Update a draft share invite. When sending status CANCELLED it is possible to cancel the draft share invite. :type user_id: int :type draft_share_invite_api_key_id: int :param status: The status of the draft share invite. Can be CANCELLED (the user cancels the draft share before it's used). :type status: str :param sub_status: The sub-status of the draft share invite. Can be NONE, ACCEPTED or REJECTED. :type sub_status: str :param expiration: The moment when this draft share invite expires. :type expiration: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseDraftShareInviteApiKey """ |
if custom_headers is None:
custom_headers = {}
api_client = client.ApiClient(cls._get_api_context())
request_map = {
cls.FIELD_STATUS: status,
cls.FIELD_SUB_STATUS: sub_status,
cls.FIELD_EXPIRATION: expiration
}
request_map_string = converter.class_to_json(request_map)
request_map_string = cls._remove_field_for_request(request_map_string)
request_bytes = request_map_string.encode()
endpoint_url = cls._ENDPOINT_URL_UPDATE.format(cls._determine_user_id(),
draft_share_invite_api_key_id)
response_raw = api_client.put(endpoint_url, request_bytes,
custom_headers)
return BunqResponseDraftShareInviteApiKey.cast_from_bunq_response(
cls._from_json(response_raw, cls._OBJECT_TYPE_PUT)
) |
<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(cls, request_inquiries, total_amount_inquired, monetary_account_id=None, status=None, event_id=None, custom_headers=None):
""" Create a request batch by sending an array of single request objects, that will become part of the batch. :type user_id: int :type monetary_account_id: int :param request_inquiries: The list of request inquiries we want to send in 1 batch. :type request_inquiries: list[RequestInquiry] :param total_amount_inquired: The total amount originally inquired for this batch. :type total_amount_inquired: object_.Amount :param status: The status of the request. :type status: str :param event_id: The ID of the associated event if the request batch was made using 'split the bill'. :type event_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ |
if custom_headers is None:
custom_headers = {}
request_map = {
cls.FIELD_REQUEST_INQUIRIES: request_inquiries,
cls.FIELD_STATUS: status,
cls.FIELD_TOTAL_AMOUNT_INQUIRED: total_amount_inquired,
cls.FIELD_EVENT_ID: event_id
}
request_map_string = converter.class_to_json(request_map)
request_map_string = cls._remove_field_for_request(request_map_string)
api_client = client.ApiClient(cls._get_api_context())
request_bytes = request_map_string.encode()
endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(),
cls._determine_monetary_account_id(
monetary_account_id))
response_raw = api_client.post(endpoint_url, request_bytes,
custom_headers)
return BunqResponseInt.cast_from_bunq_response(
cls._process_for_id(response_raw)
) |
<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(cls, amount_inquired, counterparty_alias, description, allow_bunqme, monetary_account_id=None, attachment=None, merchant_reference=None, status=None, minimum_age=None, require_address=None, want_tip=None, allow_amount_lower=None, allow_amount_higher=None, redirect_url=None, event_id=None, custom_headers=None):
""" Create a new payment request. :type user_id: int :type monetary_account_id: int :param amount_inquired: The Amount requested to be paid by the person the RequestInquiry is sent to. Must be bigger than 0. :type amount_inquired: object_.Amount :param counterparty_alias: The Alias of the party we are requesting the money from. Can be an Alias of type EMAIL, PHONE_NUMBER or IBAN. In case the EMAIL or PHONE_NUMBER Alias does not refer to a bunq monetary account, 'allow_bunqme' needs to be 'true' in order to trigger the creation of a bunq.me request. Otherwise no request inquiry will be sent. :type counterparty_alias: object_.Pointer :param description: The description for the RequestInquiry. Maximum 9000 characters. Field is required but can be an empty string. :type description: str :param allow_bunqme: Whether or not sending a bunq.me request is allowed. :type allow_bunqme: bool :param attachment: The Attachments to attach to the RequestInquiry. :type attachment: list[object_.BunqId] :param merchant_reference: Optional data to be included with the RequestInquiry specific to the merchant. Has to be unique for the same source MonetaryAccount. :type merchant_reference: str :param status: The status of the RequestInquiry. Ignored in POST requests but can be used for revoking (cancelling) the RequestInquiry by setting REVOKED with a PUT request. :type status: str :param minimum_age: The minimum age the user accepting the RequestInquiry must have. Defaults to not checking. If set, must be between 12 and 100 inclusive. :type minimum_age: int :param require_address: Whether a billing and shipping address must be provided when paying the request. Possible values are: BILLING, SHIPPING, BILLING_SHIPPING, NONE, OPTIONAL. Default is NONE. :type require_address: str :param want_tip: [DEPRECATED] Whether or not the accepting user can give an extra tip on top of the requested Amount. Defaults to false. :type want_tip: bool :param allow_amount_lower: [DEPRECATED] Whether or not the accepting user can choose to accept with a lower amount than requested. Defaults to false. :type allow_amount_lower: bool :param allow_amount_higher: [DEPRECATED] Whether or not the accepting user can choose to accept with a higher amount than requested. Defaults to false. :type allow_amount_higher: bool :param redirect_url: The URL which the user is sent to after accepting or rejecting the Request. :type redirect_url: str :param event_id: The ID of the associated event if the request was made using 'split the bill'. :type event_id: int :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ |
if custom_headers is None:
custom_headers = {}
request_map = {
cls.FIELD_AMOUNT_INQUIRED: amount_inquired,
cls.FIELD_COUNTERPARTY_ALIAS: counterparty_alias,
cls.FIELD_DESCRIPTION: description,
cls.FIELD_ATTACHMENT: attachment,
cls.FIELD_MERCHANT_REFERENCE: merchant_reference,
cls.FIELD_STATUS: status,
cls.FIELD_MINIMUM_AGE: minimum_age,
cls.FIELD_REQUIRE_ADDRESS: require_address,
cls.FIELD_WANT_TIP: want_tip,
cls.FIELD_ALLOW_AMOUNT_LOWER: allow_amount_lower,
cls.FIELD_ALLOW_AMOUNT_HIGHER: allow_amount_higher,
cls.FIELD_ALLOW_BUNQME: allow_bunqme,
cls.FIELD_REDIRECT_URL: redirect_url,
cls.FIELD_EVENT_ID: event_id
}
request_map_string = converter.class_to_json(request_map)
request_map_string = cls._remove_field_for_request(request_map_string)
api_client = client.ApiClient(cls._get_api_context())
request_bytes = request_map_string.encode()
endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(),
cls._determine_monetary_account_id(
monetary_account_id))
response_raw = api_client.post(endpoint_url, request_bytes,
custom_headers)
return BunqResponseInt.cast_from_bunq_response(
cls._process_for_id(response_raw)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(cls, request_inquiry_id, monetary_account_id=None, status=None, custom_headers=None):
""" Revoke a request for payment, by updating the status to REVOKED. :type user_id: int :type monetary_account_id: int :type request_inquiry_id: int :param status: The status of the RequestInquiry. Ignored in POST requests but can be used for revoking (cancelling) the RequestInquiry by setting REVOKED with a PUT request. :type status: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseRequestInquiry """ |
if custom_headers is None:
custom_headers = {}
api_client = client.ApiClient(cls._get_api_context())
request_map = {
cls.FIELD_STATUS: status
}
request_map_string = converter.class_to_json(request_map)
request_map_string = cls._remove_field_for_request(request_map_string)
request_bytes = request_map_string.encode()
endpoint_url = cls._ENDPOINT_URL_UPDATE.format(cls._determine_user_id(),
cls._determine_monetary_account_id(
monetary_account_id),
request_inquiry_id)
response_raw = api_client.put(endpoint_url, request_bytes,
custom_headers)
return BunqResponseRequestInquiry.cast_from_bunq_response(
cls._from_json(response_raw, cls._OBJECT_TYPE_PUT)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(cls, request_response_id, monetary_account_id=None, amount_responded=None, status=None, address_shipping=None, address_billing=None, custom_headers=None):
""" Update the status to accept or reject the RequestResponse. :type user_id: int :type monetary_account_id: int :type request_response_id: int :param amount_responded: The Amount the user decides to pay. :type amount_responded: object_.Amount :param status: The responding status of the RequestResponse. Can be ACCEPTED or REJECTED. :type status: str :param address_shipping: The shipping Address to return to the user who created the RequestInquiry. Should only be provided if 'require_address' is set to SHIPPING, BILLING_SHIPPING or OPTIONAL. :type address_shipping: object_.Address :param address_billing: The billing Address to return to the user who created the RequestInquiry. Should only be provided if 'require_address' is set to BILLING, BILLING_SHIPPING or OPTIONAL. :type address_billing: object_.Address :type custom_headers: dict[str, str]|None :rtype: BunqResponseRequestResponse """ |
if custom_headers is None:
custom_headers = {}
api_client = client.ApiClient(cls._get_api_context())
request_map = {
cls.FIELD_AMOUNT_RESPONDED: amount_responded,
cls.FIELD_STATUS: status,
cls.FIELD_ADDRESS_SHIPPING: address_shipping,
cls.FIELD_ADDRESS_BILLING: address_billing
}
request_map_string = converter.class_to_json(request_map)
request_map_string = cls._remove_field_for_request(request_map_string)
request_bytes = request_map_string.encode()
endpoint_url = cls._ENDPOINT_URL_UPDATE.format(cls._determine_user_id(),
cls._determine_monetary_account_id(
monetary_account_id),
request_response_id)
response_raw = api_client.put(endpoint_url, request_bytes,
custom_headers)
return BunqResponseRequestResponse.cast_from_bunq_response(
cls._from_json(response_raw, cls._OBJECT_TYPE_PUT)
) |
<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(cls, counter_user_alias, share_detail, status, monetary_account_id=None, draft_share_invite_bank_id=None, share_type=None, start_date=None, end_date=None, custom_headers=None):
""" Create a new share inquiry for a monetary account, specifying the permission the other bunq user will have on it. :type user_id: int :type monetary_account_id: int :param counter_user_alias: The pointer of the user to share with. :type counter_user_alias: object_.Pointer :param share_detail: The share details. Only one of these objects may be passed. :type share_detail: object_.ShareDetail :param status: The status of the share. Can be PENDING, REVOKED (the user deletes the share inquiry before it's accepted), ACCEPTED, CANCELLED (the user deletes an active share) or CANCELLATION_PENDING, CANCELLATION_ACCEPTED, CANCELLATION_REJECTED (for canceling mutual connects). :type status: str :param draft_share_invite_bank_id: The id of the draft share invite bank. :type draft_share_invite_bank_id: int :param share_type: The share type, either STANDARD or MUTUAL. :type share_type: str :param start_date: The start date of this share. :type start_date: str :param end_date: The expiration date of this share. :type end_date: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt """ |
if custom_headers is None:
custom_headers = {}
request_map = {
cls.FIELD_COUNTER_USER_ALIAS: counter_user_alias,
cls.FIELD_DRAFT_SHARE_INVITE_BANK_ID: draft_share_invite_bank_id,
cls.FIELD_SHARE_DETAIL: share_detail,
cls.FIELD_STATUS: status,
cls.FIELD_SHARE_TYPE: share_type,
cls.FIELD_START_DATE: start_date,
cls.FIELD_END_DATE: end_date
}
request_map_string = converter.class_to_json(request_map)
request_map_string = cls._remove_field_for_request(request_map_string)
api_client = client.ApiClient(cls._get_api_context())
request_bytes = request_map_string.encode()
endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(),
cls._determine_monetary_account_id(
monetary_account_id))
response_raw = api_client.post(endpoint_url, request_bytes,
custom_headers)
return BunqResponseInt.cast_from_bunq_response(
cls._process_for_id(response_raw)
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.