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 call(self, func, *args, **kwargs): """ Call a function, resolving any type-hinted arguments. """
guessed_kwargs = self._guess_kwargs(func) for key, val in guessed_kwargs.items(): kwargs.setdefault(key, val) try: return func(*args, **kwargs) except TypeError as exc: msg = ( "tried calling function %r but failed, probably " ...
<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, filename): """Load disk image for analysis"""
try: self.__session.load(filename) except IOError as e: self.logger.error(e.strerror)
<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_session(self, args): """Print current session information"""
filename = 'Not specified' if self.__session.filename is None \ else self.__session.filename print('{0: <30}: {1}'.format('Filename', 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 _convert_iterable(self, iterable): """Converts elements returned by an iterable into instances of self._wrapper """
# Return original if _wrapper isn't callable if not callable(self._wrapper): return iterable return [self._wrapper(x) for x in iterable]
<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, **kwargs): """Returns the first object encountered that matches the specified lookup parameters. {'url': 'http://site1.tld/', 'published': False, '...
for x in self: if self._check_element(kwargs, x): return x kv_str = self._stringify_kwargs(kwargs) raise QueryList.NotFound( "Element not found with attributes: %s" % kv_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 runserver(ctx, conf, port, foreground): """Run the fnExchange server"""
config = read_config(conf) debug = config['conf'].get('debug', False) click.echo('Debug mode {0}.'.format('on' if debug else 'off')) port = port or config['conf']['server']['port'] app_settings = { 'debug': debug, 'auto_reload': config['conf']['server'].get('auto_reload', 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 as_repository(resource): """ Adapts the given registered resource to its configured repository. :return: object implementing :class:`everest.repositories.int...
reg = get_current_registry() if IInterface in provided_by(resource): resource = reg.getUtility(resource, name='collection-class') return reg.getAdapter(resource, IRepository)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def commit_veto(request, response): # unused request arg pylint: disable=W0613 """ Strict commit veto to use with the transaction manager. Unlike the default com...
tm_header = response.headers.get('x-tm') if not tm_header is None: result = tm_header != 'commit' else: result = not response.status.startswith('2') \ and not tm_header == 'commit' 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 set(cls, key, obj): """ Sets the given object as global object for the given key. """
with cls._lock: if not cls._globs.get(key) is None: raise ValueError('Duplicate key "%s".' % key) cls._globs[key] = obj return cls._globs[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 as_representer(resource, content_type): """ Adapts the given resource and content type to a representer. :param resource: resource to adapt. :param str conte...
reg = get_current_registry() rpr_reg = reg.queryUtility(IRepresenterRegistry) return rpr_reg.create(type(resource), content_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 data_element_tree_to_string(data_element): """ Creates a string representation of the given data element tree. """
# FIXME: rewrite this as a visitor to use the data element tree traverser. def __dump(data_el, stream, offset): name = data_el.__class__.__name__ stream.write("%s%s" % (' ' * offset, name)) offset += 2 ifcs = provided_by(data_el) if ICollectionDataElement in ifcs: ...
<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_path(self, path_num=None): """ make the consumer_state ready for the next MC path :param int path_num: """
for c in self.consumers: c.initialize_path(path_num) self.state = [c.state for c in self.consumers]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finalize_path(self, path_num=None): """finalize path and populate result for ConsumerConsumer"""
for c in self.consumers: c.finalize_path(path_num) self.result = [c.result for c in self.consumers]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finalize(self): """finalize for ConsumerConsumer"""
for c in self.consumers: c.finalize() self.result = [c.result for c in self.consumers]
<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, queue_get): """ get to given consumer states. This function is used for merging of results of parallelized MC. The first state is used for merging ...
for (c, cs) in izip(self.consumers, queue_get): c.get(cs) self.result = [c.result for c in self.consumers]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finalize(self): """finalize for PathConsumer"""
super(TransposedConsumer, self).finalize() self.result = map(list, zip(*self.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 _get_attribute(self, offset): """Determines attribute type at the offset and returns \ initialized attribute object. Returns: MftAttr: One of the attribute o...
attr_type = self.get_uint_le(offset) # Attribute length is in header @ offset 0x4 length = self.get_uint_le(offset + 0x04) data = self.get_chunk(offset, length) return MftAttr.factory(attr_type, 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 find_in_matrix_2d(val, matrix): ''' Returns a tuple representing the index of an item in a 2D matrix. Arguments: - val (str) Value to look for - matrix (list) 2D matrix to search for val in Returns: - (tuple) Ordered pair representing location of val ''' dim = len(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def compute_distance(a, b): ''' Computes a modified Levenshtein distance between two strings, comparing the lowercase versions of each string and accounting for QWERTY distance. Arguments: - a (str) String to compare to 'b' - b (str) String to compare to 'a' Returns: - (int...
<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_defaults(path): ''' Reads file for configuration defaults. Arguments: - path (str) Absolute filepath (usually ~/.licenser) Returns: - (dict) Defaults for name, email, license, .txt extension ''' defaults = {} if os.path.isfile(path): with open(path) as 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_license(name): ''' Returns the closest match to the requested license. Arguments: - name (str) License to use Returns: - (str) License that most closely matches the 'name' parameter ''' filenames = os.listdir(cwd + licenses_loc) licenses = dict(zip(filenames, [-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 get_args(path): ''' Parse command line args & override defaults. Arguments: - path (str) Absolute filepath Returns: - (tuple) Name, email, license, project, ext, year ''' defaults = get_defaults(path) licenses = ', '.join(os.listdir(cwd + licenses_loc)) p = parser(...
<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_license(args): ''' Creates a LICENSE or LICENSE.txt file in the current directory. Reads from the 'assets' folder and looks for placeholders enclosed in curly braces. Arguments: - (tuple) Name, email, license, project, ext, year ''' with open(cwd + licenses_loc + args[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 parse(self): """ parses args json """
data = json.loads(sys.argv[1]) self.config_path = self.decode(data['config_path']) self.subject = self.decode(data['subject']) self.text = self.decode(data['text']) self.html = self.decode(data['html']) self.send_as_one = data['send_as_one'] if 'files' in ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def construct_message(self, email=None): """ construct the email message """
# add subject, from and to self.multipart['Subject'] = self.subject self.multipart['From'] = self.config['EMAIL'] self.multipart['Date'] = formatdate(localtime=True) if email is None and self.send_as_one: self.multipart['To'] = ", ".join(self.addresses) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(self, email=None): """ send email message """
if email is None and self.send_as_one: self.smtp.send_message( self.multipart, self.config['EMAIL'], self.addresses) elif email is not None and self.send_as_one is False: self.smtp.send_message( self.multipart, self.config['EMAIL'], email) ...
<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_email(self): """ main function to construct and send email """
self.connect() if self.send_as_one: self.construct_message() self.send() elif self.send_as_one is False: for email in self.addresses: self.construct_message(email) self.send(email) self.disconnect()
<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_definition(query): """Returns dictionary of id, first names of people who posted on my wall between start and end time"""
try: return get_definition_api(query) except: raise # http://api.wordnik.com:80/v4/word.json/discrimination/definitions?limit=200&includeRelated=true&sourceDictionaries=all&useCanonical=false&includeTags=false&api_key=a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5 import json pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intversion(text=None): """return version as int. 0022 -> 22 0022ubuntu0.1 -> 22 0023 -> 23 1.0 -> 100 1.0.3 -> 103 1:1.0.5+dfsg2-2 -> 105 """
try: s = text if not s: s = version() s = s.split('ubuntu')[0] s = s.split(':')[-1] s = s.split('+')[0] # <100 if s.startswith('00'): i = int(s[0:4]) # >=100 elif '.' in s: ls = s.split('.') l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_current_session(session_id) -> bool: """ Add session_id to flask globals for current request """
try: g.session_id = session_id return True except (Exception, BaseException) as error: # catch all on config update if current_app.config['DEBUG']: print(error) 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 visit_member(self, attribute_key, attribute, member_node, member_data, is_link_node, parent_data, index=None): """ Visits a member node in a resource data tr...
raise NotImplementedError('Abstract method.')
<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_relationship(self, attribute): """ Returns the domain relationship object for the given resource attribute. """
rel = self.__relationships.get(attribute.entity_attr) if rel is None: rel = LazyDomainRelationship(self, attribute, direction= self.relationship_direction) self.__relationships[attribute.entity_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simple_notification(connection, queue_name, exchange_name, routing_key, text_body): """ Publishes a simple notification. Inputs: - connection: A rabbitmq con...
channel = connection.channel() try: channel.queue_declare(queue_name, durable=True, exclusive=False, auto_delete=False) except PreconditionFailed: pass try: channel.exchange_declare(exchange_name, type="fanout", durable=True, auto_delete=False) except PreconditionFailed: ...
<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_url(self, url_or_dict): """ Returns the reversed url given a string or dict and prints errors if MENU_DEBUG is enabled """
if isinstance(url_or_dict, basestring): url_or_dict = {'viewname': url_or_dict} try: return reverse(**url_or_dict) except NoReverseMatch: if MENU_DEBUG: print >>stderr,'Unable to reverse URL with kwargs %s' % url_or_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_time(self): """Time of the TIFF file Currently, only the file modification time is supported. Note that the modification time of the TIFF file is depende...
if isinstance(self.path, pathlib.Path): thetime = self.path.stat().st_mtime else: thetime = np.nan return thetime
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify(path): """Verify that `path` is a valid TIFF file"""
valid = False try: tf = SingleTifHolo._get_tif(path) except (ValueError, IsADirectoryError): pass else: if len(tf) == 1: valid = True return 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 add(entry_point, all_entry_points, auto_write, scripts_path): '''Add Scrim scripts for a python project''' click.echo() if not entry_point and not all_entry_points: raise click.UsageError( 'Missing required option: --entry_point or --all_entry_points' ) if not os.path.ex...
<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 songs(self): '''list of songs in the playlist |force| |coro| Returns ------- list of type :class:`embypy.objects.Audio` ''' items = [] for i in await self.items: if i.type == 'Audio': items.append(i) elif hasattr(i, 'songs'): items.exten...
<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 add_items(self, *items): '''append items to the playlist |coro| Parameters ---------- items : array_like list of items to add(or their ids) See Also -------- remove_items : ''' items = [item.id for item in await self.process(items)] if not items: re...
<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 remove_items(self, *items): '''remove items from the playlist |coro| Parameters ---------- items : array_like list of items to remove(or their ids) See Also -------- add_items : ''' items = [i.id for i in (await self.process(items)) if i in self.items] if...
<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 movies(self): '''list of movies in the collection |force| |coro| Returns ------- list of type :class:`embypy.objects.Movie` ''' items = [] for i in await self.items: if i.type == 'Movie': items.append(i) elif hasattr(i, 'movies'): items....
<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 series(self): '''list of series in the collection |force| |coro| Returns ------- list of type :class:`embypy.objects.Series` ''' items = [] for i in await self.items: if i.type == 'Series': items.append(i) elif hasattr(i, 'series'): item...
<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(self, *args, **kwargs): """ Store a string representation of content_object as target and actor name for fast retrieval and sorting. """
if not self.target: self.target = str(self.content_object) if not self.actor_name: self.actor_name = str(self.actor) super(Activity, self).save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def version_from_frame(frame): """ Given a ``frame``, obtain the version number of the module running there. """
module = getmodule(frame) if module is None: s = "<unknown from {0}:{1}>" return s.format(frame.f_code.co_filename, frame.f_lineno) module_name = module.__name__ variable = "AUTOVERSION_{}".format(module_name.upper()) override = os.environ.get(variable, None) if override is 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 try_fix_num(n): """ Return ``n`` as an integer if it is numeric, otherwise return the input """
if not n.isdigit(): return n if n.startswith("0"): n = n.lstrip("0") if not n: n = "0" return int(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 tupleize_version(version): """ Split ``version`` into a lexicographically comparable tuple. "1.0.3" -> ((1, 0, 3),) "1.0.3-dev" -> ((1, 0, 3), ("dev",)) "1.0...
if version is None: return (("unknown",),) if version.startswith("<unknown"): return (("unknown",),) split = re.split("(?:\.|(-))", version) parsed = tuple(try_fix_num(x) for x in split if x) # Put the tuples in groups by "-" def is_dash(s): return s == "-" group...
<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_version(cls, path, memo={}): """ Return a string describing the version of the repository at ``path`` if possible, otherwise throws ``subprocess.CalledPr...
if path not in memo: memo[path] = subprocess.check_output( "git describe --tags --dirty 2> /dev/null", shell=True, cwd=path).strip().decode("utf-8") v = re.search("-[0-9]+-", memo[path]) if v is not None: # Replace -n- with -b...
<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_repo_instance(cls, path): """ Return ``True`` if ``path`` is a source controlled repository. """
try: cls.get_version(path) return True except subprocess.CalledProcessError: # Git returns non-zero status return False except OSError: # Git unavailable? 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 _sort_modules(mods): """ Always sort `index` or `README` as first filename in list. """
def compare(x, y): x = x[1] y = y[1] if x == y: return 0 if y.stem == "__init__.py": return 1 if x.stem == "__init__.py" or x < y: return -1 return 1 return sorted(mods, key=cmp_to_key(compare))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refs_section(doc): """ Generate a References section. Parameters doc : dict Dictionary produced by numpydoc Returns ------- list of str Markdown for referenc...
lines = [] if "References" in doc and len(doc["References"]) > 0: # print("Found refs") for ref in doc["References"]: # print(ref) ref_num = re.findall("\[([0-9]+)\]", ref)[0] # print(ref_num) ref_body = " ".join(ref.split(" ")[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 examples_section(doc, header_level): """ Generate markdown for Examples section. Parameters doc : dict Dict from numpydoc header_level : int Number of `#`s t...
lines = [] if "Examples" in doc and len(doc["Examples"]) > 0: lines.append(f"{'#'*(header_level+1)} Examples \n") egs = "\n".join(doc["Examples"]) lines += mangle_examples(doc["Examples"]) return lines
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def returns_section(thing, doc, header_level): """ Generate markdown for Returns section. Parameters thing : function Function to produce returns for doc : dict ...
lines = [] return_type = None try: return_type = thing.__annotations__["return"] except AttributeError: try: return_type = thing.fget.__annotations__["return"] except: pass except KeyError: pass if return_type is None: return_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 summary(doc): """ Generate markdown for summary section. Parameters doc : dict Output from numpydoc Returns ------- list of str Markdown strings """
lines = [] if "Summary" in doc and len(doc["Summary"]) > 0: lines.append(fix_footnotes(" ".join(doc["Summary"]))) lines.append("\n") if "Extended Summary" in doc and len(doc["Extended Summary"]) > 0: lines.append(fix_footnotes(" ".join(doc["Extended Summary"]))) lines.append...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def params_section(thing, doc, header_level): """ Generate markdown for Parameters section. Parameters thing : functuon Function to produce parameters from doc :...
lines = [] class_doc = doc["Parameters"] return type_list( inspect.signature(thing), class_doc, "#" * (header_level + 1) + " Parameters\n\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 string_annotation(typ, default): """ Construct a string representation of a type annotation. Parameters typ : type Type to turn into a string default : any D...
try: type_string = ( f"`{typ.__name__}`" if typ.__module__ == "builtins" else f"`{typ.__module__}.{typ.__name__}`" ) except AttributeError: type_string = f"`{str(typ)}`" if default is None: type_string = f"{type_string}, default ``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 type_list(signature, doc, header): """ Construct a list of types, preferring type annotations to docstrings if they are available. Parameters signature : Sig...
lines = [] docced = set() lines.append(header) try: for names, types, description in doc: names, types = _get_names(names, types) unannotated = [] for name in names: docced.add(name) try: typ = signature.pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attributes_section(thing, doc, header_level): """ Generate an attributes section for classes. Prefers type annotations, if they are present. Parameters thing...
# Get Attributes if not inspect.isclass(thing): return [] props, class_doc = _split_props(thing, doc["Attributes"]) tl = type_list(inspect.signature(thing), class_doc, "\n### Attributes\n\n") if len(tl) == 0 and len(props) > 0: tl.append("\n### Attributes\n\n") for prop in pro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enum_doc(name, enum, header_level, source_location): """ Generate markdown for an enum Parameters name : str Name of the thing being documented enum : EnumMe...
lines = [f"{'#'*header_level} Enum **{name}**\n\n"] lines.append(f"```python\n{name}\n```\n") lines.append(get_source_link(enum, source_location)) try: doc = NumpyDocString(inspect.getdoc(thing))._parsed_data lines += summary(doc) except: pass lines.append(f"{'#'*(heade...
<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_doc(name, thing, header_level, source_location): """ Generate markdown for a class or function Parameters name : str Name of the thing being documented th...
if type(thing) is enum.EnumMeta: return enum_doc(name, thing, header_level, source_location) if inspect.isclass(thing): header = f"{'#'*header_level} Class **{name}**\n\n" else: header = f"{'#'*header_level} {name}\n\n" lines = [ header, get_signature(name, thin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def doc_module(module_name, module, output_dir, source_location, leaf): """ Document a module Parameters module_name : str module : module output_dir : str sourc...
path = pathlib.Path(output_dir).joinpath(*module.__name__.split(".")) available_classes = get_available_classes(module) deffed_classes = get_classes(module) deffed_funcs = get_funcs(module) deffed_enums = get_enums(module) alias_funcs = available_classes - deffed_classes if leaf: do...
<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_color(fg=None, bg=None): """Set the current colors. If no arguments are given, sets default colors. """
if fg or bg: _color_manager.set_color(fg, bg) else: _color_manager.set_defaults()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cprint(string, fg=None, bg=None, end='\n', target=sys.stdout): """Print a colored string to the target handle. fg and bg specify foreground- and background c...
_color_manager.set_color(fg, bg) target.write(string + end) target.flush() # Needed for Python 3.x _color_manager.set_defaults()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fprint(fmt, *args, **kwargs): """Parse and print a colored and perhaps formatted string. The remaining keyword arguments are the same as for Python's built-i...
if not fmt: return hascolor = False target = kwargs.get("target", sys.stdout) # Format the string before feeding it to the parser fmt = fmt.format(*args, **kwargs) for txt, markups in _color_format_parser.parse(fmt): if markups != (None, None): _color_manager.set_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def formatcolor(string, fg=None, bg=None): """Wrap color syntax around a string and return it. fg and bg specify foreground- and background colors, respectively....
if fg is bg is None: return string temp = (['fg='+fg] if fg else []) +\ (['bg='+bg] if bg else []) fmt = _color_format_parser._COLOR_DELIM.join(temp) return _color_format_parser._START_TOKEN + fmt +\ _color_format_parser._FMT_TOKEN + string +\ _color_format_parser._...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def formatbyindex(string, fg=None, bg=None, indices=[]): """Wrap color syntax around characters using indices and return it. fg and bg specify foreground- and ba...
if not string or not indices or (fg is bg is None): return string result, p = '', 0 # The lambda syntax is necessary to support both Python 2 and 3 for k, g in itertools.groupby(enumerate(sorted(indices)), lambda x: x[0]-x[1]): tmp = list(map(operator...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def highlight(string, fg=None, bg=None, indices=[], end='\n', target=sys.stdout): """Highlight characters using indices and print it to the target handle. fg and...
if not string or not indices or (fg is bg is None): return p = 0 # The lambda syntax is necessary to support both Python 2 and 3 for k, g in itertools.groupby(enumerate(sorted(indices)), lambda x: x[0]-x[1]): tmp = list(map(operator.itemgetter(1), g))...
<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_param_info(task_params, parameter_map): """ Builds the code block for the GPTool GetParameterInfo method based on the input task_params. :param task_p...
gp_params = [] gp_param_list = [] gp_param_idx_list = [] gp_param_idx = 0 for task_param in task_params: # Setup to gp_param dictionary used to substitute against the parameter info template. gp_param = {} # Convert DataType data_type = task_param['type'].upper() ...
<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_update_parameter(task_params, parameter_map): """ Builds the code block for the GPTool UpdateParameter method based on the input task_params. :param t...
gp_params = [] for param in task_params: if param['direction'].upper() == 'OUTPUT': continue # Convert DataType data_type = param['type'].upper() if 'dimensions' in param: data_type += 'ARRAY' if data_type in parameter_map: gp_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 create_pre_execute(task_params, parameter_map): """ Builds the code block for the GPTool Execute method before the job is submitted based on the input task_p...
gp_params = [_PRE_EXECUTE_INIT_TEMPLATE] for task_param in task_params: if task_param['direction'].upper() == 'OUTPUT': continue # Convert DataType data_type = task_param['type'].upper() if 'dimensions' in task_param: data_type += 'ARRAY' if dat...
<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_post_execute(task_params, parameter_map): """ Builds the code block for the GPTool Execute method after the job is submitted based on the input task_p...
gp_params = [] for task_param in task_params: if task_param['direction'].upper() == 'INPUT': continue # Convert DataType data_type = task_param['type'].upper() if 'dimensions' in task_param: data_type += 'ARRAY' if data_type in parameter_map: ...
<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_default_templates(self): """Load the default templates"""
for importer, modname, is_pkg in pkgutil.iter_modules(templates.__path__): self.register_template('.'.join((templates.__name__, modname)))
<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_hwpack(name): """remove hardware package. :param name: hardware package name (e.g. 'Sanguino') :rtype: None """
targ_dlib = hwpack_dir() / name log.debug('remove %s', targ_dlib) targ_dlib.rmtree()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finalize(self): """finalize for StatisticsConsumer"""
super(StatisticsConsumer, self).finalize() # run statistics on timewave slice w at grid point g # self.result = [(g, self.statistics(w)) for g, w in zip(self.grid, self.result)] # self.result = zip(self.grid, (self.statistics(w) for w in self.result)) self.result = zip(self.grid...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finalize(self): """finalize for StochasticProcessStatisticsConsumer"""
super(StochasticProcessStatisticsConsumer, self).finalize() class StochasticProcessStatistics(self.statistics): """local version to store statistics""" def __str__(self): s = [k.rjust(12) + str(getattr(self, k)) for k in dir(self) if not k.startswith('_')] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_keyword(dist, _, value): # type: (setuptools.dist.Distribution, str, bool) -> None """Add autodetected commands as entry points. Args: dist: The distut...
if value is not True: return dist.entry_points = _ensure_entry_points_is_dict(dist.entry_points) for command, subcommands in six.iteritems(_get_commands(dist)): entry_point = '{command} = rcli.dispatcher:main'.format( command=command) entry_points = dist.entry_points.se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def egg_info_writer(cmd, basename, filename): # type: (setuptools.command.egg_info.egg_info, str, str) -> None """Read rcli configuration and write it out to the...
setupcfg = next((f for f in setuptools.findall() if os.path.basename(f) == 'setup.cfg'), None) if not setupcfg: return parser = six.moves.configparser.ConfigParser() # type: ignore parser.read(setupcfg) if not parser.has_section('rcli') or not parser.items('rcli'): ...
<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(dist # type: setuptools.dist.Distribution ): """Find all commands belonging to the given distribution. Args: dist: The Distribution to search f...
py_files = (f for f in setuptools.findall() if os.path.splitext(f)[1].lower() == '.py') pkg_files = (f for f in py_files if _get_package_name(f) in dist.packages) commands = {} # type: typing.Dict[str, typing.Set[str]] for file_name in pkg_files: with open(file_name) as py_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 _append_commands(dct, # type: typing.Dict[str, typing.Set[str]] module_name, # type: str commands # type:typing.Iterable[_EntryPoint] ): """Append entry poin...
for command in commands: entry_point = '{command}{subcommand} = {module}{callable}'.format( command=command.command, subcommand=(':{}'.format(command.subcommand) if command.subcommand else ''), module=module_name, callable=(':{}'.forma...
<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_module_commands(module): # type: (ast.Module) -> typing.Generator[_EntryPoint, None, None] """Yield all Command objects represented by the python module...
cls = next((n for n in module.body if isinstance(n, ast.ClassDef) and n.name == 'Command'), None) if not cls: return methods = (n.name for n in cls.body if isinstance(n, ast.FunctionDef)) if '__call__' not in methods: return docstring = ast.get_docstring(module) ...
<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_function_commands(module): # type: (ast.Module) -> typing.Generator[_EntryPoint, None, None] """Yield all Command objects represented by python function...
nodes = (n for n in module.body if isinstance(n, ast.FunctionDef)) for func in nodes: docstring = ast.get_docstring(func) for commands, _ in usage.parse_commands(docstring): yield _EntryPoint(commands[0], next(iter(commands[1:]), None), func.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 convert(b): ''' takes a number of bytes as an argument and returns the most suitable human readable unit conversion. ''' if b > 1024**3: hr = round(b/1024**3) unit = "GB" elif b > 1024**2: hr = round(b/1024**2) unit = "MB" else: hr = round(b/1024) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def calc(path): ''' Takes a path as an argument and returns the total size in bytes of the file or directory. If the path is a directory the size will be calculated recursively. ''' total = 0 err = None if os.path.isdir(path): try: for entry in os.scandir(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 du(path): ''' Put it all together! ''' size, err = calc(path) if err: return err else: hr, unit = convert(size) hr = str(hr) result = hr + " " + unit 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 handle(self, **kwargs): """ Simply re-saves all objects from models listed in settings.TIMELINE_MODELS. Since the timeline app is now following these models,...
for item in settings.ACTIVITY_MONITOR_MODELS: app_label, model = item['model'].split('.', 1) content_type = ContentType.objects.get(app_label=app_label, model=model) model = content_type.model_class() objects = model.objects.all() for object in objects: try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def album_primary_image_url(self): '''The image of the album''' path = '/Items/{}/Images/Primary'.format(self.album_id) return self.connector.get_url(path, attach_api_key=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 stream_url(self): '''stream for this song - not re-encoded''' path = '/Audio/{}/universal'.format(self.id) return self.connector.get_url(path, userId=self.connector.userid, MaxStreamingBitrate=140000000, Container='opus', TranscodingContainer='opus...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data(self): """ raw image data """
if self._data is None: request = urllib.Request(self._url, headers={'User-Agent': USER_AGENT}) with contextlib.closing(self._connection.urlopen(request)) as response: self._data = response.read() return self._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 make_filter_string(cls, filter_specification): """ Converts the given filter specification to a CQL filter expression. """
registry = get_current_registry() visitor_cls = registry.getUtility(IFilterSpecificationVisitor, name=EXPRESSION_KINDS.CQL) visitor = visitor_cls() filter_specification.accept(visitor) return str(visitor.expression)
<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_order_string(cls, order_specification): """ Converts the given order specification to a CQL order expression. """
registry = get_current_registry() visitor_cls = registry.getUtility(IOrderSpecificationVisitor, name=EXPRESSION_KINDS.CQL) visitor = visitor_cls() order_specification.accept(visitor) return str(visitor.expression)
<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_slice_key(cls, start_string, size_string): """ Converts the given start and size query parts to a slice key. :return: slice key :rtype: slice """
try: start = int(start_string) except ValueError: raise ValueError('Query parameter "start" must be a number.') if start < 0: raise ValueError('Query parameter "start" must be zero or ' 'a positive number.') try: ...
<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_slice_strings(cls, slice_key): """ Converts the given slice key to start and size query parts. """
start = slice_key.start size = slice_key.stop - start return (str(start), str(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 match(self, expression=None, xpath=None, namespaces=None): """decorator that allows us to match by expression or by xpath for each transformation method"""
class MatchObject(Dict): pass def _match(function): self.matches.append( MatchObject(expression=expression, xpath=xpath, function=function, namespaces=namespaces)) def wrapper(self, *args, **params): return function(self, *args, **para...
<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_match(self, elem): """for the given elem, return the @match function that will be applied"""
for m in self.matches: if (m.expression is not None and eval(m.expression)==True) \ or (m.xpath is not None and len(elem.xpath(m.xpath, namespaces=m.namespaces)) > 0): LOG.debug("=> match: %r" % m.expression) return 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 Element(self, elem, **params): """Ensure that the input element is immutable by the transformation. Returns a single element."""
res = self.__call__(deepcopy(elem), **params) if len(res) > 0: return res[0] 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 read_properties(filename): """read properties file into bunch. :param filename: string :rtype: bunch (dict like and object like) """
s = path(filename).text() dummy_section = 'xxx' cfgparser = configparser.RawConfigParser() # avoid converting options to lower case cfgparser.optionxform = str cfgparser.readfp(StringIO('[%s]\n' % dummy_section + s)) bunch = AutoBunch() for x in cfgparser.options(dummy_section): ...
<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_request_url(self, interface, method, version, parameters): """Create the URL to submit to the Steam Web API interface: Steam Web API interface contain...
if 'format' in parameters: parameters['key'] = self.apikey else: parameters.update({'key' : self.apikey, 'format' : self.format}) version = "v%04d" % (version) url = "http://api.steampowered.com/%s/%s/%s/?%s" % (interface, method, version, urlencode(p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retrieve_request(self, url): """Open the given url and decode and return the response url: The url to open. """
try: data = urlopen(url) except: print("Error Retrieving Data from Steam") sys.exit(2) return data.read().decode('utf-8')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def return_data(self, data, format=None): """Format and return data appropriate to the requested API format. data: The data retured by the api request """
if format is None: format = self.format if format == "json": formatted_data = json.loads(data) else: formatted_data = data return formatted_data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_friends_list(self, steamID, relationship='all', format=None): """Request the friends list of a given steam ID filtered by role. steamID: The user ID rela...
parameters = {'steamid' : steamID, 'relationship' : relationship} if format is not None: parameters['format'] = format url = self.create_request_url(self.interface, 'GetFriendsList', 1, parameters) data = self.retrieve_request(url) return self.return_data...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_player_bans(self, steamIDS, format=None): """Request the communities a steam id is banned in. steamIDS: Comma-delimited list of SteamIDs format: Return f...
parameters = {'steamids' : steamIDS} if format is not None: parameters['format'] = format url = self.create_request_url(self.interface, 'GetPlayerBans', 1, parameters) data = self.retrieve_request(url) return self.return_data(data, format=format)