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 remote_upload(apikey, picture_url, resize=None, rotation='00', noexif=False): """ prepares post for remote upload :param str apikey: Apikey needed for Autentication on picflash. :param str picture_url: URL to picture allowd Protocols are: ftp, http, https :param str resize: Aresolution in the folowing format: \ '80x80'(optional) :param str|degree rotation: The picture will be rotated by this Value. \ Allowed values are 00, 90, 180, 270.(optional) :param boolean noexif: set to True when exif data should be purged.\ (optional) """
check_rotation(rotation) check_resize(resize) url = check_if_redirect(picture_url) if url: picture_url = resolve_redirect(url) post_data = compose_post(apikey, resize, rotation, noexif) post_data['url[]'] = ('', picture_url) return do_upload(post_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compose_post(apikey, resize, rotation, noexif): """ composes basic post requests """
check_rotation(rotation) check_resize(resize) post_data = { 'formatliste': ('', 'og'), 'userdrehung': ('', rotation), 'apikey': ('', apikey) } if resize and 'x' in resize: width, height = [ x.strip() for x in resize.split('x')] post_data['udefb'] = ('', width) post_data['udefh'] = ('', height) elif resize and '%' in resize: precentage = resize.strip().strip('%') post_data['udefp'] = precentage if noexif: post_data['noexif'] = ('', '') return post_data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_upload(post_data, callback=None): """ does the actual upload also sets and generates the user agent string """
encoder = MultipartEncoder(post_data) monitor = MultipartEncoderMonitor(encoder, callback) headers = {'User-Agent': USER_AGENT, 'Content-Type': monitor.content_type} response = post(API_URL, data=monitor, headers=headers) check_response(response) return response.json()[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 upload(self, picture, resize=None, rotation=None, noexif=None, callback=None): """ wraps upload function :param str/tuple/list picture: Path to picture as str or picture data. \ If data a tuple or list with the file name as str \ and data as byte object in that order. :param str resize: Aresolution in the folowing format: \ '80x80'(optional) :param str|degree rotation: The picture will be rotated by this Value.\ Allowed values are 00, 90, 180, 270.(optional) :param boolean noexif: set to True when exif data should be purged.\ (optional) :param function callback: function will be called after every read. \ Need to take one argument. you can use the len function to \ determine the body length and call bytes_read(). """
if not resize: resize = self._resize if not rotation: rotation = self._rotation if not noexif: noexif = self._noexif if not callback: callback = self._callback return upload(self._apikey, picture, resize, rotation, noexif, callback)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remote_upload(self, picture_url, resize=None, rotation=None, noexif=None): """ wraps remote_upload funktion :param str picture_url: URL to picture allowd Protocols are: ftp,\ http, https :param str resize: Aresolution in the folowing format: \ '80x80'(optional) :param str|degree rotation: The picture will be rotated by this Value. \ Allowed values are 00, 90, 180, 270.(optional) :param boolean noexif: set to True when exif data should be purged.\ (optional) """
if not resize: resize = self._resize if not rotation: rotation = self._rotation if not noexif: noexif = self._noexif return remote_upload(self._apikey, picture_url, resize, rotation, noexif)
<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_identity(config = Config()): """Load the default identity from the configuration. If there is no default identity, a KeyError is raised. """
return Identity(name = config.get('user', 'name'), email_ = config.get('user', 'email'), **config.get_section('smtp'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _smtp_server(self): """Return a smtplib SMTP object correctly initialised and connected to a SMTP server suitable for sending email on behalf of the user."""
if self._use_ssl: server = smtplib.SMTP_SSL(**self._smtp_vars) else: server = smtplib.SMTP(**self._smtp_vars) if self._use_tls: server.starttls() if self._credentials is not None: passwd = self._credentials[1] if passwd is None: passwd = self._interface.input( \ 'Password for %s' % (self._credentials[0],), no_echo=True) server.login(*self._credentials) # if we succeeded, cache the password self._credentials = (self._credentials[0], passwd) return server
<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_clients(session, verbose): """Add clients to the ATVS Keystroke database."""
for ctype in ['Genuine', 'Impostor']: for cdid in userid_clients: cid = ctype + '_%d' % cdid if verbose>1: print(" Adding user '%s' of type '%s'..." % (cid, ctype)) session.add(Client(cid, ctype, cdid))
<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_files(session, imagedir, verbose): """Add files to the ATVS Keystroke database."""
def add_file(session, basename, userid, shotid, sessionid): """Parse a single filename and add it to the list.""" session.add(File(userid, basename, sessionid, shotid)) filenames = os.listdir(imagedir) for filename in filenames: basename, extension = os.path.splitext(filename) if extension == db_file_extension: if verbose>1: print(" Adding file '%s'..." % (basename)) parts = string.split(basename, "_") ctype = parts[0] shotid = int(parts[2]) userid = ctype + '_%d' % int(parts[1]) if parts[0] == "Impostor": sessionid = 3 elif parts[0] == "Genuine" and shotid <= 6: sessionid = 1 elif parts[0] == "Genuine" and shotid > 6: sessionid = 2 shotid = shotid - 6 add_file(session, basename, userid, shotid, sessionid)
<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(args): """Creates or re-creates this database"""
from bob.db.utils import session_try_nolock dbfile = args.files[0] if args.recreate: if args.verbose and os.path.exists(dbfile): print('unlinking %s...' % dbfile) if os.path.exists(dbfile): os.unlink(dbfile) if not os.path.exists(os.path.dirname(dbfile)): os.makedirs(os.path.dirname(dbfile)) # the real work... create_tables(args) s = session_try_nolock(args.type, dbfile, echo=(args.verbose > 2)) add_clients(s, args.verbose) add_files(s, args.imagedir, args.verbose) add_protocols(s, args.verbose) s.commit() s.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_command(subparsers): """Add specific subcommands that the action "create" can use"""
parser = subparsers.add_parser('create', help=create.__doc__) parser.add_argument('-R', '--recreate', action='store_true', help="If set, I'll first erase the current database") parser.add_argument('-v', '--verbose', action='count', help="Do SQL operations in a verbose way?") parser.add_argument('-D', '--imagedir', metavar='DIR', default='/home/bob/BTAS_Keystroke_files_SingleFile', help="Change the relative path to the directory containing the images of the ATVS Keystroke database.") parser.set_defaults(func=create)
<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_args(self, accept_unrecognized_args=False): """ Invoke the argument parser. """
# If the user provided a description, use it. Otherwise grab the doc string. if self.description: self.argparser.description = self.description elif getattr(sys.modules['__main__'], '__doc__', None): self.argparser.description = getattr(sys.modules['__main__'], '__doc__') else: self.argparser.description = 'No documentation defined. Please add a doc string to %s' % sys.modules['__main__'].__file__ self.argparser.epilog = self.epilog # Only if there aren't any other command line arguments. if len(sys.argv) == 1 and self.argument_defaults: self.argparser.set_defaults(**self.argument_defaults) if accept_unrecognized_args: self.args, self.unrecognized_args = self.argparser.parse_known_args() else: self.args = self.argparser.parse_args()
<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_config(self): """ Invoke the config file parser. """
if self.should_parse_config and (self.args.config or self.config_file): self.config = ConfigParser.SafeConfigParser() self.config.read(self.args.config or self.config_file)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __process_username_password(self): """ If indicated, process the username and password """
if self.use_username_password_store is not None: if self.args.clear_store: with load_config(sections=AUTH_SECTIONS) as config: config.remove_option(AUTH_SECTION, 'username') if not self.args.username: self.args.username = get_username(use_store=self.use_username_password_store) if self.args.clear_store: remove_password(AUTH_SECTION, username=self.args.username) if not self.args.password: self.args.password = get_password(AUTH_SECTION, username=self.args.username) if self.use_username_password_store: save_password(AUTH_SECTION, self.args.password, self.args.username)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __finish_initializing(self): """ Handle any initialization after arguments & config has been parsed. """
if self.args.debug or self.args.trace: # Set the console (StreamHandler) to allow debug statements. if self.args.debug: self.console.setLevel(logging.DEBUG) self.console.setFormatter(logging.Formatter('[%(levelname)s] %(asctime)s %(name)s - %(message)s')) # Set the global level to debug. if self.args.debug: self.log.setLevel(logging.DEBUG) if self.args.log or self.log_file: # Allow the user to override the default log file handler. try: self.log_file_handler = sys.modules['__main__'].log_file_handler(self.args.log or self.log_file) except Exception: self.log_file_handler = logging.FileHandler(self.args.log or self.log_file) self.log_file_handler.setFormatter(logging.Formatter('[%(levelname)s] %(asctime)s %(name)s - %(message)s')) self.log_file_handler.setLevel(logging.DEBUG) self.log.addHandler(self.log_file_handler) # Allow cli.log, args & self to be accessed from __main__ if not hasattr(sys.modules['__main__'], 'log'): sys.modules['__main__'].log = self.log if not hasattr(sys.modules['__main__'], 'cli'): sys.modules['__main__'].cli = self if not hasattr(sys.modules['__main__'], 'args'): sys.modules['__main__'].args = self.args
<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_item(self, item_number, raw=False): """ Get a dictionary or object with info about the given item number from the Hacker News API. Item can be a poll, story, comment or possibly other entry. Will raise an requests.HTTPError if we got a non-200 response back. Will raise a ValueError if a item_number that can not be converted to int was passed in, or the server has no information for that item number. (Possible) response parameters: "id" -> The item's unique id. Required. "deleted" -> true if the item is deleted. "type" -> The type of item. One of "job", "story", "comment", "poll", or "pollopt". "by" -> The username of the item's author. "time" -> Creation date of the item, in Unix Time. "text" -> The comment, Ask HN, or poll text. HTML. "dead" -> true if the item is dead. "parent" -> The item's parent. For comments, either another comment or the relevant story. For pollopts, the relevant poll. "kids" -> The ids of the item's comments, in ranked display order. "url" -> The URL of the story. "score" -> The story's score, or the votes for a pollopt. "title" -> The title of the story or poll. "parts" -> A list of related pollopts, in display order. :param item_number: an integer number for the HN item requested :param raw: (optional): If true, return the raw decoded JSON dict, if False, return a nice object with keywords as attributes. Default if False. :return: A dictionary with relevant info about the item, if successful. """
if not isinstance(item_number, int): item_number = int(item_number) suburl = "v0/item/{}.json".format(item_number) try: item_data = self._make_request(suburl) except requests.HTTPError as e: hn_logger.exception('Faulted on item request for item {}, with status {}'.format(item_number, e.errno)) raise e if not item_data: raise ValueError('Item id {} not found!'.format(item_number)) return item_data if raw else HackerNewsItem(**item_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_user(self, user_name, raw=False): """ Get a dictionary or object with info about the given user from the Hacker News API. Will raise an requests.HTTPError if we got a non-200 response back. Response parameters: "id' -> The user's unique username. Case-sensitive. Required. "delay" -> Delay in minutes between a comment's creation and its visibility to other users. "created" -> Creation date of the user, in Unix Time. "karma" -> The user's karma. "about" -> The user's optional self-description. HTML. "submitted" -> List of the user's stories, polls and comments. :param user_name: the relevant user's name :param raw: (optional): If true, return the raw decoded JSON dict, if False, return a nice object with keywords as attributes. Default if False. :return: A dictionary with relevant info about the user, if successful. """
suburl = "v0/user/{}.json".format(user_name) try: user_data = self._make_request(suburl) except requests.HTTPError as e: hn_logger.exception('Faulted on item request for user {}, with status {}'.format(user_name, e.errno)) raise e if not user_data: raise ValueError('User name {} not found, or no data!'.format(user_name)) return user_data if raw else HackerNewsUpdates(**user_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_recent_updates(self, raw=True): """ Get the most recent updates on Hacker News Response dictionary parameters: "items" -> A list of the most recently update items by item number. "profiles" -> A list of most recently updated user profiles by user name. :param raw: (optional): If true, return the raw dictionary, if False, return a nice object with attrs for keywords. Default is True. :return: A dictionary with relevant info about recent updates. """
suburl = "v0/updates.json" try: updates_data = self._make_request(suburl) except requests.HTTPError as e: hn_logger.exception('Faulted on get max item, with status {}'.format(e.errno)) raise e return updates_data if raw else HackerNewsUpdates(**updates_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_server(): """Creates an EC2 Server"""
try: import boto except ImportError: sys.exit("boto library required for creating servers with Amazon.") print(green("Creating EC2 server")) conn = boto.connect_ec2( get_or_prompt('ec2_key', 'API Key'), get_or_prompt('ec2_secret', 'API Secret')) reservation = conn.run_instances( get_or_prompt( 'ec2_ami', 'AMI ID', 'ami-fd589594'), instance_type=get_or_prompt( 'ec2_instancetype', 'Instance Type', 't1.micro'), key_name=get_or_prompt( 'ec2_keypair', 'Key Pair'), security_groups=get_or_prompt_list( 'ec2_secgroups', 'Security Groups')) instance = reservation.instances[0] time.sleep(3) tag = get_or_prompt('ec2_tag', 'Instance Tag (blank for none)', '').strip() if len(tag) > 0: conn.create_tags([instance.id], {"Name": tag}) while instance.state != u'running': print(yellow("Instance state: %s" % instance.state)) time.sleep(10) instance.update() print(green("Instance state: %s" % instance.state)) print(green("Public dns: %s" % instance.public_dns_name)) print(green("Waiting 30 seconds for server to boot")) time.sleep(30) return instance.public_dns_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 return_time_elements(time_stamp): """Returns formatted strings of time stamps for HTML requests. :parameters time_range: pandas.tslib.Timestamp """
yyyy = str(time_stamp.year) mm = "%02d" % (time_stamp.month,) dd = "%02d" % (time_stamp.day,) hr = "%02d" % (time_stamp.hour,) mins = "%02d" % (time_stamp.minute,) return yyyy, mm, dd, hr, mins
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fromConfigFile(filename = DEFAULT_CONFIG_FILE): """ Read settings from configuration file"""
parser = SafeConfigParser() section = 'fenixedu' parser.read(filename) client_id = parser.get(section, 'client_id') redirect_uri = parser.get(section, 'redirect_uri') client_secret = parser.get(section, 'client_secret') base_url = parser.get(section, 'base_url') api_endpoint = parser.get(section, 'api_endpoint') api_version = parser.get(section, 'api_version') return FenixEduConfiguration(client_id = client_id, redirect_uri = redirect_uri, client_secret = client_secret, base_url = base_url, api_endpoint = api_endpoint, api_version = api_version)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def map_subcommands(self, func): """ Run `func` against all the subcommands attached to our root command. """
def crawl(cmd): for sc in cmd.subcommands.values(): yield from crawl(sc) yield cmd return map(func, crawl(self.root_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 handle_command_error(self, command, args, exc): """ Depending on how the session is configured this will print information about an unhandled command exception or possibly jump to some other behavior like a debugger. """
verbosity = self.command_error_verbosity if verbosity == 'traceback': self.pretty_print_exc(command, exc, show_traceback=True) elif verbosity == 'debug': pdb.set_trace() elif verbosity == 'raise': raise exc elif verbosity == 'pretty': self.pretty_print_exc(command, exc) else: raise ValueError('Unexpected exception_verbosity: %s' % verbosity)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def complete_wrap(self, func, *args, **kwargs): """ Readline eats exceptions raised by completer functions. """
# Workaround readline's one-time-read of terminal width. termcols = shutil.get_terminal_size()[0] readline.parse_and_bind('set completion-display-width %d' % termcols) try: return func(*args, **kwargs) except: traceback.print_exc() raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_readline(self): """ Configure our tab completion settings for a context and then restore them to previous settings on exit. """
readline.parse_and_bind('tab: complete') completer_save = readline.get_completer() delims_save = readline.get_completer_delims() delims = set(delims_save) delims |= self.completer_delim_includes delims -= self.completer_delim_excludes readline.set_completer(self.completer_hook) try: readline.set_completer_delims(''.join(delims)) try: yield finally: readline.set_completer_delims(delims_save) finally: readline.set_completer(completer_save)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_loop(self): """ Main entry point for running in interactive mode. """
self.root_command.prog = '' history_file = self.load_history() rendering.vtmlprint(self.intro) try: self.loop() finally: readline.write_history_file(history_file)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loop(self): """ Inner loop for interactive mode. Do not call directly. """
while True: with self.setup_readline(): try: line = input(self.prompt) except EOFError: _vprinterr('^D') break except KeyboardInterrupt: _vprinterr('^C') continue if not line.strip(): continue try: cmd, args = self.cmd_split(line) except KeyError as e: _vprinterr('<red>Invalid command: %s</red>' % e) continue try: cmd(argv=args) except SessionExit: break except SystemExit as e: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sqldelete(table, where): ('delete from t where id=%s', [5]) """
validate_name(table) (whereclause, wherevalues) = sqlwhere(where) sql = "delete from {}".format(table) if whereclause: sql += " where " + whereclause return (sql, wherevalues)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select(self, table, fields=['*'], where=None, orderby=None, limit=None, offset=None): """ Query and return list of records. 1 {'id': 1, 'name': 'Toto'} """
(sql, values) = sqlselect(table, fields, where, orderby, limit, offset) self.execute(sql, values) return self.fetchall()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert(self, table, row): """ Add new row. Row must be a dict or implement the mapping interface. 1 {'id': 1, 'name': 'Toto'} """
(sql, values) = sqlinsert(table, row) self.execute(sql, values)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def one(iterable, cmp=None): """ Return the object in the given iterable that evaluates to True. If the given iterable has more than one object that evaluates to True, or if there is no object that fulfills such condition, return False. If a callable ``cmp`` is given, it's used to evaluate each element. True False 'a' False False True 42 """
the_one = False for i in iterable: if cmp(i) if cmp else i: if the_one: return False the_one = i return the_one
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_command(self, name, command): """ Registers the `command` with the given `name`. If the `name` has already been used to register a command a :exc:`RuntimeError` will be raised. """
if name in self.commands: raise RuntimeError('%s is already defined' % name) self.commands[name] = 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 wordify(text): """Generate a list of words given text, removing punctuation. Parameters text : unicode A piece of english text. Returns ------- words : list List of words. """
stopset = set(nltk.corpus.stopwords.words('english')) tokens = nltk.WordPunctTokenizer().tokenize(text) return [w for w in tokens if w not in stopset]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initialize_env(env_file=None, fail_silently=True, load_globally=True): """ Returns an instance of _Environment after reading the system environment an optionally provided file. """
data = {} data.update(os.environ) if env_file: data.update(read_file_values(env_file, fail_silently)) if load_globally: os.environ.update(data) return Environment(env_dict=data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup(sphinx): """Setup Sphinx object."""
from flask import has_app_context from invenio_base.factory import create_app PACKAGES = ['invenio_base', 'invenio.modules.accounts', 'invenio.modules.records', 'invenio_knowledge'] if not has_app_context(): app = create_app(PACKAGES=PACKAGES) ctx = app.test_request_context('/') ctx.push()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pretty_spaces(level): """ Return spaces and new line. :type level: int or None :param level: deep level :rtype: unicode :return: string with new line and spaces """
if level is None: return u'' return (os.linesep if level >= 0 else u'') + (u' ' * (INDENT * level))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unimapping(arg, level): """ Mapping object to unicode string. :type arg: collections.Mapping :param arg: mapping object :type level: int :param level: deep level :rtype: unicode :return: mapping object as unicode string """
if not isinstance(arg, collections.Mapping): raise TypeError( 'expected collections.Mapping, {} received'.format(type(arg).__name__) ) result = [] for i in arg.items(): result.append( pretty_spaces(level) + u': '.join(map(functools.partial(convert, level=level), i)) ) string = join_strings(result, level) if level is not None: string += pretty_spaces(level - 1) return u'{{{}}}'.format(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 uniiterable(arg, level): """ Iterable object to unicode string. :type arg: collections.Iterable :param arg: iterable object :type level: int :param level: deep level :rtype: unicode :return: iterable object as unicode string """
if not isinstance(arg, collections.Iterable): raise TypeError( 'expected collections.Iterable, {} received'.format(type(arg).__name__) ) templates = { list: u'[{}]', tuple: u'({})' } result = [] for i in arg: result.append(pretty_spaces(level) + convert(i, level=level)) string = join_strings(result, level) if level is not None: string += pretty_spaces(level - 1) return templates.get(type(arg), templates[tuple]).format(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 convert(obj, encoding=LOCALE, level=None): """ Covert any object to unicode string. :param obj: any object :type encoding: str :param encoding: codec for encoding unicode strings (locale.getpreferredencoding() by default) :type level: int :param level: Deep level. If None level is not considered. :rtype: unicode :return: any object as unicode string """
callable_ = CONVERTERS.get(type(obj)) if callable_ is not None: obj = callable_(obj) func = lambda x, level: compat.template.format(x) if isinstance(obj, compat.UnicodeType): # skip if condition, because unicode is a iterable type pass elif isinstance(obj, str): func = lambda x, level: u"'{}'".format(x.decode(encoding)) elif isinstance(obj, (bytearray, bytes)): func = lambda x, level: u"b'{}'".format( u''.join(u'\\x{:02x}'.format(b) for b in x) ) elif isinstance(obj, (type(None), int, float)): func = lambda x, level: compat.UnicodeType(x) elif isinstance(obj, (types.GeneratorType, compat.XRangeType)): func = lambda x, level: u"'{!r}'".format(x) elif isinstance(obj, collections.Mapping): func = unimapping elif isinstance(obj, collections.Iterable): func = uniiterable if level is not None: level += 1 return func(obj, level)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show(ctx, city, date): """Show a particular meetup. city: The meetup series. \b date: The date. May be: - YYYY-MM-DD or YY-MM-DD (e.g. 2015-08-27) - YYYY-MM or YY-MM (e.g. 2015-08) - MM (e.g. 08): the given month in the current year - pN (e.g. p1): show the N-th last meetup - +N (e.g. +2): show the N-th next meetup - Omitted: show the next meetup (same as +1) """
db = ctx.obj['db'] today = ctx.obj['now'].date() term = ctx.obj['term'] event = cliutil.get_event(db, city, date, today) data = event.as_dict() cliutil.handle_raw_output(ctx, data) render_event(term, event, today, verbose=ctx.obj['verbose'])
<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_list_fields(self): """Get all list fields"""
from trionyx.renderer import renderer model_fields = {f.name: f for f in self.model.get_fields(True, True)} def create_list_fields(config_fields, list_fields=None): list_fields = list_fields if list_fields else {} for field in config_fields: config = field if isinstance(field, str): config = {'field': field} if 'field' not in config: raise Exception("Field config is missing field: {}".format(config)) if 'label' not in config: if config['field'] in model_fields: config['label'] = model_fields[config['field']].verbose_name else: config['label'] = config['field'] if 'renderer' not in config: config['renderer'] = renderer.render_field list_fields[config['field']] = config return list_fields list_fields = create_list_fields(model_fields.keys()) if self.list_fields: list_fields = create_list_fields(self.list_fields, list_fields) return list_fields
<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_form(self, config_name, only_required=False): """Get form for given config else create form"""
if getattr(self, config_name, None): return import_object_by_string(getattr(self, config_name)) def use_field(field): if not only_required: return True return field.default == NOT_PROVIDED return modelform_factory(self.model, fields=[f.name for f in self.model.get_fields() if use_field(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 auto_load_configs(self): """Auto load all configs from app configs"""
for app in apps.get_app_configs(): for model in app.get_models(): config = ModelConfig(model, getattr(app, model.__name__, None)) self.configs[self.get_model_name(model)] = config
<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_config(self, model): """Get config for given model"""
if not inspect.isclass(model): model = model.__class__ return self.configs.get(self.get_model_name(model))
<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_all_configs(self, trionyx_models_only=True): """Get all model configs"""
from trionyx.models import BaseModel for index, config in self.configs.items(): if not isinstance(config.model(), BaseModel): continue yield config
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put(self, source, rel_path, metadata=None): """Puts to only the first upstream. This is to be symmetric with put_stream."""
return self.upstreams[0].put(source, rel_path, metadata)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list(self, path=None, with_metadata=False, include_partitions=False): """Combine a listing of all of the upstreams, and add a metadata item for the repo_id"""
l = {} for upstream in [self.alternate, self.upstream]: for k, v in upstream.list(path, with_metadata, include_partitions).items(): upstreams = (l[k]['caches'] if k in l else []) + \ v.get('caches', upstream.repo_id) l[k] = v l[k]['caches'] = upstreams return l
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _copy_across(self, rel_path, cb=None): """If the upstream doesn't have the file, get it from the alternate and store it in the upstream"""
from . import copy_file_or_flo if not self.upstream.has(rel_path): if not self.alternate.has(rel_path): return None source = self.alternate.get_stream(rel_path) sink = self.upstream.put_stream(rel_path, metadata=source.meta) try: copy_file_or_flo(source, sink, cb=cb) except: self.upstream.remove(rel_path, propagate=True) raise source.close() sink.close()
<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_sigmak(line, lines): """Parse Energy, Re sigma xx, Im sigma xx, Re sigma zz, Im sigma zz"""
split_line = line.split() energy = float(split_line[0]) re_sigma_xx = float(split_line[1]) im_sigma_xx = float(split_line[2]) re_sigma_zz = float(split_line[3]) im_sigma_zz = float(split_line[4]) return {"energy": energy, "re_sigma_xx": re_sigma_xx, "im_sigma_xx": im_sigma_xx, "re_sigma_zz": re_sigma_zz, "im_sigma_zz": im_sigma_zz}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def require_self(func, *args, **kwargs): """Decorator to require that this component be installed"""
try: __import__(package['name']) except ImportError: sys.stderr.write( "This component needs to be installed first. Run " + "`invoke install`\n") sys.exit(1) return func(*args, **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 require_pip_module(module): """Decorator to check for a module and helpfully exit if it's not found"""
def wrapper(func, *args, **kwargs): try: __import__(module) except ImportError: sys.stderr.write( "`pip install %s` to enable this feature\n" % module) sys.exit(1) else: return func(*args, **kwargs) return decorator(wrapper)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replaced_by_django_migrations(func, *args, **kwargs): """Decorator to preempt South requirement"""
DjangoSettings() # trigger helpful messages if Django is missing import django if django.VERSION >= (1, 7): print("Django 1.7+ has its own migrations system.") print("Use this instead: `invoke managepy makemigrations`") sys.exit(1) return func(*args, **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 create_migration(initial=False): """Create a South migration for this project"""
settings = DjangoSettings() if 'south' not in (name.lower() for name in settings.INSTALLED_APPS): print("Temporarily adding 'south' into INSTALLED_APPS.") settings.INSTALLED_APPS.append('south') kwargs = dict(initial=True) if initial else dict(auto=True) run_django_cmd('schemamigration', package['name'], **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 coverage(reportdir=None, extra=None): """Test this project with coverage reports"""
import coverage as coverage_api cov = coverage_api.coverage() opts = {'directory': reportdir} if reportdir else {} cov.start() test(extra) cov.stop() cov.html_report(**opts)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def managepy(cmd, extra=None): """Run manage.py using this component's specific Django settings"""
extra = extra.split() if extra else [] run_django_cli(['invoke', cmd] + extra)
<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_total_magnetization(line, lines): """Parse the total magnetization, which is somewhat hidden"""
toks = line.split() res = {"number of electrons": float(toks[3])} if len(toks) > 5: res["total magnetization"] = float(toks[5]) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deferred_emails(): """Checks for deferred email, that otherwise fill up the queue."""
status = SERVER_STATUS['OK'] count = Message.objects.deferred().count() if DEFERRED_WARNING_THRESHOLD <= count < DEFERRED_DANGER_THRESHOLD: status = SERVER_STATUS['WARNING'] if count >= DEFERRED_DANGER_THRESHOLD: status = SERVER_STATUS['DANGER'] return { 'label': 'Deferred Email', 'status': status, 'info': 'There are currently {0} deferred messages.'.format(count) }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def email_queue(): """Checks for emails, that fill up the queue without getting sent."""
status = SERVER_STATUS['OK'] count = Message.objects.exclude(priority=PRIORITY_DEFERRED).filter( when_added__lte=now() - timedelta(minutes=QUEUE_TIMEOUT)).count() if QUEUE_WARNING_THRESHOLD <= count < QUEUE_DANGER_THRESHOLD: status = SERVER_STATUS['WARNING'] if count >= QUEUE_DANGER_THRESHOLD: status = SERVER_STATUS['DANGER'] return { 'label': 'Queued Email', 'status': status, 'info': 'There are currently {0} messages in the mail queue.'.format( count) }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def yaml_force_unicode(): """ Force pyyaml to return unicode values. """
#/ ## modified from |http://stackoverflow.com/a/2967461| if sys.version_info[0] == 2: def construct_func(self, node): return self.construct_scalar(node) yaml.Loader.add_constructor(U('tag:yaml.org,2002:str'), construct_func) yaml.SafeLoader.add_constructor(U('tag:yaml.org,2002:str'), construct_func)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_locale_hints(): """ Get a list of locale hints, guessed according to Python's default locale info. """
#/ lang, encoding = locale.getdefaultlocale() ## can both be None #/ if lang and '_' in lang: lang3, _, lang2 = lang.partition('_') else: lang3 = None lang2 = None #/ ll_s = [encoding, lang, lang2, lang3] ## Encoding comes before lang intentionally, e.g. ## lang |en_US| with encoding |cp936|, |cp936| takes priority. #/ ll_s_unique = [] for ll in ll_s: if ll: ll = ll.lower() if ll not in ll_s_unique: ll_s_unique.append(ll) #/ return ll_s_unique
<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_locale_choices(locale_dir): """ Get a list of locale file names in the given locale dir. """
#/ file_name_s = os.listdir(locale_dir) #/ choice_s = [] for file_name in file_name_s: if file_name.endswith(I18n.TT_FILE_EXT_STXT): file_name_noext, _ = os.path.splitext(file_name) if file_name_noext: choice_s.append(file_name_noext) #/ choice_s = sorted(choice_s) #/ return choice_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 working_set(self, extra=()): """Separate method to just get the working set This is intended for reuse by similar recipes. """
options = self.options b_options = self.buildout['buildout'] # Backward compat. :( options['executable'] = sys.executable distributions = [ r.strip() for r in options.get('eggs', self.name).split('\n') if r.strip()] orig_distributions = distributions[:] distributions.extend(extra) if self.buildout['buildout'].get('offline') == 'true': ws = zc.buildout.easy_install.working_set( distributions, [options['develop-eggs-directory'], options['eggs-directory']] ) else: ws = zc.buildout.easy_install.install( distributions, options['eggs-directory'], links=self.links, index=self.index, path=[options['develop-eggs-directory']], newest=self.buildout['buildout'].get('newest') == 'true', allow_hosts=self.allow_hosts) return orig_distributions, ws
<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_required(dist): """Return a set with all distributions that are required of dist This also includes subdependencies and the given distribution. :param dist: the distribution to query. Can also be the name of the distribution :type dist: :class:`pkg_resources.Distribution` | str :returns: a list of distributions that are required including the given one :rtype: set of :class:`pkg_resources.Distribution` :raises: class:`pkg_resources.DistributionNotFound` """
d = pkg_resources.get_distribution(dist) reqs = set(d.requires()) allds = set([d]) while reqs: newreqs = set([]) for r in reqs: dr = pkg_resources.get_distribution(r) allds.add(dr) newreqs = newreqs & set(dr.requires()) reqs = newreqs - reqs return allds
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_outdated(dist, dep=False): """Return a dict with outdated distributions If the given distribution has dependencies, they are checked as well. :param dist: a distribution to check :type dist: :class:`pkg_resources.Distribution` | str :param dep: If True, also return all outdated dependencies. If False, only check given dist. :type dep: :returns: dictionary of all distributions that are outdated and are either dependencies of the given distribution or the distribution itself. Keys are the outdated distributions and values are the newest parsed versions. :rtype: dict of :class:`pkg_resources.Distribution` :raises: class:`pkg_resources.DistributionNotFound` """
if dep: required = get_required(dist) else: required = set([dist]) ListCommand = pip.commands['list'] lc = ListCommand() options, args = lc.parse_args(['--outdated']) outdated = {} for d, raw_ver, parsed_ver in lc.find_packages_latests_versions(options): for r in required: if d.project_name == r.project_name and parsed_ver > r.parsed_version: outdated[r] = parsed_ver return outdated
<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(dist, args=None): """Update the given distribution and all of its dependencies :param dist: the distribution to check :type dist: :class:`pkg_resources.Distribution` | str :param args: extra arguments for the install command. this is somewhat equivalent to: pip install -U <dist> args :type args: list :returns: None :rtype: None :raises: class:`pkg_resources.DistributionNotFound` """
dist = pkg_resources.get_distribution(dist) InstallCommand = pip.commands['install'] ic = InstallCommand() iargs = ['-U', dist.project_name] if args: iargs.extend(args) ic.main(iargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restart(): """Restart the application the same way it was started :returns: None :rtype: None :raises: SystemExit """
python = sys.executable os.execl(python, python, * sys.argv)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticated(f): """Decorator that authenticates to Keystone automatically."""
@wraps(f) def new_f(self, *args, **kwargs): if not self.nova_client.client.auth_token: self.authenticate() return f(self, *args, **kwargs) return new_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 _translate_struct(inner_dict): """Translate a teleport Struct into a val subschema."""
try: optional = inner_dict['optional'].items() required = inner_dict['required'].items() except KeyError as ex: raise DeserializationError("Missing key: {}".format(ex)) except AttributeError as ex: raise DeserializationError( "Invalid Structure: {}".format(inner_dict)) val_dict = {k: _translate(v) for k, v in required} val_dict.update({Optional(k): _translate(v) for k, v in optional}) return val_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _translate_composite(teleport_value): """Translate a composite teleport value into a val subschema."""
for key in ("Array", "Map", "Struct"): value = teleport_value.get(key) if value is None: continue return COMPOSITES[key](value) raise DeserializationError( "Could not interpret %r as a teleport schema." % teleport_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 _translate(teleport_value): """Translate a teleport value in to a val subschema."""
if isinstance(teleport_value, dict): return _translate_composite(teleport_value) if teleport_value in PRIMITIVES: return PRIMITIVES[teleport_value] raise DeserializationError( "Could not interpret %r as a teleport schema." % teleport_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 to_val(teleport_schema): """Convert a parsed teleport schema to a val schema."""
translated = _translate(teleport_schema) if isinstance(translated, BaseSchema): return translated return Schema(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 _dict_to_teleport(dict_value): """Convert a val schema dictionary to teleport."""
if len(dict_value) == 1: for key, value in dict_value.items(): if key is str: return {"Map": from_val(value)} optional = {} required = {} for key, value in dict_value.items(): if isinstance(key, Optional): optional[key.value] = from_val(value) else: required[key] = from_val(value) return {"Struct": { "required": required, "optional": optional}}
<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_val(val_schema): """Serialize a val schema to teleport."""
definition = getattr(val_schema, "definition", val_schema) if isinstance( val_schema, BaseSchema) else val_schema if isinstance(definition, dict): return _dict_to_teleport(definition) if isinstance(definition, list): # teleport only supports a single type by default if len(definition) == 1: return {"Array": from_val(definition[0])} if definition in VAL_PRIMITIVES: return VAL_PRIMITIVES[definition] raise SerializationError( "Serializing %r not (yet) supported." % definition)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def document(schema): """Print a documented teleport version of the schema."""
teleport_schema = from_val(schema) return json.dumps(teleport_schema, sort_keys=True, indent=2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def nice_identifier(): 'do not use uuid.uuid4, because it can block' big = reduce(mul, struct.unpack('<LLLL', os.urandom(16)), 1) big = big % 2**128 return uuid.UUID(int=big).hex
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _acquire_lock(self, identifier, atime=30, ltime=5): '''Acquire a lock for a given identifier. If the lock cannot be obtained immediately, keep trying at random intervals, up to 3 seconds, until `atime` has passed. Once the lock has been obtained, continue to hold it for `ltime`. :param str identifier: lock token to write :param int atime: maximum time (in seconds) to acquire lock :param int ltime: maximum time (in seconds) to own lock :return: `identifier` if the lock was obtained, :const:`False` otherwise ''' conn = redis.Redis(connection_pool=self.pool) end = time.time() + atime while end > time.time(): if conn.set(self._lock_name, identifier, ex=ltime, nx=True): # logger.debug("won lock %s" % self._lock_name) return identifier sleep_time = random.uniform(0, 3) time.sleep(sleep_time) logger.warn('failed to acquire lock %s for %f seconds', self._lock_name, atime) 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 re_acquire_lock(self, ltime=5): '''Re-acquire the lock. You must already own the lock; this is best called from within a :meth:`lock` block. :param int ltime: maximum time (in seconds) to own lock :return: the session lock identifier :raise rejester.exceptions.EnvironmentError: if we didn't already own the lock ''' conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("expire", KEYS[1], ARGV[2]) else return -1 end ''') ret = script(keys=[self._lock_name], args=[self._session_lock_identifier, ltime]) if ret != 1: raise EnvironmentError('failed to re-acquire lock') # logger.debug('re-acquired lock %s', self._lock_name) return self._session_lock_identifier
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def lock(self, atime=30, ltime=5, identifier=None): '''Context manager to acquire the namespace global lock. This is typically used for multi-step registry operations, such as a read-modify-write sequence:: with registry.lock() as session: d = session.get('dict', 'key') del d['traceback'] session.set('dict', 'key', d) Callers may provide their own `identifier`; if they do, they must ensure that it is reasonably unique (e.g., a UUID). Using a stored worker ID that is traceable back to the lock holder is a good practice. :param int atime: maximum time (in seconds) to acquire lock :param int ltime: maximum time (in seconds) to own lock :param str identifier: worker-unique identifier for the lock ''' if identifier is None: identifier = nice_identifier() if self._acquire_lock(identifier, atime, ltime) != identifier: raise LockError("could not acquire lock") try: self._session_lock_identifier = identifier yield self finally: self._release_lock(identifier) self._session_lock_identifier = 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 read_lock(self): '''Find out who currently owns the namespace global lock. This is purely a diagnostic tool. If you are trying to get the global lock, it is better to just call :meth:`lock`, which will atomically get the lock if possible and retry. :return: session identifier of the lock holder, or :const:`None` ''' return redis.Redis(connection_pool=self.pool).get(self._lock_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 force_clear_lock(self): '''Kick out whoever currently owns the namespace global lock. This is intended as purely a last-resort tool. If another process has managed to get the global lock for a very long time, or if it requested the lock with a long expiration and then crashed, this can make the system functional again. If the original lock holder is still alive, its session calls may fail with exceptions. ''' return redis.Redis(connection_pool=self.pool).delete(self._lock_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def update(self, dict_name, mapping=None, priorities=None, expire=None, locks=None): '''Add mapping to a dictionary, replacing previous values Can be called with only dict_name and expire to refresh the expiration time. NB: locks are only enforced if present, so nothing prevents another caller from coming in an modifying data without using locks. :param mapping: a dict of keys and values to update in dict_name. Must be specified if priorities is specified. :param priorities: a dict with the same keys as those in mapping that provides a numerical value indicating the priority to assign to that key. Default sets 0 for all keys. :param int expire: if specified, then dict_name will be set to expire in that many seconds. :param locks: a dict with the same keys as those in the mapping. Before making any particular update, this function checks if a key is present in a 'locks' table for this dict, and if so, then its value must match the value provided in the input locks dict for that key. If not, then the value provided in the locks dict is inserted into the 'locks' table. If the locks parameter is None, then no lock checking is performed. ''' if self._session_lock_identifier is None: raise ProgrammerError('must acquire lock first') if priorities is None: ## set all priorities to zero priorities = defaultdict(int) if locks is None: ## set all locks to None locks = defaultdict(lambda: '') if not (expire is None or isinstance(expire, int)): raise ProgrammerError('expire must be int or unspecified') conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then for i = 3, #ARGV, 4 do if ARGV[i+3] ~= 'j:""' then local curr_lock = redis.call("hget", KEYS[4], ARGV[i]) if curr_lock and curr_lock ~= ARGV[i+3] then return {-1, ARGV[i], curr_lock, ARGV[i+3]} end redis.call("hset", KEYS[4], ARGV[i], ARGV[i+3]) end end for i = 3, #ARGV, 4 do redis.call("hset", KEYS[2], ARGV[i], ARGV[i+1]) redis.call("zadd", KEYS[3], ARGV[i+2], ARGV[i]) end if tonumber(ARGV[2]) ~= nil then redis.call("expire", KEYS[2], ARGV[2]) redis.call("expire", KEYS[3], ARGV[2]) end return {1, 0} else -- ERROR: No longer own the lock return {0, 0} end ''') dict_name = self._namespace(dict_name) if mapping is None: mapping = {} items = [] ## This flattens the dictionary into a list for key, value in mapping.iteritems(): items.append(self._encode(key)) items.append(self._encode(value)) items.append(priorities[key]) items.append(self._encode(locks[key])) #logger.debug('update %r %r', dict_name, items) res = script(keys=[self._lock_name, dict_name, dict_name + 'keys', dict_name + '_locks'], args=[self._session_lock_identifier, expire] + items) if res[0] == 0: raise EnvironmentError( 'Unable to add items to %s in registry' % dict_name) elif res[0] == -1: raise EnvironmentError( 'lost lock on key=%r owned by %r not %r in %s' % (self._decode(res[1]), res[2], res[3], dict_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 reset_priorities(self, dict_name, priority): '''set all priorities in dict_name to priority :type priority: float or int ''' if self._session_lock_identifier is None: raise ProgrammerError('must acquire lock first') ## see comment above for script in update conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then local keys = redis.call('ZRANGE', KEYS[2], 0, -1) for i, next_key in ipairs(keys) do redis.call("zadd", KEYS[2], ARGV[2], next_key) end return 1 else -- ERROR: No longer own the lock return 0 end ''') dict_name = self._namespace(dict_name) res = script(keys=[self._lock_name, dict_name + 'keys'], args=[self._session_lock_identifier, priority]) if not res: # We either lost the lock or something else went wrong raise EnvironmentError( 'Unable to add items to %s in registry' % dict_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 popitem(self, dict_name, priority_min='-inf', priority_max='+inf'): '''Select an item and remove it. The item comes from `dict_name`, and has the lowest score at least `priority_min` and at most `priority_max`. If some item is found, remove it from `dict_name` and return it. This runs as a single atomic operation but still requires a session lock. :param str dict_name: source dictionary :param float priority_min: lowest score :param float priority_max: highest score :return: pair of (key, value) if an item was popped, or :const:`None` ''' if self._session_lock_identifier is None: raise ProgrammerError('must acquire lock first') conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then -- remove next item of dict_name local next_key, next_priority = redis.call("zrangebyscore", KEYS[3], ARGV[2], ARGV[3], "WITHSCORES", "LIMIT", 0, 1)[1] if not next_key then return {} end redis.call("zrem", KEYS[3], next_key) local next_val = redis.call("hget", KEYS[2], next_key) -- zrem removed it from list, so also remove from hash redis.call("hdel", KEYS[2], next_key) return {next_key, next_val} else -- ERROR: No longer own the lock return -1 end ''') dict_name = self._namespace(dict_name) key_value = script(keys=[self._lock_name, dict_name, dict_name + "keys"], args=[self._session_lock_identifier, priority_min, priority_max]) if key_value == -1: raise KeyError( 'Registry failed to return an item from %s' % dict_name) if key_value == []: return None return self._decode(key_value[0]), self._decode(key_value[1])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def popitem_move(self, from_dict, to_dict, priority_min='-inf', priority_max='+inf'): '''Select an item and move it to another dictionary. The item comes from `from_dict`, and has the lowest score at least `priority_min` and at most `priority_max`. If some item is found, remove it from `from_dict`, add it to `to_dict`, and return it. This runs as a single atomic operation but still requires a session lock. :param str from_dict: source dictionary :param str to_dict: destination dictionary :param float priority_min: lowest score :param float priority_max: highest score :return: pair of (key, value) if an item was moved, or :const:`None` ''' if self._session_lock_identifier is None: raise ProgrammerError('must acquire lock first') conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then -- find the next key and priority local next_items = redis.call("zrangebyscore", KEYS[3], ARGV[2], ARGV[3], "WITHSCORES", "LIMIT", 0, 1) local next_key = next_items[1] local next_priority = next_items[2] if not next_key then return {} end -- remove next item of from_dict redis.call("zrem", KEYS[3], next_key) local next_val = redis.call("hget", KEYS[2], next_key) -- zrem removed it from list, so also remove from hash redis.call("hdel", KEYS[2], next_key) -- put it in to_dict redis.call("hset", KEYS[4], next_key, next_val) redis.call("zadd", KEYS[5], next_priority, next_key) return {next_key, next_val, next_priority} else -- ERROR: No longer own the lock return -1 end ''') key_value = script(keys=[self._lock_name, self._namespace(from_dict), self._namespace(from_dict) + 'keys', self._namespace(to_dict), self._namespace(to_dict) + 'keys'], args=[self._session_lock_identifier, priority_min, priority_max]) if key_value == []: return None if None in key_value or key_value == -1: raise KeyError( 'Registry.popitem_move(%r, %r) --> %r' % (from_dict, to_dict, key_value)) return self._decode(key_value[0]), self._decode(key_value[1])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def move(self, from_dict, to_dict, mapping, priority=None): '''Move keys between dictionaries, possibly with changes. Every key in `mapping` is removed from `from_dict`, and added to `to_dict` with its corresponding value. The priority will be `priority`, if specified, or else its current priority. This operation on its own is atomic and does not require a session lock; however, it does require you to pass in the values, which probably came from a previous query call. If you do not call this with a session lock but some other caller has one, you will get :class:`rejester.LockError`. If you do have a session lock, this will check that you still have it. :param str from_dict: name of original dictionary :param str to_dict: name of target dictionary :param dict mapping: keys to move with new values :param int priority: target priority, or :const:`None` to use existing :raise rejester.LockError: if the session lock timed out :raise rejester.EnvironmentError: if some items didn't move ''' items = [] ## This flattens the dictionary into a list for key, value in mapping.iteritems(): key = self._encode(key) items.append(key) value = self._encode(value) items.append(value) conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' local lock_holder = redis.call("get", KEYS[1]) if (not lock_holder) or (lock_holder == ARGV[1]) then local count = 0 for i = 3, #ARGV, 2 do -- find the priority of the item local next_priority = ARGV[2] if next_priority == "" then next_priority = redis.call("zscore", KEYS[3], ARGV[i]) end -- remove item from the sorted set and the real data redis.call("hdel", KEYS[2], ARGV[i]) redis.call("zrem", KEYS[3], ARGV[i]) -- put it in to_dict redis.call("hset", KEYS[4], ARGV[i], ARGV[i+1]) redis.call("zadd", KEYS[5], next_priority, ARGV[i]) count = count + 1 end return count else -- ERROR: No longer own the lock return -1 end ''') # Experimental evidence suggests that redis-py passes # *every* value as a string, maybe unless it's obviously # a number. Empty string is an easy "odd" value to test for. if priority is None: priority = '' num_moved = script(keys=[self._lock_name, self._namespace(from_dict), self._namespace(from_dict) + "keys", self._namespace(to_dict), self._namespace(to_dict) + "keys"], args=[self._session_lock_identifier, priority] + items) if num_moved == -1: raise LockError() if num_moved != len(items) / 2: raise EnvironmentError( 'Registry failed to move all: num_moved = %d != %d len(items)' % (num_moved, len(items)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def move_all(self, from_dict, to_dict): '''Move everything from one dictionary to another. This can be expensive if the source dictionary is large. This always requires a session lock. :param str from_dict: source dictionary :param str to_dict: destination dictionary ''' if self._session_lock_identifier is None: raise ProgrammerError('must acquire lock first') conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then local count = 0 local keys = redis.call('ZRANGE', KEYS[3], 0, -1) for i, next_key in ipairs(keys) do -- get the value and priority for this key local next_val = redis.call("hget", KEYS[2], next_key) local next_priority = redis.call("zscore", KEYS[3], next_key) -- remove item of from_dict redis.call("zrem", KEYS[3], next_key) -- also remove from hash redis.call("hdel", KEYS[2], next_key) -- put it in to_dict redis.call("hset", KEYS[4], next_key, next_val) redis.call("zadd", KEYS[5], next_priority, next_key) count = count + 1 end return count else -- ERROR: No longer own the lock return 0 end ''') num_moved = script(keys=[self._lock_name, self._namespace(from_dict), self._namespace(from_dict) + 'keys', self._namespace(to_dict), self._namespace(to_dict) + 'keys'], args=[self._session_lock_identifier]) return num_moved
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pull(self, dict_name): '''Get the entire contents of a single dictionary. This operates without a session lock, but is still atomic. In particular this will run even if someone else holds a session lock and you do not. This is only suitable for "small" dictionaries; if you have hundreds of thousands of items or more, consider :meth:`filter` instead to get a subset of a dictionary. :param str dict_name: name of the dictionary to retrieve :return: corresponding Python dictionary ''' dict_name = self._namespace(dict_name) conn = redis.Redis(connection_pool=self.pool) res = conn.hgetall(dict_name) split_res = dict([(self._decode(key), self._decode(value)) for key, value in res.iteritems()]) return split_res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def filter(self, dict_name, priority_min='-inf', priority_max='+inf', start=0, limit=None): '''Get a subset of a dictionary. This retrieves only keys with priority scores greater than or equal to `priority_min` and less than or equal to `priority_max`. Of those keys, it skips the first `start` ones, and then returns at most `limit` keys. With default parameters, this retrieves the entire dictionary, making it a more expensive version of :meth:`pull`. This can be used to limit the dictionary by priority score, for instance using the score as a time stamp and only retrieving values before or after a specific time; or it can be used to get slices of the dictionary if there are too many items to use :meth:`pull`. This is a read-only operation and does not require a session lock, but if this is run in a session context, the lock will be honored. :param str dict_name: name of the dictionary to retrieve :param float priority_min: lowest score to retrieve :param float priority_max: highest score to retrieve :param int start: number of items to skip :param int limit: number of items to retrieve :return: corresponding (partial) Python dictionary :raise rejester.LockError: if the session lock timed out ''' conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if (ARGV[1] == "") or (redis.call("get", KEYS[1]) == ARGV[1]) then -- find all the keys and priorities within range local next_keys = redis.call("zrangebyscore", KEYS[3], ARGV[2], ARGV[3], "limit", ARGV[4], ARGV[5]) if not next_keys[1] then return {} end local t = {} for i = 1, #next_keys do local next_val = redis.call("hget", KEYS[2], next_keys[i]) table.insert(t, next_keys[i]) table.insert(t, next_val) end return t else -- ERROR: No longer own the lock return -1 end ''') if limit is None: limit = -1 res = script(keys=[self._lock_name, self._namespace(dict_name), self._namespace(dict_name) + 'keys'], args=[self._session_lock_identifier or '', priority_min, priority_max, start, limit]) if res == -1: raise LockError() split_res = dict([(self._decode(res[i]), self._decode(res[i+1])) for i in xrange(0, len(res)-1, 2)]) return split_res
<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_1to1(self, dict_name, key1, key2): '''Set two keys to be equal in a 1-to-1 mapping. Within `dict_name`, `key1` is set to `key2`, and `key2` is set to `key1`. This always requires a session lock. :param str dict_name: dictionary to update :param str key1: first key/value :param str key2: second key/value ''' if self._session_lock_identifier is None: raise ProgrammerError('must acquire lock first') conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then redis.call("hset", KEYS[2], ARGV[2], ARGV[3]) redis.call("hset", KEYS[2], ARGV[3], ARGV[2]) else -- ERROR: No longer own the lock return -1 end ''') res = script(keys=[self._lock_name, self._namespace(dict_name)], args=[self._session_lock_identifier, self._encode(key1), self._encode(key2)]) if res == -1: raise EnvironmentError()
<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, dict_name, key, default=None, include_priority=False): '''Get the value for a specific key in a specific dictionary. If `include_priority` is false (default), returns the value for that key, or `default` (defaults to :const:`None`) if it is absent. If `include_priority` is true, returns a pair of the value and its priority, or of `default` and :const:`None`. This does not use or enforce the session lock, and is read-only, but inconsistent results are conceivably possible if the caller does not hold the lock and `include_priority` is set. :param str dict_name: name of dictionary to query :param str key: key in dictionary to query :param default: default value if `key` is absent :param bool include_priority: include score in results :return: value from dictionary, or pair of value and priority ''' dict_name = self._namespace(dict_name) key = self._encode(key) conn = redis.Redis(connection_pool=self.pool) val = conn.hget(dict_name, key) if val is None: _val = default else: _val = self._decode(val) if include_priority: if val is not None: priority = conn.zscore(dict_name + 'keys', key) return _val, priority else: return _val, None return _val
<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(self, dict_name, key, value, priority=None): '''Set a single value for a single key. This requires a session lock. :param str dict_name: name of the dictionary to update :param str key: key to update :param str value: value to assign to `key` :param int priority: priority score for the value (if any) ''' if priority is not None: priorities = {key: priority} else: priorities = None self.update(dict_name, {key: value}, priorities=priorities)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def delete(self, dict_name): '''Delete an entire dictionary. This operation on its own is atomic and does not require a session lock, but a session lock is honored. :param str dict_name: name of the dictionary to delete :raises rejester.exceptions.LockError: if called with a session lock, but the system does not currently have that lock; or if called without a session lock but something else holds it ''' conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then redis.call("del", KEYS[2], KEYS[3]) return 0 else return -1 end ''') res = script(keys=[self._lock_name, self._namespace(dict_name), self._namespace(dict_name) + 'keys'], args=[self._session_lock_identifier]) if res == -1: raise LockError()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def direct_call(self, *args): '''execute a direct redis call against this Registry instances namespaced keys. This is low level is should only be used for prototyping. arg[0] = redis function arg[1] = key --- will be namespaced before execution args[2:] = args to function :returns raw return value of function: Neither args nor return values are encoded/decoded ''' conn = redis.Redis(connection_pool=self.pool) command = args[0] key = self._namespace(args[1]) args = args[2:] func = getattr(conn, command) return func(key, *args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ask(question): ''' Infinite loop to get yes or no answer or quit the script. ''' while True: ans = input(question) al = ans.lower() if match('^y(es)?$', al): return True elif match('^n(o)?$', al): return False elif match('^q(uit)?$', al): stdout.write(CYAN) print("\nGoodbye.\n") stdout.write(RESET) quit() else: stdout.write(RED) print("%s is invalid. Enter (y)es, (n)o or (q)uit." % ans) stdout.write(RESET)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_remote_user(request): """Parse basic HTTP_AUTHORIZATION and return user name """
if 'HTTP_AUTHORIZATION' not in request.environ: return authorization = request.environ['HTTP_AUTHORIZATION'] try: authmeth, auth = authorization.split(' ', 1) except ValueError: # not enough values to unpack return if authmeth.lower() != 'basic': return try: auth = base64.b64decode(auth.strip().encode('latin1')).decode('latin1') except (binascii.Error, TypeError): # can't decode return try: login, password = auth.split(':', 1) except ValueError: # not enough values to unpack return return login, password
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def basic_auth_tween_factory(handler, registry): """Do basic authentication, parse HTTP_AUTHORIZATION and set remote_user variable to request """
def basic_auth_tween(request): remote_user = get_remote_user(request) if remote_user is not None: request.environ['REMOTE_USER'] = remote_user[0] return handler(request) return basic_auth_tween
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def plot_triaxial(height, width, tools): '''Plot pandas dataframe containing an x, y, and z column''' import bokeh.plotting p = bokeh.plotting.figure(x_axis_type='datetime', plot_height=height, plot_width=width, title=' ', toolbar_sticky=False, tools=tools, active_drag=BoxZoomTool(), output_backend='webgl') p.yaxis.axis_label = 'Acceleration (count)' p.xaxis.axis_label = 'Time (timezone as programmed)' # Plot accelerometry data as lines and scatter (for BoxSelectTool) colors = ['#1b9e77', '#d95f02', '#7570b3'] axes = ['x', 'y', 'z'] lines = [None,]*3 scats = [None,]*3 for i, (ax, c) in enumerate(zip(axes, colors)): lines[i] = p.line(y=ax, x='dt', color=c, legend=False, source=source) scats[i] = p.scatter(y=ax, x='dt', color=c, legend=False, size=1, source=source) return p, lines, scats
<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_data(path_dir): '''Load data, directory parameters, and accelerometer parameter names Args ---- path_dir: str Path to the data directory Returns ------- data: pandas.DataFrame Experiment data params_tag: dict A dictionary of parameters parsed from the directory name params_data: list A list of the accelerometer parameter names ''' import os import pylleo exp_name = os.path.split(path_dir)[1] params_tag = pylleo.utils.parse_experiment_params(exp_name) # Load the Little Leonardo tag data meta = pylleo.lleoio.read_meta(path_dir, params_tag['tag_model'], params_tag['tag_id']) data = pylleo.lleoio.read_data(meta, path_dir, sample_f=sample_f) # Get and curate the parameter names of the loaded dataframe params_data = pylleo.utils.get_tag_params(params_tag['tag_model']) params_data = [pylleo.utils.posix_string(p) for p in params_data] params_data = [p for p in params_data if p.startswith('acc')] return data, params_tag, params_data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def callback_checkbox(attr, old, new): '''Update visible data from parameters selectin in the CheckboxSelect''' import numpy for i in range(len(lines)): lines[i].visible = i in param_checkbox.active scats[i].visible = i in param_checkbox.active return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_password(config): """Returns the password for a remote server It tries to fetch the password from the following locations in this order: 1. config file [remote] section, password option 2. GNOME keyring 3. interactively, from the user """
password = config.get_option('remote.password') if password == '': user = config.get_option('remote.user') url = config.get_option('remote.url') url_obj = urlparse.urlparse(url) server = url_obj.hostname protocol = url_obj.scheme if HAS_GNOME_KEYRING_SUPPORT: password = get_password_from_gnome_keyring(user, server, protocol) else: prompt = 'Enter %s password for %s at %s: ' % (get_app(), user, server) password = getpass.getpass(prompt) return password