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 _compare(self, dir1, dir2): """ Compare contents of two directories """
left = set() right = set() self._numdirs += 1 excl_patterns = set(self._exclude).union(self._ignore) for cwd, dirs, files in os.walk(dir1): self._numdirs += len(dirs) for f in dirs + files: path = os.path.relpath(os.path.join(cwd, f), dir1) re_path = path.replace('\\', '/') if self._only: for pattern in self._only: if re.match(pattern, re_path): # go to exclude and ignore filtering break else: # next item, this one does not match any pattern # in the _only list continue add_path = False for pattern in self._include: if re.match(pattern, re_path): add_path = True break else: # path was not in includes # test if it is in excludes for pattern in excl_patterns: if re.match(pattern, re_path): # path is in excludes, do not add it break else: # path was not in excludes # it should be added add_path = True if add_path: left.add(path) anc_dirs = re_path[:-1].split('/') for i in range(1, len(anc_dirs)): left.add('/'.join(anc_dirs[:i])) for cwd, dirs, files in os.walk(dir2): for f in dirs + files: path = os.path.relpath(os.path.join(cwd, f), dir2) re_path = path.replace('\\', '/') for pattern in self._ignore: if re.match(pattern, re_path): if f in dirs: dirs.remove(f) break else: right.add(path) # no need to add the parent dirs here, # as there is no _only pattern detection if f in dirs and path not in left: self._numdirs += 1 common = left.intersection(right) left.difference_update(common) right.difference_update(common) return DCMP(left, right, common)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dowork(self, dir1, dir2, copyfunc=None, updatefunc=None): """ Private attribute for doing work """
if self._verbose: self.log('Source directory: %s:' % dir1) self._dcmp = self._compare(dir1, dir2) # Files & directories only in target directory if self._purge: for f2 in self._dcmp.right_only: fullf2 = os.path.join(self._dir2, f2) if self._verbose: self.log('Deleting %s' % fullf2) try: if os.path.isfile(fullf2): try: os.remove(fullf2) self._deleted.append(fullf2) self._numdelfiles += 1 except OSError as e: self.log(str(e)) self._numdelffld += 1 elif os.path.isdir(fullf2): try: shutil.rmtree(fullf2, True) self._deleted.append(fullf2) self._numdeldirs += 1 except shutil.Error as e: self.log(str(e)) self._numdeldfld += 1 except Exception as e: # of any use ? self.log(str(e)) continue # Files & directories only in source directory for f1 in self._dcmp.left_only: try: st = os.stat(os.path.join(self._dir1, f1)) except os.error: continue if stat.S_ISREG(st.st_mode): if copyfunc: copyfunc(f1, self._dir1, self._dir2) self._added.append(os.path.join(self._dir2, f1)) elif stat.S_ISDIR(st.st_mode): to_make = os.path.join(self._dir2, f1) if not os.path.exists(to_make): os.makedirs(to_make) self._numnewdirs += 1 self._added.append(to_make) # common files/directories for f1 in self._dcmp.common: try: st = os.stat(os.path.join(self._dir1, f1)) except os.error: continue if stat.S_ISREG(st.st_mode): if updatefunc: updatefunc(f1, self._dir1, self._dir2)
<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(self, filename, dir1, dir2): """ Private function for copying a file """
# NOTE: dir1 is source & dir2 is target if self._copyfiles: rel_path = filename.replace('\\', '/').split('/') rel_dir = '/'.join(rel_path[:-1]) filename = rel_path[-1] dir2_root = dir2 dir1 = os.path.join(dir1, rel_dir) dir2 = os.path.join(dir2, rel_dir) if self._verbose: self.log('Copying file %s from %s to %s' % (filename, dir1, dir2)) try: # source to target if self._copydirection == 0 or self._copydirection == 2: if not os.path.exists(dir2): if self._forcecopy: # 1911 = 0o777 os.chmod(os.path.dirname(dir2_root), 1911) try: os.makedirs(dir2) self._numnewdirs += 1 except OSError as e: self.log(str(e)) self._numdirsfld += 1 if self._forcecopy: os.chmod(dir2, 1911) # 1911 = 0o777 sourcefile = os.path.join(dir1, filename) try: if os.path.islink(sourcefile): os.symlink(os.readlink(sourcefile), os.path.join(dir2, filename)) else: shutil.copy2(sourcefile, dir2) self._numfiles += 1 except (IOError, OSError) as e: self.log(str(e)) self._numcopyfld += 1 if self._copydirection == 1 or self._copydirection == 2: # target to source if not os.path.exists(dir1): if self._forcecopy: # 1911 = 0o777 os.chmod(os.path.dirname(self.dir1_root), 1911) try: os.makedirs(dir1) self._numnewdirs += 1 except OSError as e: self.log(str(e)) self._numdirsfld += 1 targetfile = os.path.abspath(os.path.join(dir1, filename)) if self._forcecopy: os.chmod(dir1, 1911) # 1911 = 0o777 sourcefile = os.path.join(dir2, filename) try: if os.path.islink(sourcefile): os.symlink(os.readlink(sourcefile), os.path.join(dir1, filename)) else: shutil.copy2(sourcefile, targetfile) self._numfiles += 1 except (IOError, OSError) as e: self.log(str(e)) self._numcopyfld += 1 except Exception as e: self.log('Error copying file %s' % filename) self.log(str(e))
<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, filename, dir1, dir2): """ Private function for updating a file based on last time stamp of modification """
# NOTE: dir1 is source & dir2 is target if self._updatefiles: file1 = os.path.join(dir1, filename) file2 = os.path.join(dir2, filename) try: st1 = os.stat(file1) st2 = os.stat(file2) except os.error: return -1 # Update will update in both directions depending # on the timestamp of the file & copy-direction. if self._copydirection == 0 or self._copydirection == 2: # Update file if file's modification time is older than # source file's modification time, or creation time. Sometimes # it so happens that a file's creation time is newer than it's # modification time! (Seen this on windows) if self._cmptimestamps(st1, st2): if self._verbose: # source to target self.log('Updating file %s' % file2) try: if self._forcecopy: os.chmod(file2, 1638) # 1638 = 0o666 try: if os.path.islink(file1): os.symlink(os.readlink(file1), file2) else: shutil.copy2(file1, file2) self._changed.append(file2) self._numupdates += 1 return 0 except (IOError, OSError) as e: self.log(str(e)) self._numupdsfld += 1 return -1 except Exception as e: self.log(str(e)) return -1 if self._copydirection == 1 or self._copydirection == 2: # Update file if file's modification time is older than # source file's modification time, or creation time. Sometimes # it so happens that a file's creation time is newer than it's # modification time! (Seen this on windows) if self._cmptimestamps(st2, st1): if self._verbose: # target to source self.log('Updating file %s' % file1) try: if self._forcecopy: os.chmod(file1, 1638) # 1638 = 0o666 try: if os.path.islink(file2): os.symlink(os.readlink(file2), file1) else: shutil.copy2(file2, file1) self._changed.append(file1) self._numupdates += 1 return 0 except (IOError, OSError) as e: self.log(str(e)) self._numupdsfld += 1 return -1 except Exception as e: self.log(str(e)) return -1 return -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 _dirdiffandcopy(self, dir1, dir2): """ Private function which does directory diff & copy """
self._dowork(dir1, dir2, self._copy)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dirdiffandupdate(self, dir1, dir2): """ Private function which does directory diff & update """
self._dowork(dir1, dir2, 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 _diff(self, dir1, dir2): """ Private function which only does directory diff """
self._dcmp = self._compare(dir1, dir2) if self._dcmp.left_only: self.log('Only in %s' % dir1) for x in sorted(self._dcmp.left_only): self.log('>> %s' % x) self.log('') if self._dcmp.right_only: self.log('Only in %s' % dir2) for x in sorted(self._dcmp.right_only): self.log('<< %s' % x) self.log('') if self._dcmp.common: self.log('Common to %s and %s' % (self._dir1, self._dir2)) for x in sorted(self._dcmp.common): self.log('-- %s' % x) else: self.log('No common files or sub-directories!')
<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): """ Update will try to update the target directory w.r.t source directory. Only files that are common to both directories will be updated, no new files or directories are created """
self._copyfiles = False self._updatefiles = True self._purge = False self._creatdirs = False if self._verbose: self.log('Updating directory %s with %s\n' % (self._dir2, self._dir1)) self._dirdiffandupdate(self._dir1, self._dir2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diff(self): """ Only report difference in content between two directories """
self._copyfiles = False self._updatefiles = False self._purge = False self._creatdirs = False self._updatefiles = False self.log('Difference of directory %s from %s\n' % (self._dir2, self._dir1)) self._diff(self._dir1, self._dir2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def report(self): """ Print report of work at the end """
# We need only the first 4 significant digits tt = (str(self._endtime - self._starttime))[:4] self.log('\n%s finished in %s seconds.' % (__pkg_name__, tt)) self.log('%d directories parsed, %d files copied' % (self._numdirs, self._numfiles)) if self._numdelfiles: self.log('%d files were purged.' % self._numdelfiles) if self._numdeldirs: self.log('%d directories were purged.' % self._numdeldirs) if self._numnewdirs: self.log('%d directories were created.' % self._numnewdirs) if self._numupdates: self.log('%d files were updated by timestamp.' % self._numupdates) # Failure stats self.log('') if self._numcopyfld: self.log('there were errors in copying %d files.' % self._numcopyfld) if self._numdirsfld: self.log('there were errors in creating %d directories.' % self._numdirsfld) if self._numupdsfld: self.log('there were errors in updating %d files.' % self._numupdsfld) if self._numdeldfld: self.log('there were errors in purging %d directories.' % self._numdeldfld) if self._numdelffld: self.log('there were errors in purging %d files.' % self._numdelffld)
<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 set_action(self, on=None, bri=None, hue=None, sat=None, xy=None, ct=None, alert=None, effect=None, transitiontime=None, bri_inc=None, sat_inc=None, hue_inc=None, ct_inc=None, xy_inc=None, scene=None): """Change action of a group."""
data = { key: value for key, value in { 'on': on, 'bri': bri, 'hue': hue, 'sat': sat, 'xy': xy, 'ct': ct, 'alert': alert, 'effect': effect, 'transitiontime': transitiontime, 'bri_inc': bri_inc, 'sat_inc': sat_inc, 'hue_inc': hue_inc, 'ct_inc': ct_inc, 'xy_inc': xy_inc, 'scene': scene, }.items() if value is not None } await self._request('put', 'groups/{}/action'.format(self.id), json=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 _pre_tasks(self): """ Pre-tasks handler. """
if self.flushdb: management.call_command('flush', verbosity=0, interactive=False) logger.info('Flushed database')
<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_users(self): """ Creates users. """
rn = RandomNicknames() for name in rn.random_nicks(count=50): username = '%s%d' % (slugify(name), random.randrange(1, 99)) user = User.objects.create_user( username=username, email='%[email protected]' % username, password='secret') logger.info('Created user: %s', user.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 _create_badges(self): """ Creates badges. """
rn = RandomNicknames() for name in rn.random_nicks(count=20): slug = slugify(name) badge = Badge.objects.create( name=name, slug=slug, description='Lorem ipsum dolor sit amet, consectetur adipisicing elit') logger.info('Created badge: %s', badge.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 _create_awards(self): """ Creates awards. """
users = User.objects.all() for user in users: everyone_badge = Badge.objects.last() badge = Badge.objects.order_by('?')[0] try: award = Award.objects.create(user=user, badge=badge) everyone_award = Award.objects.create(user=user, badge=everyone_badge) logger.info('%s --- %s', award, everyone_award) except IntegrityError: 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 chunks(l, n): """ Yields successive n-sized chunks from l. """
for i in _range(0, len(l), n): yield l[i:i + n]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sanitize_command_options(options): """ Sanitizes command options. """
multiples = [ 'badges', 'exclude_badges', ] for option in multiples: if options.get(option): value = options[option] if value: options[option] = [v for v in value.split(' ') if v] return options
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, recipe): """ Registers a new recipe class. """
if not isinstance(recipe, (list, tuple)): recipe = [recipe, ] for item in recipe: recipe = self.get_recipe_instance_from_class(item) self._registry[recipe.slug] = recipe
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unregister(self, recipe): """ Unregisters a given recipe class. """
recipe = self.get_recipe_instance_from_class(recipe) if recipe.slug in self._registry: del self._registry[recipe.slug]
<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_recipe_instance(self, badge): """ Returns the recipe instance for the given badge slug. If badge has not been registered, raises ``exceptions.BadgeNotFound``. """
from .exceptions import BadgeNotFound if badge in self._registry: return self.recipes[badge] raise BadgeNotFound()
<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_recipe_instances(self, badges=None, excluded=None): """ Returns all recipe instances or just those for the given badges. """
if badges: if not isinstance(badges, (list, tuple)): badges = [badges] if excluded: if not isinstance(excluded, (list, tuple)): excluded = [excluded] badges = list(set(self.registered) - set(excluded)) if badges: valid, invalid = self.get_recipe_instances_for_badges(badges=badges) return valid return self.recipes.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 _init_taskqueue_stub(self, **stub_kwargs): """Initializes the taskqueue stub using nosegae config magic"""
task_args = {} # root_path is required so the stub can find 'queue.yaml' or 'queue.yml' if 'root_path' not in stub_kwargs: for p in self._app_path: # support --gae-application values that may be a .yaml file dir_ = os.path.dirname(p) if os.path.isfile(p) else p if os.path.isfile(os.path.join(dir_, 'queue.yaml')) or \ os.path.isfile(os.path.join(dir_, 'queue.yml')): task_args['root_path'] = dir_ break task_args.update(stub_kwargs) self.testbed.init_taskqueue_stub(**task_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 _init_datastore_v3_stub(self, **stub_kwargs): """Initializes the datastore stub using nosegae config magic"""
task_args = dict(datastore_file=self._data_path) task_args.update(stub_kwargs) self.testbed.init_datastore_v3_stub(**task_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 _init_user_stub(self, **stub_kwargs): """Initializes the user stub using nosegae config magic"""
# do a little dance to keep the same kwargs for multiple tests in the same class # because the user stub will barf if you pass these items into it # stub = user_service_stub.UserServiceStub(**stub_kw_args) # TypeError: __init__() got an unexpected keyword argument 'USER_IS_ADMIN' task_args = stub_kwargs.copy() self.testbed.setup_env(overwrite=True, USER_ID=task_args.pop('USER_ID', 'testuser'), USER_EMAIL=task_args.pop('USER_EMAIL', '[email protected]'), USER_IS_ADMIN=task_args.pop('USER_IS_ADMIN', '1')) self.testbed.init_user_stub(**task_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 _init_modules_stub(self, **_): """Initializes the modules stub based off of your current yaml files Implements solution from http://stackoverflow.com/questions/28166558/invalidmoduleerror-when-using-testbed-to-unit-test-google-app-engine """
from google.appengine.api import request_info # edit all_versions per modules & versions thereof needing tests all_versions = {} # {'default': [1], 'andsome': [2], 'others': [1]} def_versions = {} # {m: all_versions[m][0] for m in all_versions} m2h = {} # {m: {def_versions[m]: 'localhost:8080'} for m in def_versions} for module in self.configuration.modules: module_name = module._module_name or 'default' module_version = module._version or '1' all_versions[module_name] = [module_version] def_versions[module_name] = module_version m2h[module_name] = {module_version: 'localhost:8080'} request_info._local_dispatcher = request_info._LocalFakeDispatcher( module_names=list(all_versions), module_name_to_versions=all_versions, module_name_to_default_versions=def_versions, module_name_to_version_to_hostname=m2h) self.testbed.init_modules_stub()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_stub(self, stub_init, **stub_kwargs): """Initializes all other stubs for consistency's sake"""
getattr(self.testbed, stub_init, lambda **kwargs: None)(**stub_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 html_for_env_var(key): """Returns an HTML snippet for an environment variable. Args: key: A string representing an environment variable name. Returns: String HTML representing the value and variable. """
value = os.getenv(key) return KEY_VALUE_TEMPLATE.format(key, value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def html_for_cgi_argument(argument, form): """Returns an HTML snippet for a CGI argument. Args: argument: A string representing an CGI argument name in a form. form: A CGI FieldStorage object. Returns: String HTML representing the CGI value and variable. """
value = form[argument].value if argument in form else None return KEY_VALUE_TEMPLATE.format(argument, 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 html_for_modules_method(method_name, *args, **kwargs): """Returns an HTML snippet for a Modules API method. Args: method_name: A string containing a Modules API method. args: Positional arguments to be passed to the method. kwargs: Keyword arguments to be passed to the method. Returns: String HTML representing the Modules API method and value. """
method = getattr(modules, method_name) value = method(*args, **kwargs) return KEY_VALUE_TEMPLATE.format(method_name, 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(self): """GET handler that serves environment data."""
environment_variables_output = [html_for_env_var(key) for key in sorted(os.environ)] cgi_arguments_output = [] if os.getenv('CONTENT_TYPE') == 'application/x-www-form-urlencoded': # Note: a blank Content-type header will still sometimes # (in dev_appserver) show up as 'application/x-www-form-urlencoded' form = cgi.FieldStorage() if not form: cgi_arguments_output.append('No CGI arguments given...') else: for cgi_argument in form: cgi_arguments_output.append( html_for_cgi_argument(cgi_argument, form)) else: data = '' cgi_arguments_output.append(STDIN_TEMPLATE.format(len(data))) cgi_arguments_output.append(cgi.escape(data)) modules_api_output = [ html_for_modules_method('get_current_module_name'), html_for_modules_method('get_current_version_name'), html_for_modules_method('get_current_instance_id'), html_for_modules_method('get_modules'), html_for_modules_method('get_versions'), html_for_modules_method('get_default_version'), html_for_modules_method('get_hostname'), ] result = PAGE_TEMPLATE.format( users.CreateLoginURL(self.request.url), users.CreateLogoutURL(self.request.url), '<br>\n'.join(environment_variables_output), '<br>\n'.join(cgi_arguments_output), '<br>\n'.join(modules_api_output), ) self.response.write(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sync_badges(**kwargs): """ Iterates over registered recipes and creates missing badges. """
update = kwargs.get('update', False) created_badges = [] instances = registry.get_recipe_instances() for instance in instances: reset_queries() badge, created = instance.create_badge(update=update) if created: created_badges.append(badge) log_queries(instance) return created_badges
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sync_awards(**kwargs): """ Iterates over registered recipes and possibly creates awards. """
badges = kwargs.get('badges') excluded = kwargs.get('exclude_badges') disable_signals = kwargs.get('disable_signals') batch_size = kwargs.get('batch_size', None) db_read = kwargs.get('db_read', None) award_post_save = True if disable_signals: settings.AUTO_DENORMALIZE = False award_post_save = False instances = registry.get_recipe_instances(badges=badges, excluded=excluded) for instance in instances: reset_queries() instance.create_awards( batch_size=batch_size, db_read=db_read, post_save_signal=award_post_save) log_queries(instance)
<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_stats(**kwargs): """ Shows badges stats. """
db_read = kwargs.get('db_read', DEFAULT_DB_ALIAS) badges = (Badge.objects.using(db_read) .all() .annotate(u_count=Count('users')) .order_by('u_count')) for badge in badges: logger.info('{:<20} {:>10} users awarded | users_count: {})'.format( badge.name, badge.u_count, badge.users_count))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_current_user_ids(self, db_read=None): """ Returns current user ids and the count. """
db_read = db_read or self.db_read return self.user_ids.using(db_read)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_arguments(self, parser): """ Command arguments. """
super(Command, self).add_arguments(parser) parser.add_argument('--badges', action='store', dest='badges', type=str) parser.add_argument('--db-read', action='store', dest='db_read', type=str) parser.add_argument('--disable-signals', action='store_true', dest='disable_signals') parser.add_argument('--batch-size', action='store', dest='batch_size', type=int) parser.add_argument('--update', action='store_true', dest='update') parser.add_argument('--exclude-badges', action='store', dest='exclude_badges', type=str)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare(cls, match, subject): """ Accepts two OrganizationName objects and returns an arbitrary, numerical score based upon how well the names match. """
if match.expand().lower() == subject.expand().lower(): return 4 elif match.kernel().lower() == subject.kernel().lower(): return 3 # law and lobbying firms in CRP data typically list only the first two partners # before 'et al' elif ',' in subject.expand(): # we may have a list of partners if subject.crp_style_firm_name() == str(match).lower(): return 3 else: return 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 badgify_badges(**kwargs): """ Returns all badges or only awarded badges for the given user. """
User = get_user_model() user = kwargs.get('user', None) username = kwargs.get('username', None) if username: try: user = User.objects.get(username=username) except User.DoesNotExist: pass if user: awards = Award.objects.filter(user=user).select_related('badge') badges = [award.badge for award in awards] return badges return Badge.objects.all()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def without_extra_phrases(self): """Removes parenthethical and dashed phrases"""
# the last parenthesis is optional, because sometimes they are truncated name = re.sub(r'\s*\([^)]*\)?\s*$', '', self.name) name = re.sub(r'(?i)\s* formerly.*$', '', name) name = re.sub(r'(?i)\s*and its affiliates$', '', name) name = re.sub(r'\bet al\b', '', name) # in some datasets, the name of an organization is followed by a hyphen and an abbreviated name, or a specific # department or geographic subdivision; we want to remove this extraneous stuff without breaking names like # Wal-Mart or Williams-Sonoma # if there's a hyphen at least four characters in, proceed if "-" in name: hyphen_parts = name.rsplit("-", 1) # if the part after the hyphen is shorter than the part before, # AND isn't either a number (often occurs in Union names) or a single letter (e.g., Tech-X), # AND the hyphen is preceded by either whitespace or at least four characters, # discard the hyphen and whatever follows if len(hyphen_parts[1]) < len(hyphen_parts[0]) and re.search(r'(\w{4,}|\s+)$', hyphen_parts[0]) and not re.match(r'^([a-zA-Z]|[0-9]+)$', hyphen_parts[1]): name = hyphen_parts[0].strip() return 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 kernel(self): """ The 'kernel' is an attempt to get at just the most pithy words in the name """
stop_words = [ y.lower() for y in self.abbreviations.values() + self.filler_words ] kernel = ' '.join([ x for x in self.expand().split() if x.lower() not in stop_words ]) # this is a hack to get around the fact that this is the only two-word phrase we want to block # amongst our stop words. if we end up with more, we may need a better way to do this kernel = re.sub(r'\s*United States', '', kernel) return kernel
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detect_and_fix_two_part_surname(self, args): """ This detects common family name prefixes and joins them to the last name, so names like "De Kuyper" don't end up with "De" as a middle name. """
i = 0 while i < len(args) - 1: if args[i].lower() in self.family_name_prefixes: args[i] = ' '.join(args[i:i+2]) del(args[i+1]) break else: i += 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 case_name_parts(self): """ """
if not self.is_mixed_case(): self.honorific = self.honorific.title() if self.honorific else None self.nick = self.nick.title() if self.nick else None if self.first: self.first = self.first.title() self.first = self.capitalize_and_punctuate_initials(self.first) if self.last: self.last = self.last.title() self.last = self.uppercase_the_scots(self.last) self.middle = self.middle.title() if self.middle else None if self.suffix: # Title case Jr/Sr, but uppercase roman numerals if re.match(r'(?i).*[js]r', self.suffix): self.suffix = self.suffix.title() else: self.suffix = self.suffix.upper() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(args=None): """Print metadata as JSON strings."""
args = sys.argv[1:] parser = argparse.ArgumentParser() parser.add_argument("safe_file", type=str, nargs='+') parser.add_argument("--granules", action="store_true") parsed = parser.parse_args(args) pp = pprint.PrettyPrinter() for safe_file in parsed.safe_file: with s2reader.open(safe_file) as safe_dataset: if parsed.granules: pp.pprint( dict( safe_file=safe_file, granules=[ dict( granule_identifier=granule.granule_identifier, footprint=str(granule.footprint), srid=granule.srid, # cloudmask_polys=str(granule.cloudmask), # nodata_mask=str(granule.nodata_mask), cloud_percent=granule.cloud_percent ) for granule in safe_dataset.granules ] ) ) else: pp.pprint( dict( safe_file=safe_file, product_start_time=safe_dataset.product_start_time, product_stop_time=safe_dataset.product_stop_time, generation_time=safe_dataset.generation_time, footprint=str(safe_dataset.footprint), bounds=str(safe_dataset.footprint.bounds), granules=len(safe_dataset.granules), granules_srids=list(set([ granule.srid for granule in safe_dataset.granules ])) ) ) print "\n"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(safe_file): """Return a SentinelDataSet object."""
if os.path.isdir(safe_file) or os.path.isfile(safe_file): return SentinelDataSet(safe_file) else: raise IOError("file not found: %s" % safe_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 _granule_identifier_to_xml_name(granule_identifier): """ Very ugly way to convert the granule identifier. e.g. From Granule Identifier: S2A_OPER_MSI_L1C_TL_SGS__20150817T131818_A000792_T28QBG_N01.03 To Granule Metadata XML name: S2A_OPER_MTD_L1C_TL_SGS__20150817T131818_A000792_T28QBG.xml """
# Replace "MSI" with "MTD". changed_item_type = re.sub("_MSI_", "_MTD_", granule_identifier) # Split string up by underscores. split_by_underscores = changed_item_type.split("_") del split_by_underscores[-1] cleaned = str() # Stitch string list together, adding the previously removed underscores. for i in split_by_underscores: cleaned += (i + "_") # Remove last underscore and append XML file extension. out_xml = cleaned[:-1] + ".xml" return out_xml
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _polygon_from_coords(coords, fix_geom=False, swap=True, dims=2): """ Return Shapely Polygon from coordinates. - coords: list of alterating latitude / longitude coordinates - fix_geom: automatically fix geometry """
assert len(coords) % dims == 0 number_of_points = len(coords)/dims coords_as_array = np.array(coords) reshaped = coords_as_array.reshape(number_of_points, dims) points = [ (float(i[1]), float(i[0])) if swap else ((float(i[0]), float(i[1]))) for i in reshaped.tolist() ] polygon = Polygon(points).buffer(0) try: assert polygon.is_valid return polygon except AssertionError: if fix_geom: return polygon.buffer(0) else: raise RuntimeError("Geometry is not valid.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def product_metadata_path(self): """Return path to product metadata XML file."""
data_object_section = self._manifest_safe.find("dataObjectSection") for data_object in data_object_section: # Find product metadata XML. if data_object.attrib.get("ID") == "S2_Level-1C_Product_Metadata": relpath = os.path.relpath( data_object.iter("fileLocation").next().attrib["href"]) try: if self.is_zip: abspath = os.path.join(self._zip_root, relpath) assert abspath in self._zipfile.namelist() else: abspath = os.path.join(self.path, relpath) assert os.path.isfile(abspath) except AssertionError: raise S2ReaderIOError( "S2_Level-1C_product_metadata_path not found: %s \ " % abspath ) return abspath
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def footprint(self): """Return product footprint."""
product_footprint = self._product_metadata.iter("Product_Footprint") # I don't know why two "Product_Footprint" items are found. for element in product_footprint: global_footprint = None for global_footprint in element.iter("Global_Footprint"): coords = global_footprint.findtext("EXT_POS_LIST").split() return _polygon_from_coords(coords)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def granules(self): """Return list of SentinelGranule objects."""
for element in self._product_metadata.iter("Product_Info"): product_organisation = element.find("Product_Organisation") if self.product_format == 'SAFE': return [ SentinelGranule(_id.find("Granules"), self) for _id in product_organisation.findall("Granule_List") ] elif self.product_format == 'SAFE_COMPACT': return [ SentinelGranuleCompact(_id.find("Granule"), self) for _id in product_organisation.findall("Granule_List") ] else: raise Exception( "PRODUCT_FORMAT not recognized in metadata file, found: '" + str(self.safe_format) + "' accepted are 'SAFE' and 'SAFE_COMPACT'" )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def granule_paths(self, band_id): """Return the path of all granules of a given band."""
band_id = str(band_id).zfill(2) try: assert isinstance(band_id, str) assert band_id in BAND_IDS except AssertionError: raise AttributeError( "band ID not valid: %s" % band_id ) return [ granule.band_path(band_id) for granule in self.granules ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def metadata_path(self): """Determine the metadata path."""
xml_name = _granule_identifier_to_xml_name(self.granule_identifier) metadata_path = os.path.join(self.granule_path, xml_name) try: assert os.path.isfile(metadata_path) or \ metadata_path in self.dataset._zipfile.namelist() except AssertionError: raise S2ReaderIOError( "Granule metadata XML does not exist:", metadata_path) return metadata_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 tci_path(self): """Return the path to the granules TrueColorImage."""
tci_paths = [ path for path in self.dataset._product_metadata.xpath( ".//Granule[@granuleIdentifier='%s']/IMAGE_FILE/text()" % self.granule_identifier ) if path.endswith('TCI') ] try: tci_path = tci_paths[0] except IndexError: return None return os.path.join( self.dataset._zip_root if self.dataset.is_zip else self.dataset.path, tci_path ) + '.jp2'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cloud_percent(self): """Return percentage of cloud coverage."""
image_content_qi = self._metadata.findtext( ( """n1:Quality_Indicators_Info/Image_Content_QI/""" """CLOUDY_PIXEL_PERCENTAGE""" ), namespaces=self._nsmap) return float(image_content_qi)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def footprint(self): """Find and return footprint as Shapely Polygon."""
# Check whether product or granule footprint needs to be calculated. tile_geocoding = self._metadata.iter("Tile_Geocoding").next() resolution = 10 searchstring = ".//*[@resolution='%s']" % resolution size, geoposition = tile_geocoding.findall(searchstring) nrows, ncols = (int(i.text) for i in size) ulx, uly, xdim, ydim = (int(i.text) for i in geoposition) lrx = ulx + nrows * resolution lry = uly - ncols * resolution utm_footprint = box(ulx, lry, lrx, uly) project = partial( pyproj.transform, pyproj.Proj(init=self.srid), pyproj.Proj(init='EPSG:4326') ) footprint = transform(project, utm_footprint).buffer(0) return footprint
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cloudmask(self): """Return cloudmask as a shapely geometry."""
polys = list(self._get_mask(mask_type="MSK_CLOUDS")) return MultiPolygon([ poly["geometry"] for poly in polys if poly["attributes"]["maskType"] == "OPAQUE" ]).buffer(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 band_path(self, band_id, for_gdal=False, absolute=False): """Return paths of given band's jp2 files for all granules."""
band_id = str(band_id).zfill(2) if not isinstance(band_id, str) or band_id not in BAND_IDS: raise ValueError("band ID not valid: %s" % band_id) if self.dataset.is_zip and for_gdal: zip_prefix = "/vsizip/" if absolute: granule_basepath = zip_prefix + os.path.dirname(os.path.join( self.dataset.path, self.dataset.product_metadata_path )) else: granule_basepath = zip_prefix + os.path.dirname( self.dataset.product_metadata_path ) else: if absolute: granule_basepath = os.path.dirname(os.path.join( self.dataset.path, self.dataset.product_metadata_path )) else: granule_basepath = os.path.dirname( self.dataset.product_metadata_path ) product_org = self.dataset._product_metadata.iter( "Product_Organisation").next() granule_item = [ g for g in chain(*[gl for gl in product_org.iter("Granule_List")]) if self.granule_identifier == g.attrib["granuleIdentifier"] ] if len(granule_item) != 1: raise S2ReaderMetadataError( "Granule ID cannot be found in product metadata." ) rel_path = [ f.text for f in granule_item[0].iter() if f.text[-2:] == band_id ] if len(rel_path) != 1: # Apparently some SAFE files don't contain all bands. In such a # case, raise a warning and return None. warnings.warn( "%s: image path to band %s could not be extracted" % ( self.dataset.path, band_id ) ) return img_path = os.path.join(granule_basepath, rel_path[0]) + ".jp2" # Above solution still fails on the "safe" test dataset. Therefore, # the path gets checked if it contains the IMG_DATA folder and if not, # try to guess the path from the old schema. Not happy with this but # couldn't find a better way yet. if "IMG_DATA" in img_path: return img_path else: if self.dataset.is_zip: zip_prefix = "/vsizip/" granule_basepath = zip_prefix + os.path.join( self.dataset.path, self.granule_path) else: granule_basepath = self.granule_path return os.path.join( os.path.join(granule_basepath, "IMG_DATA"), "".join([ "_".join((self.granule_identifier).split("_")[:-1]), "_B", band_id, ".jp2" ]) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def geo_to_pixel(geo, level): """Transform from geo coordinates to pixel coordinates"""
lat, lon = float(geo[0]), float(geo[1]) lat = TileSystem.clip(lat, TileSystem.LATITUDE_RANGE) lon = TileSystem.clip(lon, TileSystem.LONGITUDE_RANGE) x = (lon + 180) / 360 sin_lat = sin(lat * pi / 180) y = 0.5 - log((1 + sin_lat) / (1 - sin_lat)) / (4 * pi) # might need to cast to uint map_size = TileSystem.map_size(level) pixel_x = int(TileSystem.clip(x * map_size + 0.5, (0, map_size - 1))) pixel_y = int(TileSystem.clip(y * map_size + 0.5, (0, map_size - 1))) # print '\n'+str( ((lat, lon), sin_lat, (x, y), map_size, (pixel_x, # pixel_y)) )+'\n' return pixel_x, pixel_y
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pixel_to_geo(pixel, level): """Transform from pixel to geo coordinates"""
pixel_x = pixel[0] pixel_y = pixel[1] map_size = float(TileSystem.map_size(level)) x = (TileSystem.clip(pixel_x, (0, map_size - 1)) / map_size) - 0.5 y = 0.5 - (TileSystem.clip(pixel_y, (0, map_size - 1)) / map_size) lat = 90 - 360 * atan(exp(-y * 2 * pi)) / pi lon = 360 * x return round(lat, 6), round(lon, 6)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tile_to_pixel(tile, centered=False): """Transform tile to pixel coordinates"""
pixel = [tile[0] * 256, tile[1] * 256] if centered: # should clip on max map size pixel = [pix + 128 for pix in pixel] return pixel[0], pixel[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 tile_to_quadkey(tile, level): """Transform tile coordinates to a quadkey"""
tile_x = tile[0] tile_y = tile[1] quadkey = "" for i in xrange(level): bit = level - i digit = ord('0') mask = 1 << (bit - 1) # if (bit - 1) > 0 else 1 >> (bit - 1) if (tile_x & mask) is not 0: digit += 1 if (tile_y & mask) is not 0: digit += 2 quadkey += chr(digit) return quadkey
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def quadkey_to_tile(quadkey): """Transform quadkey to tile coordinates"""
tile_x, tile_y = (0, 0) level = len(quadkey) for i in xrange(level): bit = level - i mask = 1 << (bit - 1) if quadkey[level - bit] == '1': tile_x |= mask if quadkey[level - bit] == '2': tile_y |= mask if quadkey[level - bit] == '3': tile_x |= mask tile_y |= mask return [(tile_x, tile_y), 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 authorize_url(self, state=''): """ return user authorize url """
url = 'https://openapi.youku.com/v2/oauth2/authorize?' params = { 'client_id': self.client_id, 'response_type': 'code', 'state': state, 'redirect_uri': self.redirect_uri } return url + urlencode(params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_none_value(data): """remove item from dict if value is None. return new dict. """
return dict((k, v) for k, v in data.items() if v is not 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_dataset(ds,dataDir,removecompressed=1): """ A function which attempts downloads and uncompresses the latest version of an openfmri.fmri dataset. PARAMETERS :ds: dataset number of the openfMRI.org dataset (integer) without zero padding. I.e. can just be 212 (doesn't need to be 000212). :dataDir: where to save the data. Will get saved in 'dataDir/openfmri/ds000XXX' :removecompressed: delete compressed data once unzipped. 1=yes. 0=no. NOTES There is no "default" way to download data from openfMRI so this solution is a little hacky. It may not be a universal functoin and it is best to verify that all necessary data has been downloaded. """
#Convert input ds to string incase it is put in via function ds = str(ds) #The final character of the dataset can be a letter lettersuffix='' if re.search('[A-Za-z]$',ds): lettersuffix = ds[-1] ds = ds[:-1] openfMRI_dataset_string = '{0:06d}'.format(int(ds)) + lettersuffix #Some datasets include try: os.mkdir(dataDir) except: pass datasetDir = os.path.join(dataDir, 'openfmri/') try: os.mkdir(datasetDir) except: pass openfMRI_url = 'https://openfmri.org/dataset/ds' + openfMRI_dataset_string + '/' r = urlopen(openfMRI_url).read() soup = BeautifulSoup(r,'lxml') #Isolate only the links from the latest revision. The text "data associated with revision". If the website changes its static text, this needs to be changed unformatted_soup=soup.prettify() firstOccurance=unformatted_soup.find('Data Associated with Revision') secondOccurancce=unformatted_soup[firstOccurance+1:].find('Data Associated with Revision') #If there is only one "Data Associated..." (i.e. only one revision) this returns -1. This should be kept. Otherwise add on the firstOccurance index if secondOccurancce != -1: secondOccurancce+=firstOccurance #The latest links are confined within this part of the text soup_latestversion = BeautifulSoup(unformatted_soup[firstOccurance:secondOccurancce],'lxml') # Loop through all links and dowload files filelist = [] for a in soup_latestversion.find_all('a', href=True): #This assumes that all files include ds.... if re.search('ds[A-Za-z_0-9.-]*$',a['href']): filename_start=re.search('ds[A-Za-z_0-9.-]*$',a['href']).start() filelist.append(a['href'][filename_start:]) print('Downloading: ' + a['href'][filename_start:]) urlretrieve(a['href'],datasetDir + a['href'][filename_start:]) print('--- Download complete ---') for f in filelist: untar_or_unzip(datasetDir,f) print('--- Uncompressing complete ---') if removecompressed==1: for f in filelist: print('Clean up. Deleting: ' + f) os.remove(datasetDir+f) print('--- Clean up complete ---') print('NOTE: It is best to verify manually that all the correct data has been downloaded and uncompressed correctly. \n If data is used in any publication, see openfmri.org about how to appropriately cite/credit the data.') print('--- Script complete ---')
<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_video_params(self, title=None, tags='Others', description='', copyright_type='original', public_type='all', category=None, watch_password=None, latitude=None, longitude=None, shoot_time=None ): """ util method for create video params to upload. Only need to provide a minimum of two essential parameters: title and tags, other video params are optional. All params spec see: http://cloud.youku.com/docs?id=110#create . Args: title: string, 2-50 characters. tags: string, 1-10 tags joind with comma. description: string, less than 2000 characters. copyright_type: string, 'original' or 'reproduced' public_type: string, 'all' or 'friend' or 'password' watch_password: string, if public_type is password. latitude: double. longitude: double. shoot_time: datetime. Returns: dict params that upload/create method need. """
params = {} if title is None: title = self.file_name elif len(title) > 80: title = title[:80] if len(description) > 2000: description = description[0:2000] params['title'] = title params['tags'] = tags params['description'] = description params['copyright_type'] = copyright_type params['public_type'] = public_type if category: params['category'] = category if watch_password: params['watch_password'] = watch_password if latitude: params['latitude'] = latitude if longitude: params['longitude'] = longitude if shoot_time: params['shoot_time'] = shoot_time return params
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _save_upload_state_to_file(self): """if create and create_file has execute, save upload state to file for next resume upload if current upload process is interrupted. """
if os.access(self.file_dir, os.W_OK | os.R_OK | os.X_OK): save_file = self.file + '.upload' data = { 'upload_token': self.upload_token, 'upload_server_ip': self.upload_server_ip } with open(save_file, 'w') as f: json.dump(data, 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 upload(self, params={}): """start uploading the file until upload is complete or error. This is the main method to used, If you do not care about state of process. Args: params: a dict object describe video info, eg title, tags, description, category. all video params see the doc of prepare_video_params. Returns: return video_id if upload successfully """
if self.upload_token is not None: # resume upload status = self.check() if status['status'] != 4: return self.commit() else: self.new_slice() while self.slice_task_id != 0: self.upload_slice() return self.commit() else: # new upload self.create(self.prepare_video_params(**params)) self.create_file() self.new_slice() while self.slice_task_id != 0: self.upload_slice() return self.commit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sync_users(self): """Synchronize LDAP users with local user model."""
if self.settings.USER_FILTER: user_attributes = self.settings.USER_ATTRIBUTES.keys() + self.settings.USER_EXTRA_ATTRIBUTES ldap_users = self.ldap.search(self.settings.USER_FILTER, user_attributes) self._sync_ldap_users(ldap_users) logger.info("Users are synchronized")
<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(args=sys.argv[1:]): """Generate EO O&M XML metadata."""
parser = argparse.ArgumentParser() parser.add_argument("filename", nargs=1) parser.add_argument("--granule-id", dest="granule_id", help=( "Optional. Specify a granule to export metadata from." ) ) parser.add_argument("--single-granule", dest="single_granule", action="store_true", default=False, help=( "When only one granule is contained in the package, include product " "metadata from this one granule. Fails when more than one granule " "is contained." ) ) parser.add_argument("--out-file", "-f", dest="out_file", help=( "Specify an output file to write the metadata to. By default, the " "XML is printed on stdout." ) ) parser.add_argument("--resolution", "-r", dest="resolution", default="10", help=( "Only produce metadata for bands of this resolution (in meters). " "Default is 10." ) ) parsed = parser.parse_args(args) try: safe_pkg = s2reader.open(parsed.filename[0]) except IOError, e: parser.error('Could not open SAFE package. Error was "%s"' % e) granules = safe_pkg.granules granule = None if parsed.granule_id: granule_dict = dict( (granule.granule_identifier, granule) for granule in granules ) try: granule = granule_dict[parsed.granule_id] except KeyError: parser.error('No such granule %r' % parsed.granule_id) elif parsed.single_granule: if len(granules) > 1: parser.error('Package contains more than one granule.') granule = granules[0] params = _get_product_template_params(safe_pkg, parsed.resolution) if granule: params.update(_get_granule_template_params(granule, parsed.resolution)) xml_string = EOOM_TEMPLATE_GRANULE.format(**params) else: xml_string = EOOM_TEMPLATE_PRODUCT.format(**params) if parsed.out_file: with open(parsed.out_file, "w") as f: f.write(xml_string) else: print(xml_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 is_ancestor(self, node): """ If node is ancestor of self Get the difference in level If not, None """
if self.level <= node.level or self.key[:len(node.key)] != node.key: return None return self.level - node.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 xdifference(self, to): """ Generator Gives the difference of quadkeys between self and to Generator in case done on a low level Only works with quadkeys of same level """
x,y = 0,1 assert self.level == to.level self_tile = list(self.to_tile()[0]) to_tile = list(to.to_tile()[0]) if self_tile[x] >= to_tile[x] and self_tile[y] <= self_tile[y]: ne_tile, sw_tile = self_tile, to_tile else: sw_tile, ne_tile = self_tile, to_tile cur = ne_tile[:] while cur[x] >= sw_tile[x]: while cur[y] <= sw_tile[y]: yield from_tile(tuple(cur), self.level) cur[y] += 1 cur[x] -= 1 cur[y] = ne_tile[y]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unwind(self): """ Get a list of all ancestors in descending order of level, including a new instance of self """
return [ QuadKey(self.key[:l+1]) for l in reversed(range(len(self.key))) ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self): """Apply validation rules for loaded settings."""
if self.GROUP_ATTRIBUTES and self.GROUPNAME_FIELD not in self.GROUP_ATTRIBUTES.values(): raise ImproperlyConfigured("LDAP_SYNC_GROUP_ATTRIBUTES must contain '%s'" % self.GROUPNAME_FIELD) if not self.model._meta.get_field(self.USERNAME_FIELD).unique: raise ImproperlyConfigured("LDAP_SYNC_USERNAME_FIELD '%s' must be unique" % self.USERNAME_FIELD) if self.USER_ATTRIBUTES and self.USERNAME_FIELD not in self.USER_ATTRIBUTES.values(): raise ImproperlyConfigured("LDAP_SYNC_USER_ATTRIBUTES must contain '%s'" % self.USERNAME_FIELD)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self, filterstr, attrlist): """Query the configured LDAP server."""
return self._paged_search_ext_s(self.settings.BASE, ldap.SCOPE_SUBTREE, filterstr=filterstr, attrlist=attrlist, page_size=self.settings.PAGE_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 fetch_lid(self, woeid): """Fetch a location's corresponding LID. Args: woeid: (string) the location's WOEID. Returns: a string containing the requested LID or None if the LID could not be found. Raises: urllib.error.URLError: urllib.request could not open the URL (Python 3). urllib2.URLError: urllib2 could not open the URL (Python 2). xml.etree.ElementTree.ParseError: xml.etree.ElementTree failed to parse the XML document. """
rss = self._fetch_xml(LID_LOOKUP_URL.format(woeid, "f")) # We are pulling the LID from the permalink tag in the XML file # returned by Yahoo. try: link = rss.find("channel/link").text except AttributeError: return None # use regex or string.split # regex assumes the format XXXXNNNN for the LID. # string.split works more general of the context. lid = re.search("[A-Za-z]{4}[0-9]{4}", link).group() # lid = link.split("/forecast/")[1].split("_")[0] return lid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_woeid(self, location): """Fetch a location's corresponding WOEID. Args: location: (string) a location (e.g. 23454 or Berlin, Germany). Returns: a string containing the location's corresponding WOEID or None if the WOEID could not be found. Raises: urllib.error.URLError: urllib.request could not open the URL (Python 3). urllib2.URLError: urllib2 could not open the URL (Python 2). xml.etree.ElementTree.ParseError: xml.etree.ElementTree failed to parse the XML document. """
rss = self._fetch_xml( WOEID_LOOKUP_URL.format(quote(location))) try: woeid = rss.find("results/Result/woeid").text except AttributeError: return None return woeid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _degrees_to_direction(self, degrees): """Convert wind direction from degrees to compass direction."""
try: degrees = float(degrees) except ValueError: return None if degrees < 0 or degrees > 360: return None if degrees <= 11.25 or degrees >= 348.76: return "N" elif degrees <= 33.75: return "NNE" elif degrees <= 56.25: return "NE" elif degrees <= 78.75: return "ENE" elif degrees <= 101.25: return "E" elif degrees <= 123.75: return "ESE" elif degrees <= 146.25: return "SE" elif degrees <= 168.75: return "SSE" elif degrees <= 191.25: return "S" elif degrees <= 213.75: return "SSW" elif degrees <= 236.25: return "SW" elif degrees <= 258.75: return "WSW" elif degrees <= 281.25: return "W" elif degrees <= 303.75: return "WNW" elif degrees <= 326.25: return "NW" elif degrees <= 348.75: return "NNW" else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fetch_xml(self, url): """Fetch a url and parse the document's XML."""
with contextlib.closing(urlopen(url)) as f: return xml.etree.ElementTree.parse(f).getroot()
<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_value(self, value): """ Get a specific canned value :type value: str :param value: Canned value to show :rtype: dict :return: A dictionnary containing canned value description """
values = self.get_values() values = [x for x in values if x['label'] == value] if len(values) == 0: raise Exception("Unknown value") else: return values[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show_key(self, value): """ Get a specific canned key :type value: str :param value: Canned key to show :rtype: dict :return: A dictionnary containing canned key description """
keys = self.get_keys() keys = [x for x in keys if x['label'] == value] if len(keys) == 0: raise Exception("Unknown key") else: return keys[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 download(self, dest_pattern="{originalFilename}", override=True, parent=False): """ Download the original image. Parameters dest_pattern : str, optional Destination path for the downloaded image. "{X}" patterns are replaced by the value of X attribute if it exists. override : bool, optional True if a file with same name can be overrided by the new file. parent : bool, optional True to download image parent if the image is a part of a multidimensional file. Returns ------- downloaded : bool True if everything happens correctly, False otherwise. """
if self.id is None: raise ValueError("Cannot download image with no ID.") pattern = re.compile("{(.*?)}") dest_pattern = re.sub(pattern, lambda m: str(getattr(self, str(m.group(0))[1:-1], "_")), dest_pattern) parameters = {"parent": parent} destination = os.path.dirname(dest_pattern) if not os.path.exists(destination): os.makedirs(destination) return Cytomine.get_instance().download_file("{}/{}/download".format(self.callback_identifier, self.id), dest_pattern, override, parameters)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump(self, dest_pattern="{id}.jpg", override=True, max_size=None, bits=8, contrast=None, gamma=None, colormap=None, inverse=None): """ Download the image with optional image modifications. Parameters dest_pattern : str, optional Destination path for the downloaded image. "{X}" patterns are replaced by the value of X attribute if it exists. override : bool, optional True if a file with same name can be overrided by the new file. max_size : int, tuple, optional Maximum size (width or height) of returned image. None to get original size. bits : int (8,16,32) or str ("max"), optional Bit depth (bit per channel) of returned image. "max" returns the original image bit depth contrast : float, optional Optional contrast applied on returned image. gamma : float, optional Optional gamma applied on returned image. colormap : int, optional Cytomine identifier of a colormap to apply on returned image. inverse : bool, optional True to inverse color mapping, False otherwise. Returns ------- downloaded : bool True if everything happens correctly, False otherwise. As a side effect, object attribute "filename" is filled with downloaded file path. """
if self.id is None: raise ValueError("Cannot dump an annotation with no ID.") pattern = re.compile("{(.*?)}") dest_pattern = re.sub(pattern, lambda m: str(getattr(self, str(m.group(0))[1:-1], "_")), dest_pattern) destination = os.path.dirname(dest_pattern) filename, extension = os.path.splitext(os.path.basename(dest_pattern)) extension = extension[1:] if extension not in ("jpg", "png", "tif", "tiff"): extension = "jpg" if not os.path.exists(destination): os.makedirs(destination) if isinstance(max_size, tuple) or max_size is None: max_size = max(self.width, self.height) parameters = { "maxSize": max_size, "contrast": contrast, "gamma": gamma, "colormap": colormap, "inverse": inverse, "bits": bits } file_path = os.path.join(destination, "{}.{}".format(filename, extension)) url = self.preview[:self.preview.index("?")] url = url.replace(".png", ".{}".format(extension)) result = Cytomine.get_instance().download_file(url, file_path, override, parameters) if result: self.filename = file_path return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filtered_elements(self, model): """Return iterator based on `element_type`."""
if isinstance(model, self.element_type): yield model yield from (e for e in model.eAllContents() if isinstance(e, self.element_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 folder_path_for_package(cls, package: ecore.EPackage): """Returns path to folder holding generated artifact for given element."""
parent = package.eContainer() if parent: return os.path.join(cls.folder_path_for_package(parent), package.name) return package.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 imported_classifiers_package(p: ecore.EPackage): """Determines which classifiers have to be imported into given package."""
classes = {c for c in p.eClassifiers if isinstance(c, ecore.EClass)} references = itertools.chain(*(c.eAllReferences() for c in classes)) references_types = (r.eType for r in references) imported = {c for c in references_types if getattr(c, 'ePackage', p) is not p} imported_dict = {} for classifier in imported: imported_dict.setdefault(classifier.ePackage, set()).add(classifier) return imported_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 imported_classifiers(p: ecore.EPackage): """Determines which classifiers have to be imported into given module."""
classes = {c for c in p.eClassifiers if isinstance(c, ecore.EClass)} supertypes = itertools.chain(*(c.eAllSuperTypes() for c in classes)) imported = {c for c in supertypes if c.ePackage is not p} attributes = itertools.chain(*(c.eAttributes for c in classes)) attributes_types = (a.eType for a in attributes) imported |= {t for t in attributes_types if t.ePackage not in {p, ecore.eClass, None}} imported_dict = {} for classifier in imported: imported_dict.setdefault(classifier.ePackage, set()).add(classifier) return imported_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 classes(p: ecore.EPackage): """Returns classes in package in ordered by number of bases."""
classes = (c for c in p.eClassifiers if isinstance(c, ecore.EClass)) return sorted(classes, key=lambda c: len(set(c.eAllSuperTypes())))
<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_pyfqn(cls, value, relative_to=0): """ Returns Python form of fully qualified name. Args: relative_to: If greater 0, the returned path is relative to the first n directories. """
def collect_packages(element, packages): parent = element.eContainer() if parent: collect_packages(parent, packages) packages.append(element.name) packages = [] collect_packages(value, packages) if relative_to < 0 or relative_to > len(packages): raise ValueError('relative_to not in range of number of packages') fqn = '.'.join(packages[relative_to:]) if relative_to: fqn = '.' + fqn return cls.module_path_map.get(fqn, fqn)
<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_environment(self, **kwargs): """ Return a new Jinja environment. Derived classes may override method to pass additional parameters or to change the template loader type. """
environment = super().create_environment(**kwargs) environment.tests.update({ 'type': self.test_type, 'kind': self.test_kind, 'opposite_before_self': self.test_opposite_before_self, }) environment.filters.update({ 'docstringline': self.filter_docstringline, 'pyquotesingle': self.filter_pyquotesingle, 'derivedname': self.filter_derived_name, 'refqualifiers': self.filter_refqualifiers, 'attrqualifiers': self.filter_attrqualifiers, 'supertypes': self.filter_supertypes, 'all_contents': self.filter_all_contents, 'pyfqn': self.filter_pyfqn, 're_sub': lambda v, p, r: re.sub(p, r, v), 'set': self.filter_set, }) from pyecore import ecore environment.globals.update({'ecore': ecore}) return environment
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate(self, model, outfolder, *, exclude=None): """ Generate model code. Args: model: The meta-model to generate code for. outfolder: Path to the directoty that will contain the generated code. exclude: List of referenced resources for which code was already generated (to prevent regeneration). """
with pythonic_names(): super().generate(model, outfolder) check_dependency = self.with_dependencies and model.eResource if check_dependency: if exclude is None: exclude = set() resource = model.eResource # the current resource had been managed and is excluded from further generations exclude.add(resource) rset = resource.resource_set direct_resources = {r for r in rset.resources.values() if r not in exclude} for resource in direct_resources: self.generate(resource.contents[0], outfolder, exclude=exclude)
<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_group(self, group_id): """ Get information about a group :type group_id: int :param group_id: Group ID Number :rtype: dict :return: a dictionary containing group information """
res = self.post('loadGroups', {'groupId': group_id}) if isinstance(res, list): return _fix_group(res[0]) else: return _fix_group(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 get_organism_permissions(self, group): """ Get the group's organism permissions :type group: str :param group: group name :rtype: list :return: a list containing organism permissions (if any) """
data = { 'name': group, } response = _fix_group(self.post('getOrganismPermissionsForGroup', data)) return response
<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_group_admin(self, group): """ Get the group's admins :type group: str :param group: group name :rtype: list :return: a list containing group admins """
data = { 'name': group, } response = _fix_group(self.post('getGroupAdmin', data)) return response
<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_group_creator(self, group): """ Get the group's creator :type group: str :param group: group name :rtype: list :return: creator userId """
data = { 'name': group, } response = _fix_group(self.post('getGroupCreator', data)) return response
<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_query_string(params): """ Support Elasticsearch 5.X """
parameters = params or {} for param, value in parameters.items(): param_value = str(value).lower() if isinstance(value, bool) else value parameters[param] = param_value return urlencode(parameters)
<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_status(self, status): """ Get a specific status :type status: str :param status: Status to show :rtype: dict :return: A dictionnary containing status description """
statuses = self.get_statuses() statuses = [x for x in statuses if x['value'] == status] if len(statuses) == 0: raise Exception("Unknown status value") else: return statuses[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_attribute(self, feature_id, attribute_key, attribute_value, organism=None, sequence=None): """ Add an attribute to a feature :type feature_id: str :param feature_id: Feature UUID :type attribute_key: str :param attribute_key: Attribute Key :type attribute_value: str :param attribute_value: Attribute Value :type organism: str :param organism: Organism Common Name :type sequence: str :param sequence: Sequence Name This seems to show two attributes being added, but it behaves like those two are one. :rtype: dict """
data = { 'features': [ { 'uniquename': feature_id, 'non_reserved_properties': [ { 'tag': attribute_key, 'value': attribute_value, } ] } ] } data = self._update_data(data, organism, sequence) return self.post('addAttribute', 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 add_dbxref(self, feature_id, db, accession, organism=None, sequence=None): """ Add a dbxref to a feature :type feature_id: str :param feature_id: Feature UUID :type db: str :param db: DB Name (e.g. PMID) :type accession: str :param accession: Accession Value :type organism: str :param organism: Organism Common Name :type sequence: str :param sequence: Sequence Name This seems to show two attributes being added, but it behaves like those two are one. :rtype: dict """
data = { 'features': [ { 'uniquename': feature_id, 'dbxrefs': [ { 'db': db, 'accession': accession, } ] } ] } data = self._update_data(data, organism, sequence) return self.post('addDbxref', 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 _handle_empty(self, user, response): """Apollo likes to return empty user arrays, even when you REALLY
if len(response.keys()) == 0: response = self.show_user(user) # And sometimes show_user can return nothing. Ask again... if len(response) == 0: response = self.show_user(user) return response
<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_user(self, user): """ Get a specific user :type user: str :param user: User Email :rtype: dict :return: a dictionary containing user information """
res = self.post('loadUsers', {'userId': user}) if isinstance(res, list) and len(res) > 0: res = res[0] return _fix_user(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 require_user(wa, email): """Require that the user has an account"""
cache_key = 'user-list' try: # Get the cached value data = userCache[cache_key] except KeyError: # If we hit a key error above, indicating that # we couldn't find the key, we'll simply re-request # the data data = wa.users.loadUsers() userCache[cache_key] = data return AssertUser([x for x in data if x.username == email])