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 main(): """Entry point for command line usage."""
import colorama import argparse import logging import sys import os parser = argparse.ArgumentParser(prog="gulpless", description="Simple build system.") parser.add_argument("-v", "--version", action="version", version="%(prog)s 0.7.6") parser.add_argument("-d", "--directory", action="store", default=os.getcwd(), help="Look for `build.py` in this folder (defaults to " "the current directory)") parser.add_argument("mode", action="store", choices=["build", "interactive"], default="interactive", metavar="mode", nargs="?", help="If `interactive` (the default), will wait for " "filesystem events and attempt to keep the input " "and output folders in sync. If `build`, it will " "attempt to build all updated files, then exit.") args = parser.parse_args() os.chdir(args.directory) sys.path.append(os.getcwd()) if os.environ.get("TERM") == "cygwin": # colorama doesn't play well with git bash del os.environ["TERM"] colorama.init() os.environ["TERM"] = "cygwin" else: colorama.init() try: old, sys.dont_write_bytecode = sys.dont_write_bytecode, True import build except ImportError: sys.exit("No `build.py` found in current folder.") finally: sys.dont_write_bytecode = old try: logging.basicConfig(level=build.LOGGING, format="%(message)s") except AttributeError: logging.basicConfig(level=logging.INFO, format="%(message)s") reactor = Reactor(build.SRC, build.DEST) for handler in build.HANDLERS: reactor.add_handler(handler) reactor.run(args.mode == "build")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def del_kwnkb(mapper, connection, target): """Remove taxonomy file."""
if(target.kbtype == KnwKB.KNWKB_TYPES['taxonomy']): # Delete taxonomy file if os.path.isfile(target.get_filename()): os.remove(target.get_filename())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def name(self, value): """Set name and generate the slug."""
self._name = value # generate slug if not self.slug: self.slug = KnwKB.generate_slug(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 kbtype(self, value): """Set kbtype."""
if value is None: # set the default value return # or set one of the available values kbtype = value[0] if len(value) > 0 else 'w' if kbtype not in ['t', 'd', 'w']: raise ValueError('unknown type "{value}", please use one of \ following values: "taxonomy", "dynamic" or \ "written_as"'.format(value=value)) self._kbtype = kbtype
<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_dict(self): """Return a dict representation of KnwKB."""
mydict = {'id': self.id, 'name': self.name, 'description': self.description, 'kbtype': self.kbtype} if self.kbtype == 'd': mydict.update((self.kbdefs.to_dict() if self.kbdefs else {}) or {}) return mydict
<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_dyn_config(self, field, expression, collection=None): """Set dynamic configuration."""
if self.kbdefs: # update self.kbdefs.output_tag = field self.kbdefs.search_expression = expression self.kbdefs.collection = collection db.session.merge(self.kbdefs) else: # insert self.kbdefs = KnwKBDDEF(output_tag=field, search_expression=expression, collection=collection)
<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_slug(name): """Generate a slug for the knowledge. :param name: text to slugify :return: slugified text """
slug = slugify(name) i = KnwKB.query.filter(db.or_( KnwKB.slug.like(slug), KnwKB.slug.like(slug + '-%'), )).count() return slug + ('-{0}'.format(i) if i > 0 else '')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_exists(filters): """Return True if a kb with the given filters exists. E.g: KnwKB.query_exists(KnwKB.name.like('FAQ')) :param filters: filter for sqlalchemy :return: True if kb exists """
return db.session.query( KnwKB.query.filter( filters).exists()).scalar()
<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_dict(self): """Return a dict representation of KnwKBDDEF."""
return {'field': self.output_tag, 'expression': self.search_expression, 'coll_id': self.id_collection, 'collection': self.collection.name if self.collection else 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 to_dict(self): """Return a dict representation of KnwKBRVAL."""
# FIXME remove 'id' dependency from invenio modules return {'id': self.m_key + "_" + str(self.id_knwKB), 'key': self.m_key, 'value': self.m_value, 'kbid': self.kb.id if self.kb else None, 'kbname': self.kb.name if self.kb else 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 social_links(context, object, user=None, authed=False, downable=False, vote_down_msg=None): """ Outputs social links. At minimum, this will be Facebook and Twitter. But if possible, it will also output voting and watchlist links. Usage: {% social_links object %} {% social_links object user %} {% social_links object user authenticated_request %} """
# check if voting available voting = False if hasattr(object, 'votes'): voting = True return { 'object': object, 'url': object.get_absolute_url(), 'site': get_current_site(context.request), 'ctype': ContentType.objects.get_for_model(object), 'user': user, 'voting': voting, 'vote_down': downable, 'vote_down_msg': vote_down_msg, 'authenticated_request': authed, }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(obj): """Convienently render strings with the fabric context"""
def get_v(v): return v % env if isinstance(v, basestring) else v if isinstance(obj, types.StringType): return obj % env elif isinstance(obj, types.TupleType) or isinstance(obj, types.ListType): rv = [] for v in obj: rv.append(get_v(v)) elif isinstance(obj, types.DictType): rv = {} for k, v in obj.items(): rv[k] = get_v(v) return rv
<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_wwln(file): """Read WWLN file"""
tmp = pd.read_csv(file, parse_dates=True, header=None, names=['date', 'time', 'lat', 'lon', 'err', '#sta']) # Generate a list of datetime objects with time to miliseconds list_dts = [] for dvals, tvals, in zip(tmp['date'], tmp['time']): list_dts.append(gen_datetime(dvals, tvals)) dtdf = pd.DataFrame(list_dts, columns=['datetime']) result = pd.concat([dtdf, tmp], axis=1) result = result.drop(['date', 'time'], axis=1) 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 wwln_to_geopandas(file): """Read data from Blitzorg first using pandas.read_csv for convienence, and then convert lat, lon points to a shaleply geometry POINT type. Finally put this gemoetry into a geopandas dataframe and return it."""
tmp = pd.read_csv(file, parse_dates=True, header=None, names=['date', 'time', 'lat', 'lon', 'err', '#sta']) list_dts = [gen_datetime(dvals, tvals) for dvals, tvals in zip(tmp['date'], tmp['time'])] points = [[Point(tmp.lat[row], tmp.lon[row]), dt] for row, dt in zip(tmp.index, list_dts)] df = gpd.GeoDataFrame(points, columns=['geometry', 'dt']) return df
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gen_time_intervals(start, end, delta): """Create time intervals with timedelta periods using datetime for start and end """
curr = start while curr < end: yield curr curr += delta
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_date(value): """ Convert timestamp to datetime and set everything to zero except a date """
dtime = value.to_datetime() dtime = (dtime - timedelta(hours=dtime.hour) - timedelta(minutes=dtime.minute) - timedelta(seconds=dtime.second) - timedelta(microseconds=dtime.microsecond)) return dtime
<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_request(self, request): """Check if user is logged in"""
assert hasattr(request, 'user') if not request.user.is_authenticated(): path = request.path_info.lstrip('/') if not any(m.match(path) for m in EXEMPT_URLS): return HttpResponseRedirect(reverse(settings.LOGIN_URL))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prt_js(js, sort_keys=True, indent=4): """Print Json in pretty format. There's a standard module pprint, can pretty print python dict and list. But it doesn't support sorted key. That why we need this func. Usage:: { "a": 1, "b": 2 } **中文文档** 以人类可读的方式打印可Json化的Python对象。 """
print(js2str(js, sort_keys, indent))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def string_SizeInBytes(size_in_bytes): """Make ``size in bytes`` human readable. Doesn"t support size greater than 1000PB. Usage:: 100 B 97.66 KB 95.37 MB 93.13 GB 90.95 TB 88.82 PB """
res, by = divmod(size_in_bytes, 1024) res, kb = divmod(res, 1024) res, mb = divmod(res, 1024) res, gb = divmod(res, 1024) pb, tb = divmod(res, 1024) if pb != 0: human_readable_size = "%.2f PB" % (pb + tb / float(1024)) elif tb != 0: human_readable_size = "%.2f TB" % (tb + gb / float(1024)) elif gb != 0: human_readable_size = "%.2f GB" % (gb + mb / float(1024)) elif mb != 0: human_readable_size = "%.2f MB" % (mb + kb / float(1024)) elif kb != 0: human_readable_size = "%.2f KB" % (kb + by / float(1024)) else: human_readable_size = "%s B" % by return human_readable_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 download_url(url, save_as, iter_size=_default_iter_size, enable_verbose=True): """A simple url binary content download function with progress info. Warning: this function will silently overwrite existing file. """
msg = Messenger() if enable_verbose: msg.on() else: msg.off() msg.show("Downloading %s from %s..." % (save_as, url)) with open(save_as, "wb") as f: response = requests.get(url, stream=True) if not response.ok: print("http get error!") return start_time = time.clock() downloaded_size = 0 for block in response.iter_content(iter_size): if not block: break f.write(block) elapse = datetime.timedelta(seconds=(time.clock() - start_time)) downloaded_size += sys.getsizeof(block) msg.show(" Finished %s, elapse %s." % ( string_SizeInBytes(downloaded_size), elapse )) msg.show(" 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 decode(hashcode, delta=False): """ decode a hashcode and get center coordinate, and distance between center and outer border """
lat, lon, lat_length, lon_length = _decode_c2i(hashcode) if hasattr(float, "fromhex"): latitude_delta = 90.0/(1 << lat_length) longitude_delta = 180.0/(1 << lon_length) latitude = _int_to_float_hex(lat, lat_length) * 90.0 + latitude_delta longitude = _int_to_float_hex(lon, lon_length) * 180.0 + longitude_delta if delta: return latitude, longitude, latitude_delta, longitude_delta return latitude, longitude lat = (lat << 1) + 1 lon = (lon << 1) + 1 lat_length += 1 lon_length += 1 latitude = 180.0*(lat-(1 << (lat_length-1)))/(1 << lat_length) longitude = 360.0*(lon-(1 << (lon_length-1)))/(1 << lon_length) if delta: latitude_delta = 180.0/(1 << lat_length) longitude_delta = 360.0/(1 << lon_length) return latitude, longitude, latitude_delta, longitude_delta return latitude, longitude
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bbox(hashcode): """ decode a hashcode and get north, south, east and west border. """
lat, lon, lat_length, lon_length = _decode_c2i(hashcode) if hasattr(float, "fromhex"): latitude_delta = 180.0/(1 << lat_length) longitude_delta = 360.0/(1 << lon_length) latitude = _int_to_float_hex(lat, lat_length) * 90.0 longitude = _int_to_float_hex(lon, lon_length) * 180.0 return {"s": latitude, "w": longitude, "n": latitude+latitude_delta, "e": longitude+longitude_delta} ret = {} if lat_length: ret['n'] = 180.0*(lat+1-(1 << (lat_length-1)))/(1 << lat_length) ret['s'] = 180.0*(lat-(1 << (lat_length-1)))/(1 << lat_length) else: # can't calculate the half with bit shifts (negative shift) ret['n'] = 90.0 ret['s'] = -90.0 if lon_length: ret['e'] = 360.0*(lon+1-(1 << (lon_length-1)))/(1 << lon_length) ret['w'] = 360.0*(lon-(1 << (lon_length-1)))/(1 << lon_length) else: # can't calculate the half with bit shifts (negative shift) ret['e'] = 180.0 ret['w'] = -180.0 return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_formset(self, request, form, formset, change): """ Given an inline formset save it to the database. """
formset.save() for form in formset.forms: if hasattr(form, 'nested_formsets') and form not in formset.deleted_forms: for nested_formset in form.nested_formsets: self.save_formset(request, form, nested_formset, change)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def all_valid_with_nesting(self, formsets): "Recursively validate all nested formsets" if not all_valid(formsets): return False for formset in formsets: if not formset.is_bound: pass for form in formset: if hasattr(form, 'nested_formsets'): if not self.all_valid_with_nesting(form.nested_formsets): return False #TODO - find out why this breaks when extra = 1 and just adding new item with no sub items if (not hasattr(form, 'cleaned_data') or not form.cleaned_data) and self.formset_has_nested_data(form.nested_formsets): form._errors["__all__"] = form.error_class(["Parent object must be created when creating nested inlines."]) return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(method, add_args, version=None, docstring=None, error_stream=sys.stderr): """Run the method as a script Add a '--version' argument Call add_args(parser) to add any more Parse sys.argv call method(args) Catch any exceptions exit on SystemExit or KeyboardError Others: If version is less then 1, reraise them Else print them to the error stream """
if version: _versions.append(version) try: args = parse_args( add_args, docstring and docstring or '%s()' % method.__name__) return _exit_ok if method(args) else _exit_fail except KeyboardInterrupt as e: ctrl_c = 3 return ctrl_c except SystemExit as e: return e.code except DebugExit: return _exit_fail except Exception as e: # pylint: disable=broad-except if int(latest_version().split('.')[0]) < 1: raise if error_stream: print(e, file=error_stream) return _exit_fail return _exit_ok
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ingest(self, corpus_file): ''' load and parse a pre-formatted and cleaned text file. Garbage in, garbage out ''' corpus = open(corpus_file) total_letters = 0 total_words = 0 shortest_word = 100 for word in corpus.readlines(): # clean word word = word.strip() word = re.sub(r'[\',\.\"]', '', word) total_letters += len(word) total_words += 1 shortest_word = len(word) if len(word) < shortest_word else shortest_word # iterate through n letter groups, where 1 <= n <= 3 n = self.chunk_size start = 0 # >: C, Cys: t, yst: i self.links[self.initial].append(word[0:n]) for position in range(n, len(word)): start = position - n if position - n >= 0 else 0 base = word[start:position] if not base in self.links: self.links[base] = [] self.links[base].append(word[position]) if not word[-n:] in self.links: self.links[word[-n:]] = [] self.links[word[-n:]].append(self.terminal) self.average_word_length = total_letters / total_words self.shortest = shortest_word
<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_word(self, word=None): ''' creates a new word ''' word = word if not word == None else self.initial if not self.terminal in word: if len(word) > self.average_word_length and \ self.terminal in self.links[word[-self.chunk_size:]] \ and random.randint(0, 1): addon = self.terminal else: options = self.links[word[-self.chunk_size:]] addon = random.choice(options) word = word + addon return self.get_word(word) return word[1:-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 existing_path(string): '''"Convert" a string to a string that is a path to an existing file.''' if not os.path.exists(string): msg = 'path {0!r} does not exist'.format(string) raise argparse.ArgumentTypeError(msg) return 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 absolute_path(string): '''"Convert" a string to a string that is an absolute existing path.''' if not os.path.isabs(string): msg = '{0!r} is not an absolute path'.format(string) raise argparse.ArgumentTypeError(msg) if not os.path.exists(os.path.dirname(string)): msg = 'path {0!r} does not exist'.format(string) raise argparse.ArgumentTypeError(msg) return 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 task_master(self): """A `TaskMaster` object for manipulating work"""
if self._task_master is None: self._task_master = build_task_master(self.config) return self._task_master
<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_work_spec(self, args): '''Get the contents of the work spec from the arguments.''' with open(args.work_spec_path) as f: return yaml.load(f)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _get_work_spec_name(self, args): '''Get the name of the work spec from the arguments. This assumes :meth:`_add_work_spec_name_args` has been called, but will also work if just :meth:`_add_work_spec_args` was called instead. ''' if getattr(args, 'work_spec_name', None): return args.work_spec_name return self._get_work_spec(args)['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 do_load(self, args): '''loads work_units into a namespace for a given work_spec --work-units file is JSON, one work unit per line, each line a JSON dict with the one key being the work unit key and the value being a data dict for the work unit. ''' work_spec = self._get_work_spec(args) work_spec['nice'] = args.nice self.task_master.set_work_spec(work_spec) if args.no_work: work_units_fh = [] # it just has to be an iterable with no lines else: work_units_fh = self._work_units_fh_from_path(args.work_units_path) if work_units_fh is None: raise RuntimeError('need -u/--work-units or --no-work') self.stdout.write('loading work units from {0!r}\n' .format(work_units_fh)) work_units = dict(self._read_work_units_file(work_units_fh)) if work_units: self.stdout.write('pushing work units\n') self.task_master.add_work_units(work_spec['name'], work_units.items()) self.stdout.write('finished writing {0} work units to work_spec={1!r}\n' .format(len(work_units), work_spec['name'])) else: self.stdout.write('no work units. done.\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 do_delete(self, args): '''delete the entire contents of the current namespace''' namespace = self.config['namespace'] if not args.assume_yes: response = raw_input('Delete everything in {0!r}? Enter namespace: ' .format(namespace)) if response != namespace: self.stdout.write('not deleting anything\n') return self.stdout.write('deleting namespace {0!r}\n'.format(namespace)) self.task_master.clear()
<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_work_specs(self, args): '''print the names of all of the work specs''' work_spec_names = [x['name'] for x in self.task_master.iter_work_specs()] work_spec_names.sort() for name in work_spec_names: self.stdout.write('{0}\n'.format(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 do_work_spec(self, args): '''dump the contents of an existing work spec''' work_spec_name = self._get_work_spec_name(args) spec = self.task_master.get_work_spec(work_spec_name) if args.json: self.stdout.write(json.dumps(spec, indent=4, sort_keys=True) + '\n') else: yaml.safe_dump(spec, self.stdout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def do_status(self, args): '''print the number of work units in an existing work spec''' work_spec_name = self._get_work_spec_name(args) status = self.task_master.status(work_spec_name) self.stdout.write(json.dumps(status, indent=4, sort_keys=True) + '\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 do_summary(self, args): '''print a summary of running rejester work''' assert args.json or args.text or (args.text is None) do_text = args.text xd = {} for ws in self.task_master.iter_work_specs(): name = ws['name'] status = self.task_master.status(name) xd[name] = status xd['_NOW'] = time.time() if args.json: self.stdout.write(json.dumps(xd) + '\n') else: if do_text is None: do_text = True if do_text: self.stdout.write('Work spec Avail Pending Blocked' ' Failed Finished Total\n') self.stdout.write('==================== ======== ======== ========' ' ======== ======== ========\n') for name in sorted(xd.keys()): if name == '_NOW': continue status = xd[name] self.stdout.write('{0:20s} {1[num_available]:8d} ' '{1[num_pending]:8d} {1[num_blocked]:8d} ' '{1[num_failed]:8d} {1[num_finished]:8d} ' '{1[num_tasks]:8d}\n'.format(name, status))
<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_work_units(self, args): '''list work units that have not yet completed''' work_spec_name = self._get_work_spec_name(args) if args.status: status = args.status.upper() statusi = getattr(self.task_master, status, None) if statusi is None: self.stdout.write('unknown status {0!r}\n'.format(args.status)) return else: statusi = None work_units = dict(self.task_master.get_work_units( work_spec_name, state=statusi, limit=args.limit)) work_unit_names = sorted(work_units.keys()) if args.limit: work_unit_names = work_unit_names[:args.limit] for k in work_unit_names: if args.details: tback = work_units[k].get('traceback', '') if tback: tback += '\n' work_units[k]['traceback'] = 'displayed below' self.stdout.write( '{0!r}: {1}\n{2}' .format(k, pprint.pformat(work_units[k], indent=4), tback)) else: self.stdout.write('{0}\n'.format(k))
<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_work_unit(self, args): '''print basic details about work units''' work_spec_name = self._get_work_spec_name(args) for work_unit_name in args.unit: status = self.task_master.get_work_unit_status(work_spec_name, work_unit_name) self.stdout.write('{0} ({1!r})\n' .format(work_unit_name, status['status'])) if 'expiration' in status: when = time.ctime(status['expiration']) if status == 'available': if status['expiration'] == 0: self.stdout.write(' Never scheduled\n') else: self.stdout.write(' Available since: {0}\n' .format(when)) else: self.stdout.write(' Expires: {0}\n'.format(when)) if 'worker_id' in status: try: heartbeat = self.task_master.get_heartbeat(status['worker_id']) except: heartbeat = None if heartbeat: hostname = (heartbeat.get('fqdn', None) or heartbeat.get('hostname', None) or '') ipaddrs = ', '.join(heartbeat.get('ipaddrs', ())) if hostname and ipaddrs: summary = '{0} on {1}'.format(hostname, ipaddrs) else: summary = hostname + ipaddrs else: summary = 'No information' self.stdout.write(' Worker: {0} ({1})\n'.format( status['worker_id'], summary)) if 'traceback' in status: self.stdout.write(' Traceback:\n{0}\n'.format( status['traceback'])) if 'depends_on' in status: self.stdout.write(' Depends on:\n') for what in status['depends_on']: self.stdout.write(' {0!r}\n'.format(what))
<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_retry(self, args): '''retry a specific failed job''' work_spec_name = self._get_work_spec_name(args) retried = 0 complained = False try: if args.all: while True: units = self.task_master.get_work_units( work_spec_name, limit=1000, state=self.task_master.FAILED) units = [u[0] for u in units] # just need wu key if not units: break try: self.task_master.retry(work_spec_name, *units) retried += len(units) except NoSuchWorkUnitError, e: # Because of this sequence, this probably means # something else retried the work unit. If we # try again, we shouldn't see it in the failed # list...so whatever pass else: units = args.unit try: self.task_master.retry(work_spec_name, *units) retried += len(units) except NoSuchWorkUnitError, e: unit = e.work_unit_name self.stdout.write('No such failed work unit {0!r}.\n' .format(unit)) complained = True units.remove(unit) # and try again except NoSuchWorkSpecError, e: # NB: you are not guaranteed to get this, especially with --all self.stdout.write('Invalid work spec {0!r}.\n' .format(work_spec_name)) return if retried == 0 and not complained: self.stdout.write('Nothing to do.\n') elif retried == 1: self.stdout.write('Retried {0} work unit.\n'.format(retried)) elif retried > 1: self.stdout.write('Retried {0} work units.\n'.format(retried))
<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_clear(self, args): '''remove work units from a work spec''' # Which units? work_spec_name = self._get_work_spec_name(args) units = args.unit or None # What to do? count = 0 if args.status is None: all = units is None count += self.task_master.del_work_units(work_spec_name, work_unit_keys=units, all=all) elif args.status == 'available': count += self.task_master.del_work_units( work_spec_name, work_unit_keys=units, state=self.task_master.AVAILABLE) elif args.status == 'pending': count += self.task_master.del_work_units( work_spec_name, work_unit_keys=units, state=self.task_master.PENDING) elif args.status == 'blocked': count += self.task_master.del_work_units( work_spec_name, work_unit_keys=units, state=self.task_master.BLOCKED) elif args.status == 'finished': count += self.task_master.del_work_units( work_spec_name, work_unit_keys=units, state=self.task_master.FINISHED) elif args.status == 'failed': count += self.task_master.del_work_units( work_spec_name, work_unit_keys=units, state=self.task_master.FAILED) self.stdout.write('Removed {0} work units.\n'.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 do_mode(self, args): '''get or set the global rejester worker mode''' if args.mode: mode = { 'idle': self.task_master.IDLE, 'run': self.task_master.RUN, 'terminate': self.task_master.TERMINATE }[args.mode] self.task_master.set_mode(mode) self.stdout.write('set mode to {0!r}\n'.format(args.mode)) else: mode = self.task_master.get_mode() self.stdout.write('{0!s}\n'.format(mode))
<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_workers(self, args): '''list all known workers''' workers = self.task_master.workers(alive=not args.all) for k in sorted(workers.iterkeys()): self.stdout.write('{0} ({1})\n'.format(k, workers[k])) if args.details: heartbeat = self.task_master.get_heartbeat(k) for hk, hv in heartbeat.iteritems(): self.stdout.write(' {0}: {1}\n'.format(hk, hv))
<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_run_one(self, args): '''run a single job''' work_spec_names = args.from_work_spec or None worker = SingleWorker(self.config, task_master=self.task_master, work_spec_names=work_spec_names, max_jobs=args.max_jobs) worker.register() rc = False starttime = time.time() count = 0 try: while True: rc = worker.run() if not rc: break count += 1 if (args.limit_seconds is None) and (args.limit_count is None): # only do one break if (args.limit_seconds is not None) and ((time.time() - starttime) >= args.limit_seconds): break if (args.limit_count is not None) and (count >= args.limit_count): break finally: worker.unregister() if not rc: self.exitcode = 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 get_number_of_particles(): """ Queries the ``dynac.short`` file for the number of particles used in the simulation. """
with open('dynac.short') as f: data_str = ''.join(line for line in f.readlines()) num_of_parts = int(data_str.split('Simulation with')[1].strip().split()[0]) return num_of_parts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multi_process_pynac(file_list, pynac_func, num_iters=100, max_workers=8): """ Use a ProcessPool from the ``concurrent.futures`` module to execute ``num_iters`` number of instances of ``pynac_func``. This function takes advantage of ``do_single_dynac_process`` and ``pynac_in_sub_directory``. """
with ProcessPoolExecutor(max_workers=max_workers) as executor: tasks = [executor.submit(do_single_dynac_process, num, file_list, pynac_func) for num in range(num_iters)] exc = [task.exception() for task in tasks if task.exception()] if exc: return exc else: return "No errors encountered"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pynac_in_sub_directory(num, file_list): """ A context manager to create a new directory, move the files listed in ``file_list`` to that directory, and change to that directory before handing control back to context. The closing action is to change back to the original directory. The directory name is based on the ``num`` input, and if it already exists, it will be deleted upon entering the context. The primary purpose of this function is to enable multiprocess use of Pynac via the ``multi_process_pynac`` function. """
print('Running %d' % num) new_dir = 'dynacProc_%04d' % num if os.path.isdir(new_dir): shutil.rmtree(new_dir) os.mkdir(new_dir) for f in file_list: shutil.copy(f, new_dir) os.chdir(new_dir) yield os.chdir('..')
<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(self): """ Run the simulation in the current directory. """
self._start_dynac_proc(stdin=subp.PIPE, stdout=subp.PIPE) str2write = self.name + '\r\n' if self._DEBUG: with open('pynacrun.log', 'a') as f: f.write(str2write) self.dynacProc.stdin.write(str2write.encode()) # The name field for pynEle in self.lattice: try: ele = pynEle.dynacRepresentation() except AttributeError: ele = pynEle str2write = ele[0] if self._DEBUG: with open('pynacrun.log', 'a') as f: f.write(str2write + '\r\n') try: self.dynacProc.stdin.write((str2write + '\r\n').encode()) except IOError: break for datum in ele[1]: str2write = ' '.join([str(i) for i in datum]) if self._DEBUG: with open('pynacrun.log', 'a') as f: f.write(str2write+'\r\n') try: self.dynacProc.stdin.write((str2write+'\r\n').encode()) except IOError: break self.dynacProc.stdin.close() if self.dynacProc.wait() != 0: raise RuntimeError("Errors occured during execution of Dynac")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format(self, format_target, remove_obsolete=True): """ Changes the internal self.format_string_object format target based on input. Also checks to see if input is an entry in the config file in case we want to switch to a preexisting config format. :param format_target: str, input for the new format type. All strings will be the new tokens. :param remove_obsolete: bool, dictates whether we are removing the obselete tokens or not that previously existed :return: None """
original_format, original_format_order = (self.format, self.format_order) try: format_target = self.CFG.get(format_target, return_type=str, throw_null_return_error=True) except (errors.ResourceNotFoundError, KeyError): pass self.format_string_object.swap_format(format_target) self._update_tokens_from_swap_format(original_format, original_format_order, remove_obsolete=remove_obsolete)
<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_format_options(self, format_target=''): """ First attempts to use format_target as a config path or gets the default format if it's invalid or is empty. :param format_target: (str, list(str)), can be either a query path to a format or in format of a naming string the sections should be spaced around e.g. - this_is_a_naming_string :raises: IOError """
try: if format_target: self.format = format_target else: raise errors.FormatError except errors.FormatError: self.format_string_object.swap_format(self.CFG.get(self.DEFAULT_FORMAT_PATH, return_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 initialize_options(cls): """ Stores options from the config file """
cls.CONFIG_OPTIONS = cls.CFG.get(cls.CONFIG_PATH, return_type=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 merge_dict(self, *args, **kwargs): """ Takes variable inputs, compiles them into a dictionary then merges it to the current nomenclate's state :param args: (dict, Nomenclate), any number of dictionary inputs or Nomenclates to be converted to dicts :param kwargs: str, any number of kwargs that represent token:value pairs """
input_dict = self._convert_input(*args, **kwargs) if input_dict: self._sift_and_init_configs(input_dict) self.token_dict.merge_serialization(input_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 get_token_settings(cls, token, default=None): """ Get the value for a specific token as a dictionary or replace with default :param token: str, token to query the nomenclate for :param default: object, substitution if the token is not found :return: (dict, object, None), token setting dictionary or default """
setting_dict = {} for key, value in iteritems(cls.__dict__): if '%s_' % token in key and not callable(key) and not isinstance(value, tokens.TokenAttr): setting_dict[key] = cls.__dict__.get(key, default) return setting_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 _update_tokens_from_swap_format(self, original_format, original_format_order, remove_obsolete=True): """ Updates tokens based on a swap format call that will maintain synchronicity between token_dict and attrs If there was an accidental setting already set to one of the attrs that should now be a token attr due to the format swap, we wipe it and add a new TokenAttr to the Nomenclate attribute. :param original_format: str, original format string to compare to :param original_format_order: list(str), the original format order to compare to :param remove_obsolete: bool, whether to remove obsolete tokens if off: persistent state across format swaps of missing tokens """
old_format_order = [_.lower() for _ in original_format_order] new_format_order = [_.lower() for _ in self.format_order] if hasattr(self, 'token_dict') and self.format != original_format: old_tokens = [token for token in list(set(old_format_order) - set(new_format_order)) if hasattr(self, token)] new_tokens = [token for token in set(new_format_order) - set(old_format_order) if not hasattr(self, token) or isinstance(getattr(self, token, ''), str)] self.merge_dict(dict.fromkeys(new_tokens, '')) if remove_obsolete: self.token_dict.purge_tokens(old_tokens) for new_token in new_tokens: try: delattr(self, new_token) except AttributeError: 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 _convert_input(self, *args, **kwargs): """ Takes variable inputs :param args: (dict, Nomenclate), any number of dictionary inputs or Nomenclates to be converted to dicts :param kwargs: str, any number of kwargs that represent token:value pairs :return: dict, combined dictionary of all inputs """
args = [arg.state if isinstance(arg, Nomenclate) else arg for arg in args] input_dict = combine_dicts(*args, **kwargs) return input_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 matchiter(r, s, flags=0): """ Yields contiguous MatchObjects of r in s. Raises ValueError if r eventually doesn't match contiguously. """
if isinstance(r, basestring): r = re.compile(r, flags) i = 0 while s: m = r.match(s) g = m and m.group(0) if not m or not g: raise ValueError("{}: {!r}".format(i, s[:50])) i += len(g) s = s[len(g):] yield m
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def matchall(r, s, flags=0): """ Returns the list of contiguous string matches of r in s, or None if r does not successively match the entire s. """
try: return [m.group(0) for m in matchiter(r, s, flags)] except ValueError: 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 check_subconfig(config, name, sub): """Validate the configuration of an object within this. This calls :meth:`Configurable.check_config` or equivalent on `sub`. A dictionary configuration for `sub` is required in `config`. :param dict config: parent configuration :param str name: name of the parent configuration block :param sub: Configurable-like subobject to check :raise yakonfig.ConfigurationError: if there is no configuration for `sub`, or it is not a dictionary """
subname = sub.config_name subconfig = config.setdefault(subname, {}) if not isinstance(subconfig, collections.Mapping): raise ProgrammerError('configuration for {0} in {1} must be a mapping' .format(subname, name)) checker = getattr(sub, 'check_config', None) if checker is not None: checker(subconfig, '{0}.{1}'.format(name, subname))
<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_cmor_fp_meta(fp): """Processes a CMOR style file path. Section 3.1 of the `Data Reference Syntax`_ details: The standard CMIP5 output tool CMOR optionally writes output files to a directory structure mapping DRS components to directory names as: <activity>/<product>/<institute>/<model>/<experiment>/<frequency>/ <modeling_realm>/<variable_name>/<ensemble_member>/<CMOR filename>.nc Arguments: fp (str): A file path conforming to DRS spec. Returns: dict: Metadata as extracted from the file path. .. _Data Reference Syntax: http://cmip-pcmdi.llnl.gov/cmip5/docs/cmip5_data_reference_syntax.pdf """
# Copy metadata list then reverse to start at end of path directory_meta = list(CMIP5_FP_ATTS) # Prefer meta extracted from filename meta = get_dir_meta(fp, directory_meta) meta.update(get_cmor_fname_meta(fp)) return meta
<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_datanode_fp_meta(fp): """Processes a datanode style file path. Section 3.2 of the `Data Reference Syntax`_ details: It is recommended that ESGF data nodes should layout datasets on disk mapping DRS components to directories as: <activity>/<product>/<institute>/<model>/<experiment>/ <frequency>/<modeling_realm>/<mip_table>/<ensemble_member>/ <version_number>/<variable_name>/<CMOR filename>.nc Arguments: fp (str): A file path conforming to DRS spec. Returns: dict: Metadata as extracted from the file path. .. _Data Reference Syntax: http://cmip-pcmdi.llnl.gov/cmip5/docs/cmip5_data_reference_syntax.pdf """
# Copy metadata list then reverse to start at end of path directory_meta = list(CMIP5_DATANODE_FP_ATTS) # Prefer meta extracted from filename meta = get_dir_meta(fp, directory_meta) meta.update(get_cmor_fname_meta(fp)) return meta
<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_cmor_fname_meta(fname): """Processes a CMOR style file name. Section 3.3 of the `Data Reference Syntax`_ details: filename = <variable name>_<mip_table>_<model>_<experiment>_ <ensemble_member>[_<temporal_subset>][_<geographical_info>].nc Temporal subsets are detailed in section 2.4: Time instants or periods will be represented by a construction of the form “N1-N2”, where N1 and N2 are of the form ‘yyyy[MM[dd[hh[mm[ss]]]]][-suffix]’, where ‘yyyy’, ‘MM’, ‘dd’, ‘hh’ ‘mm’ and ‘ss’ are integer year, month, day, hour, minute, and second, respectively, and the precision with which time is expressed must unambiguously resolve the interval between timesamples contained in the file or virtual file Geographic subsets are also detailed in section 2.4: The DRS specification for this indicator is a string of the form g-XXXX[-YYYY]. The “g-” indicates that some spatial selection or processing has been done (i.e., selection of a sub-global region and possibly spatial averaging). Arguments: fname (str): A file name conforming to DRS spec. Returns: dict: Metadata as extracted from the filename. .. _Data Reference Syntax: http://cmip-pcmdi.llnl.gov/cmip5/docs/cmip5_data_reference_syntax.pdf """
if '/' in fname: fname = os.path.split(fname)[1] fname = os.path.splitext(fname)[0] meta = fname.split('_') res = {} try: for key in CMIP5_FNAME_REQUIRED_ATTS: res[key] = meta.pop(0) except IndexError: raise PathError(fname) # Determine presence and order of optional metadata if len(meta) > 2: raise PathError(fname) is_geo = lambda x: x[0] == 'g' for key in meta: if is_geo(key): res['geographical_info'] = key else: res['temporal_subset'] = key 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 run(self, once=False): """Runs the reactor in the main thread."""
self._once = once self.start() while self.running: try: time.sleep(1.0) except KeyboardInterrupt: self.stop() self.join()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_to_enc_filename(fname): """ Converts the filename of a cleartext file and convert it to an encrypted filename :param fname: :return: filename of encrypted secret file if found, else None """
if not fname.lower().endswith('.json'): raise CredkeepException('Invalid filetype') if fname.lower().endswith('.enc.json'): raise CredkeepException('File already encrypted') enc_fname = fname[:-4] + 'enc.json' return enc_fname if exists(enc_fname) else 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 enc_to_clear_filename(fname): """ Converts the filename of an encrypted file to cleartext :param fname: :return: filename of clear secret file if found, else None """
if not fname.lower().endswith('.json'): raise CredkeepException('Invalid filetype') if not fname.lower().endswith('.enc.json'): raise CredkeepException('Not filename of encrypted file') clear_fname = fname.replace('.enc.json', '.json') print clear_fname return clear_fname if exists(clear_fname) else None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_heatmap(x_vec, y_vec, hist_matrix, fig, colormap='Blues', alpha=1, grid=False, colorbar=True, vmax='auto', vmin='auto', crop=True): """ convenience function to initialize a standard colormap in a figure """
plt.figure(fig.number) ax = fig.gca() # set vmax and vmin vma = np.amax(hist_matrix) if vmax == 'auto' else vmax vmi = np.amin(hist_matrix) if vmin == 'auto' else vmin # an error check if vma <= vmi: vma = vmi + 1 # grid the space for pcolormesh x_grid, y_grid = np.meshgrid(x_vec, y_vec) hmap = ax.pcolormesh(x_grid, y_grid, np.array(hist_matrix), cmap=colormap, alpha=alpha, shading='gouraud', vmax=vma, vmin=vmi) if colorbar: plt.colorbar(hmap) if not grid: ax.grid(False) if crop: ax.set_xlim([x_vec[0], x_vec[-1]]) ax.set_ylim([y_vec[0], y_vec[-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 heatmap(x, y, step=None, min_pt=None, max_pt=None, colormap='Blues', alpha=1, grid=False, colorbar=True, scale='lin', vmax='auto', vmin='auto', crop=True): """ function to take vectors x and y and hist them """
(x_vec, y_vec, hist_matrix) = calc_2d_hist(x, y, step, min_pt, max_pt) # simple in this case because it is positive counts if scale == 'log': for row in hist_matrix: for i, el in enumerate(row): row[i] = 0 if row[i] == 0 else log10(row[i]) # plot fig = plt.figure() init_heatmap(x_vec, y_vec, hist_matrix, fig, colormap=colormap, alpha=alpha, grid=grid, colorbar=colorbar, vmax=vmax, vmin=vmin, crop=crop) return fig
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ext_language(ext, exts=None): """Language of the extension in those extensions If exts is supplied, then restrict recognition to those exts only If exts is not supplied, then use all known extensions True """
languages = { '.py': 'python', '.py2': 'python2', '.py3': 'python3', '.sh': 'bash', '.bash': 'bash', '.pl': 'perl', '.js': 'javascript', '.txt': 'english', } ext_languages = {_: languages[_] for _ in exts} if exts else languages return ext_languages.get(ext)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_language(script, exts=None): """Determine the script's language extension True If exts are given they restrict which extensions are allowed True If there is no extension, but shebang is present, then use that (Expecting to find "#!" in ~/.bashrc for this test, but ~/.bashrc might not exist - then there's no language) True """
if not script.isfile(): return None if script.ext: return ext_language(script.ext, exts) shebang = script.shebang() return shebang and str(shebang.name) or 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 makepath(s, as_file=False): """Make a path from a string Expand out any variables, home squiggles, and normalise it See also http://stackoverflow.com/questions/26403972 """
if s is None: return None result = FilePath(s) if (os.path.isfile(s) or as_file) else DirectPath(s) return result.expandall()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cd(path_to): # pylint: disable=invalid-name """cd to the given path If the path is a file, then cd to its parent directory Remember current directory before the cd so that we can cd back there with cd('-') """
if path_to == '-': if not cd.previous: raise PathError('No previous directory to return to') return cd(cd.previous) if not hasattr(path_to, 'cd'): path_to = makepath(path_to) try: previous = os.getcwd() except OSError as e: if 'No such file or directory' in str(e): return False raise if path_to.isdir(): os.chdir(path_to) elif path_to.isfile(): os.chdir(path_to.parent) elif not os.path.exists(path_to): return False else: raise PathError('Cannot cd to %s' % path_to) cd.previous = previous return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_needed(pattern, path_to_directory, wanted): """Make a method to check if an item matches the pattern, and is wanted If wanted is None just check the pattern """
if wanted: def needed(name): return fnmatch(name, pattern) and wanted( os.path.join(path_to_directory, name)) return needed else: return lambda name: fnmatch(name, pattern)
<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_items(path_to_directory, pattern, wanted): """All items in the given path which match the given glob and are wanted"""
if not path_to_directory: return set() needed = make_needed(pattern, path_to_directory, wanted) return [os.path.join(path_to_directory, name) for name in _names_in_directory(path_to_directory) if needed(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 contains_glob(path_to_directory, pattern, wanted=None): """Whether the given path contains an item matching the given glob"""
if not path_to_directory: return False needed = make_needed(pattern, path_to_directory, wanted) for name in _names_in_directory(path_to_directory): if needed(name): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tab_complete(string): """Finish file names "left short" by tab-completion For example, if an argument is "fred." and no file called "fred." exists but "fred.py" does exist then return fred.py """
if is_option(string): return string if not missing_extension(string): return string if os.path.isfile(string): return string extended_files = [f for f in extend(string) if os.path.isfile(f)] try: return extended_files[0] except IndexError: return 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 pyc_to_py(path_to_file): """Change some file extensions to those which are more likely to be text True """
stem, ext = os.path.splitext(path_to_file) if ext == '.pyc': return '%s.py' % stem return path_to_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 as_existing_file(self, filepath): """Return the file class for existing files only"""
if os.path.isfile(filepath) and hasattr(self, '__file_class__'): return self.__file_class__(filepath) # pylint: disable=no-member return self.__class__(filepath)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dirpaths(self): """Split the dirname into individual directory names An absolute path starts with an empty string, a relative path does not True """
parts = self.parts() result = [DotPath(parts[0] or '/')] for name in parts[1:]: result.append(result[-1] / name) 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 parts(self): """Split the path into parts like Pathlib """
parts = self.split(os.path.sep) parts[0] = parts[0] and parts[0] or '/' return parts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def short_relative_path_to(self, destination): """The shorter of either the absolute path of the destination, or the relative path to it ../build/python.tar /mnt/guido/build/python.tar """
relative = self.relpathto(destination) absolute = self.__class__(destination).abspath() if len(relative) < len(absolute): return relative return absolute
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extend_by(self, extension): """The path to the file changed to use the given extension <FilePath '/path/to/fred.txt'> <FilePath '/path/to/fred.tmp'> <FilePath '/path/to/fred.fred'> """
copy = self[:] filename, _ = os.path.splitext(copy) return self.__class__('%s.%s' % (filename, extension.lstrip('.')))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_file_exist(self): """Make sure the parent directory exists, then touch the file"""
self.parent.make_directory_exist() self.parent.touch_file(self.name) 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 language(self): """The language of this file"""
try: return self._language except AttributeError: self._language = find_language(self, getattr(self, 'exts', None)) return self._language
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def try_remove(self): """Try to remove the path If it is a directory, try recursive removal of contents too """
if self.islink(): self.unlink() elif self.isfile(): self.remove() elif self.isdir(): self.empty_directory() if self.isdir(): self.rmdir() else: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def empty_directory(self): """Remove all contents of a directory Including any sub-directories and their contents"""
for child in self.walkfiles(): child.remove() for child in reversed([d for d in self.walkdirs()]): if child == self or not child.isdir(): continue child.rmdir()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_file_exist(self, filename=None): """Make the directory exist, then touch the file If the filename is None, then use self.name as filename """
if filename is None: path_to_file = FilePath(self) path_to_file.make_file_exist() return path_to_file else: self.make_directory_exist() path_to_file = self.touch_file(filename) return FilePath(path_to_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 touch_file(self, filename): """Touch a file in the directory"""
path_to_file = self.__file_class__(os.path.join(self, filename)) path_to_file.touch() return path_to_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 existing_sub_paths(self, sub_paths): """Those in the given list of sub_paths which do exist"""
paths_to_subs = [self / _ for _ in sub_paths] return [_ for _ in paths_to_subs if _.exists()]
<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_preset(self): """ Loads preset if it is specified in the .frigg.yml """
if 'preset' in self.settings.preview: with open(os.path.join(os.path.dirname(__file__), 'presets.yaml')) as f: presets = yaml.load(f.read()) if self.settings.preview['preset'] in presets: self.preset = presets[self.settings.preview['preset']] return self.preset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call_command(self, cmd, *argv): """ Runs a command. :param cmd: command to run (key at the registry) :param argv: arguments that would be passed to the command """
parser = self.get_parser() args = [cmd] + list(argv) namespace = parser.parse_args(args) self.run_command(namespace)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self, argv=None): """ Executes command based on given arguments. """
if self.completion: self.autocomplete() parser = self.get_parser() namespace = parser.parse_args(argv) if hasattr(namespace, 'func'): self.run_command(namespace)
<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_commands_to_register(self): """ Returns dictionary with commands given during construction. If value is a string, it would be converted into proper class pointer. """
return dict((key, get_class(value)) for key, value in self.simple_commands.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 get_path_directories(): """Return a list of all the directories on the path. """
pth = os.environ['PATH'] if sys.platform == 'win32' and os.environ.get("BASH"): # winbash has a bug.. if pth[1] == ';': # pragma: nocover pth = pth.replace(';', ':', 1) return [p.strip() for p in pth.split(os.pathsep) if p.strip()]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _listdir(pth, extensions): """Non-raising listdir."""
try: return [fname for fname in os.listdir(pth) if os.path.splitext(fname)[1] in extensions] except OSError: # pragma: nocover 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 which(filename, interactive=False, verbose=False): """Yield all executable files on path that matches `filename`. """
exe = [e.lower() for e in os.environ.get('PATHEXT', '').split(';')] if sys.platform != 'win32': # pragma: nocover exe.append('') name, ext = os.path.splitext(filename) has_extension = bool(ext) if has_extension and ext.lower() not in exe: raise ValueError("which can only search for executable files") def match(filenames): """Returns the sorted subset of ``filenames`` that matches ``filename``. """ res = set() for fname in filenames: if fname == filename: # pragma: nocover res.add(fname) # exact match continue fname_name, fname_ext = os.path.splitext(fname) if fname_name == name and fname_ext.lower() in exe: # pragma: nocover res.add(fname) return sorted(res) returnset = set() found = False for pth in get_path_directories(): if verbose: # pragma: nocover print('checking pth..') fnames = _listdir(pth, exe) if not fnames: continue for m in match(fnames): found_file = _normalize(os.path.join(pth, m)) if found_file not in returnset: # pragma: nocover if is_executable(found_file): yield found_file returnset.add(found_file) found = True if not found and interactive: # pragma: nocover print("Couldn't find %r anywhere on the path.." % filename) sys.exit(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 enableEffect(self, name, **kwargs): """Enable an effect in the KezMenu."""
if name not in VALID_EFFECTS: raise KeyError("KezMenu doesn't know an effect of type %s" % name) self.__getattribute__( '_effectinit_{}'.format(name.replace("-", "_")) )(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 disableEffect(self, name): """Disable an effect."""
try: del self._effects[name] self.__getattribute__( '_effectdisable_%s' % name.replace("-", "_") )() except KeyError: pass except AttributeError: 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 _updateEffects(self, time_passed): """Update method for the effects handle"""
for name in self._effects: update_func = getattr( self, '_effectupdate_{}'.format(name.replace("-", "_")), ) update_func(time_passed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _effectinit_enlarge_font_on_focus(self, name, **kwargs): """Init the effect that enlarge the focused menu entry. Keyword arguments can contain enlarge_time and enlarge_factor. """
self._effects[name] = kwargs if "font" not in kwargs: raise TypeError( "enlarge_font_on_focus: font parameter is required" ) if "size" not in kwargs: raise TypeError( "enlarge_font_on_focus: size parameter is required" ) if "enlarge_time" not in kwargs: kwargs['enlarge_time'] = 0.5 if "enlarge_factor" not in kwargs: kwargs['enlarge_factor'] = 2.0 kwargs['raise_font_ps'] = ( kwargs['enlarge_factor'] / kwargs['enlarge_time'] # pixel-per-sec ) for option in self.options: option['font'] = pygame.font.Font(kwargs['font'], kwargs['size']) option['font_current_size'] = kwargs['size'] option['raise_font_factor'] = 1.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 _effectupdate_enlarge_font_on_focus(self, time_passed): """Gradually enlarge the font size of the focused line."""
data = self._effects['enlarge-font-on-focus'] fps = data['raise_font_ps'] final_size = data['size'] * data['enlarge_factor'] for i, option in enumerate(self.options): if i == self.option: # Raise me if option['font_current_size'] < final_size: option['raise_font_factor'] += fps * time_passed elif option['font_current_size'] > final_size: option['raise_font_factor'] = data['enlarge_factor'] elif option['raise_font_factor'] != 1.0: # decrease if option['raise_font_factor'] > 1.0: option['raise_font_factor'] -= fps * time_passed elif option['raise_font_factor'] < 1.0: option['raise_font_factor'] = 1.0 new_size = int(data['size'] * option['raise_font_factor']) if new_size != option['font_current_size']: option['font'] = pygame.font.Font(data['font'], new_size) option['font_current_size'] = new_size