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 " "because it takes arguments that cannot be resolved" ) % func raise DiayException(msg) from exc
<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, 'id': 1} {'url': 'http://site1.tld/', 'published': True, 'id': 2} {'url': 'http://site1.tld/', 'published': True, 'id': 2} If the QueryList contains multiple elements that match the criteria, only the first match will be returned. Use ``filter()`` to retrieve the entire set. If no match is found in the QueryList, the method will raise a ``NotFound`` exception. Traceback (most recent call last): File "<stdin>", line 1, in <module> File "querylist/list.py", line 113, in get "Element not found with attributes: %s" % kv_str) querylist.list.NotFound: Element not found with attributes: id=None """
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), } handlers_settings = __create_handler_settings(config) if foreground: click.echo('Requested mode: foreground') start_app(port, app_settings, handlers_settings) else: click.echo('Requested mode: background') # subprocess.call([sys.executable, 'yourscript.py'], env=os.environ.copy()) raise NotImplementedError
<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.interfaces.IRepository`. """
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 commit veto supplied with the transaction manager, this will veto all commits for HTTP status codes other than 2xx unless a commit is explicitly requested by setting the "x-tm" response header to "commit". As with the default commit veto, the commit is always vetoed if the "x-tm" response header is set to anything other than "commit". """
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 content_type: content (MIME) type to obtain a representer for. """
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: stream.write("[") first_member = True for member_data_el in data_el.get_members(): if first_member: stream.write('%s' % os.linesep + ' ' * offset) first_member = False else: stream.write(',%s' % os.linesep + ' ' * offset) __dump(member_data_el, stream, offset) stream.write("]") else: stream.write("(") if ILinkedDataElement in ifcs: stream.write("url=%s, kind=%s, relation=%s" % (data_el.get_url(), data_el.get_kind(), data_el.get_relation())) else: first_attr = True for attr_name, attr_value in iteritems_(data_el.data): if first_attr: first_attr = False else: stream.write(',%s' % os.linesep + ' ' * (offset + len(name) + 1)) if attr_value is None: continue if not IResourceDataElement in provided_by(attr_value): stream.write("%s=%s" % (attr_name, attr_value)) else: stream.write("%s=" % attr_name) __dump(attr_value, stream, offset) stream.write(')') stream = NativeIO() __dump(data_element, stream, 0) return stream.getvalue()
<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 in place. The states must be disjoint. :param object queue_get: second consumer state """
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 objects \ (eg. :class:`~.mft_attribute.MftAttrFilename`). None: If atttribute type does not mach any one of the supported \ attribute types. """
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(matrix[0]) item_index = 0 for row in matrix: for i in row: if i == val: break item_index += 1 if i == val: break loc = (int(item_index / dim), item_index % dim) return loc
<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) Number representing closeness of 'a' and 'b' (lower is better) ''' # check simple cases first if not a: return len(b) if not b: return len(a) if a == b or str.lower(a) == str.lower(b): return 0 # lowercase each string a = str.lower(a) b = str.lower(b) # create empty vectors to store costs vector_1 = [-1] * (len(b) + 1) vector_2 = [-1] * (len(b) + 1) # set default values for i in range(len(vector_1)): vector_1[i] = i # compute distance for i in range(len(a)): vector_2[0] = i + 1 for j in range(len(b)): penalty = 0 if a[i] == b[j] else compute_qwerty_distance(a[i], b[j]) vector_2[j + 1] = min(vector_2[j] + 1, vector_1[j + 1] + 1, vector_1[j] + penalty) for j in range(len(vector_1)): vector_1[j] = vector_2[j] return vector_2[len(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 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: for line in f: line = line.strip() if '=' not in line or line.startswith('#'): continue k, v = line.split('=', 1) v = v.strip('"').strip("'") defaults[k] = v return defaults else: return {}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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] * len(filenames))) for l in licenses: licenses[l] = compute_distance(name, l) return min(licenses, key=(lambda k: licenses[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 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(description='tool for adding open source licenses to your projects. available licenses: %s' % licenses) _name = False if defaults.get('name') else True _email = False if defaults.get('email') else True _license = False if defaults.get('license') else True p.add_argument('-n', dest='name', required=_name, help='name') p.add_argument('-e', dest='email', required=_email, help='email') p.add_argument('-l', dest='license', required=_license, help='license') p.add_argument('-p', dest='project', required=False, help='project') p.add_argument('-v', '--version', action='version', version='%(prog)s {version}'.format(version=version)) p.add_argument('--txt', action='store_true', required=False, help='add .txt to filename') args = p.parse_args() name = args.name if args.name else defaults.get('name') email = args.email if args.email else defaults.get('email') license = get_license(args.license) if args.license else defaults.get('license') project = args.project if args.project else os.getcwd().split('/')[-1] ext = '.txt' if args.txt else '' year = str(date.today().year) return (name, email, license, project, ext, year)
<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]) as f: license = f.read() license = license.format(name=args[0], email=args[1], license=args[2], project=args[3], year=args[5]) with open('LICENSE' + args[4], 'w') as f: f.write(license) print('licenser: license file added to current directory')
<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 data: self.parse_files(data['files']) self.ccs = data['ccs'] self.addresses = data['addresses'] if not self.addresses: raise ValueError( 'Atleast one email address is required to send an 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 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) elif email is not None and self.send_as_one is False: self.multipart['To'] = email # add ccs if self.ccs is not None and self.ccs: self.multipart['Cc'] = ", ".join(self.ccs) # add html and text body html = MIMEText(self.html, 'html') alt_text = MIMEText(self.text, 'plain') self.multipart.attach(html) self.multipart.attach(alt_text) for file in self.files: self.multipart.attach(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 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) self.multipart = MIMEMultipart('alternative')
<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 payload = {'q': query, 'limit': 200, 'includeRelated': 'true', 'sourceDictionaries': 'all', 'useCanonical': 'false', 'includeTags': 'false', 'api_key': 'a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5'} url = 'http://api.wordnik.com:80/v4/word.json/%s/definitions' % query r = requests.get(url, params=payload) result = json.loads(r.text) 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 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('.') ls += [0, 0, 0] i = int(ls[0]) * 100 + int(ls[1]) * 10 + int(ls[2]) except ValueError: print ('Can not parse version: %s' % text) raise return i
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 tree. :param tuple attribute_key: tuple containing the attribute tokens identifying the member node's position in the resource data tree. :param attribute: mapped attribute holding information about the member node's name (in the parent) and type etc. :type attribute: :class:`everest.representers.attributes.MappedAttribute` :param member_node: the node holding resource data. This is either a resource instance (when using a :class:`ResourceTreeTraverser` on a tree of resources) or a data element instance (when using a :class:`DataElementTreeTraverser` on a data element tree. :param dict member_data: dictionary holding all member data extracted during traversal (with mapped attributes as keys). :param bool is_link_node: indicates if the given member node is a link. :param dict parent_data: dictionary holding all parent data extracted during traversal (with mapped attributes as keys). :param int index: this indicates a member node's index in a collection parent node. If the parent node is a member node, it will be `None`. """
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_attr] = rel return rel
<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 connection object. - queue_name: The name of the queue to be checked or created. - exchange_name: The name of the notification exchange. - routing_key: The routing key for the exchange-queue binding. - text_body: The text to be published. """
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: pass channel.queue_bind(queue_name, exchange_name, routing_key=routing_key) message = Message(text_body) channel.basic_publish(message, exchange_name, routing_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 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 dependent on the file system and may have temporal resolution as low as 3 seconds. """
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.exists('setup.py'): raise click.UsageError('No setup.py found.') setup_data = parse_setup('setup.py') console_scripts = get_console_scripts(setup_data) scripts = [] if all_entry_points and console_scripts: # Make sure our entry points start with py for entry in console_scripts: if not entry.startswith('py'): click.echo('Your python entry_points must start with py.') click.echo('Found: ' + entry) raise click.Abort() for entry in console_scripts: click.echo('Found entry_point: ' + entry) py_entry_point = entry entry_point = entry[2:] more_scripts = copy_templates( entry_point, py_entry_point, auto_write, scripts_path ) for script in more_scripts: click.echo(' Created ' + script) scripts.extend(more_scripts) elif entry_point: if not entry_point.startswith('py'): click.echo('Your python entry_points must start with py.') raise click.Abort() if entry_point not in console_scripts: click.echo(entry_point + ' not found in your setups entry_points') click.echo('You will need to add it afterward if you continue...') click.echo('') click.confirm('Do you want to continue?', abort=True) click.echo('\nCreating scripts for: ' + entry_point) py_entry_point = entry_point entry_point = entry_point[2:] more_scripts = copy_templates( entry_point, py_entry_point, auto_write, scripts_path ) for script in more_scripts: click.echo(' Created ' + script) scripts.extend(more_scripts) click.echo('\n\nAdd the following section to your package setup:\n') click.echo('scripts=[') for script in scripts: click.echo(" '{}',".format(script)) click.echo('],')
<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.extend(await i.songs) return 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 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: return await self.connector.post('Playlists/{Id}/Items'.format(Id=self.id), data={'Ids': ','.join(items)}, remote=False )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
async def 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 not items: return await self.connector.delete( 'Playlists/{Id}/Items'.format(Id=self.id), EntryIds=','.join(items), remote=False )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
async def 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.extend(await i.movies) return 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'): items.extend(await i.series) return 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 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 not None: return override while True: try: get_distribution(module_name) except DistributionNotFound: # Look at what's to the left of "." module_name, dot, _ = module_name.partition(".") if dot == "": # There is no dot, nothing more we can do. break else: return getversion(module_name) 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 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.3-rc-5" -> ((1, 0, 3), ("rc",), (5,)) """
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 == "-" grouped = groupby(parsed, is_dash) return tuple(tuple(group) for dash, group in grouped if not dash)
<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.CalledProcessError``. (Note: memoizes the result in the ``memo`` parameter) """
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 -branchname-n- branch = r"-{0}-\1-".format(cls.get_branch(path)) (memo[path], _) = re.subn("-([0-9]+)-", branch, memo[path], 1) return memo[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 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 references section """
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:]) # print(f"[^{ref_num}] {ref_body}" + "\n") lines.append(f"[^{ref_num}]: {ref_body}" + "\n\n") # print(lines) 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 examples_section(doc, header_level): """ Generate markdown for Examples section. Parameters doc : dict Dict from numpydoc header_level : int Number of `#`s to use for header Returns ------- list of str Markdown for examples section """
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 Dict from numpydoc header_level : int Number of `#`s to use for header Returns ------- list of str Markdown for examples section """
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 = "" else: # print(f"{thing} has annotated return type {return_type}") try: return_type = ( f"{return_type.__name__}" if return_type.__module__ == "builtins" else f"{return_type.__module__}.{return_type.__name__}" ) except AttributeError: return_type = str(return_type) # print(return_type) try: if "Returns" in doc and len(doc["Returns"]) > 0 or return_type != "": lines.append(f"{'#'*(header_level+1)} Returns\n") if return_type != "" and len(doc["Returns"]) == 1: name, typ, desc = doc["Returns"][0] if typ != "": lines.append(f"- `{name}`: ``{return_type}``") else: lines.append(f"- ``{return_type}``") lines.append("\n\n") if desc != "": lines.append(f" {' '.join(desc)}\n\n") elif return_type != "": lines.append(f"- ``{return_type}``") lines.append("\n\n") else: for name, typ, desc in doc["Returns"]: if ":" in name: name, typ = name.split(":") if typ != "": line = f"- `{name}`: {mangle_types(typ)}" else: line = f"- {mangle_types(name)}" line += "\n\n" lines.append(line) lines.append(f" {' '.join(desc)}\n\n") except Exception as e: # print(e) # print(doc) pass 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 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("\n") 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 params_section(thing, doc, header_level): """ Generate markdown for Parameters section. Parameters thing : functuon Function to produce parameters from doc : dict Dict from numpydoc header_level : int Number of `#`s to use for header Returns ------- list of str Markdown for examples section """
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 Default value (if any) of the type Returns ------- str String version of the type annotation """
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``" elif default == inspect._empty: pass else: type_string = f"{type_string}, default ``{default}``" return type_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 type_list(signature, doc, header): """ Construct a list of types, preferring type annotations to docstrings if they are available. Parameters signature : Signature Signature of thing doc : list of tuple Numpydoc's type list section Returns ------- list of str Markdown formatted type list """
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.parameters[name].annotation if typ == inspect._empty: raise AttributeError default = signature.parameters[name].default type_string = string_annotation(typ, default) lines.append(f"- `{name}`: {type_string}") lines.append("\n\n") except (AttributeError, KeyError): unannotated.append(name) # No annotation if len(unannotated) > 0: lines.append("- ") lines.append(", ".join(f"`{name}`" for name in unannotated)) if types != "" and len(unannotated) > 0: lines.append(f": {mangle_types(types)}") lines.append("\n\n") lines.append(f" {' '.join(description)}\n\n") for names, types, description in doc: names, types = _get_names(names, types) for name in names: if name not in docced: try: typ = signature.parameters[name].annotation default = signature.parameters[name].default type_string = string_annotation(typ, default) lines.append(f"- `{name}`: {type_string}") lines.append("\n\n") except (AttributeError, KeyError): lines.append(f"- `{name}`") lines.append("\n\n") except Exception as e: print(e) return lines if len(lines) > 1 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 attributes_section(thing, doc, header_level): """ Generate an attributes section for classes. Prefers type annotations, if they are present. Parameters thing : class Class to document doc : dict Numpydoc output header_level : int Number of `#`s to use for header Returns ------- list of str Markdown formatted attribute list """
# 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 props: tl.append(f"- [`{prop}`](#{prop})\n\n") return tl
<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 : EnumMeta Enum to document header_level : int Heading level source_location : str URL of repo containing source code """
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"{'#'*(header_level + 1)} Members\n\n") lines += [f"- `{str(v).split('.').pop()}`: `{v.value}` \n\n" for v in enum] 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 to_doc(name, thing, header_level, source_location): """ Generate markdown for a class or function Parameters name : str Name of the thing being documented thing : class or function Class or function to document header_level : int Heading level source_location : str URL of repo containing source code """
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, thing), get_source_link(thing, source_location), ] try: doc = NumpyDocString(inspect.getdoc(thing))._parsed_data lines += summary(doc) lines += attributes_section(thing, doc, header_level) lines += params_section(thing, doc, header_level) lines += returns_section(thing, doc, header_level) lines += examples_section(doc, header_level) lines += notes_section(doc) lines += refs_section(doc) except Exception as e: # print(f"No docstring for {name}, src {source_location}: {e}") pass 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 doc_module(module_name, module, output_dir, source_location, leaf): """ Document a module Parameters module_name : str module : module output_dir : str source_location : str leaf : bool """
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: doc_path = path.with_suffix(".md") else: doc_path = path / "index.md" doc_path.parent.mkdir(parents=True, exist_ok=True) module_path = "/".join(module.__name__.split(".")) doc = [f"title: {module_name.split('.')[-1]}" + "\n"] module_doc = module.__doc__ # Module overview documentation if module_doc is not None: doc += to_doc(module.__name__, module, 1, source_location) else: doc.append(f"# {module.__name__}\n\n") doc.append("\n\n") for cls_name, cls in sorted(deffed_enums) + sorted(deffed_classes): doc += to_doc(cls_name, cls, 2, source_location) class_methods = [ x for x in inspect.getmembers(cls, inspect.isfunction) if (not x[0].startswith("_")) and deffed_here(x[1], cls) ] class_methods += inspect.getmembers(cls, lambda o: isinstance(o, property)) if len(class_methods) > 0: doc.append("### Methods \n\n") for method_name, method in class_methods: doc += to_doc(method_name, method, 4, source_location) for fname, func in sorted(deffed_funcs): doc += to_doc(fname, func, 2, source_location) return doc_path.absolute(), "".join(doc)
<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 colors, respectively. The remaining keyword arguments are the same as for Python's built-in print function. Colors are returned to their defaults before the function returns. """
_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-in print function. Colors are returning to their defaults before the function returns. """
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_color(*markups) hascolor = True else: if hascolor: _color_manager.set_defaults() hascolor = False target.write(txt) target.flush() # Needed for Python 3.x _color_manager.set_defaults() target.write(kwargs.get('end', '\n')) _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 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._STOP_TOKEN
<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 background colors, respectively. """
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.itemgetter(1), g)) s, e = tmp[0], tmp[-1]+1 if s < len(string): result += string[p:s] result += formatcolor(string[s:e], fg, bg) p = e if p < len(string): result += string[p:] 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 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 bg specify foreground- and background colors, respectively. The remaining keyword arguments are the same as for Python's built-in print function. """
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)) s, e = tmp[0], tmp[-1]+1 target.write(string[p:s]) target.flush() # Needed for Python 3.x _color_manager.set_color(fg, bg) target.write(string[s:e]) target.flush() # Needed for Python 3.x _color_manager.set_defaults() p = e if p < len(string): target.write(string[p:]) target.write(end)
<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_params: A list of task parameters to map to GPTool parameters. :return: A string representing the code block to the GPTool GetParameterInfo method. """
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() if 'dimensions' in task_param: if len(task_param['dimensions'].split(',')) > 1: raise UnknownDataTypeError('Only one-dimensional arrays are supported.') data_type += 'ARRAY' if data_type in parameter_map: gp_param['dataType'] = parameter_map[data_type].data_type else: # No Mapping exists for this data type! raise UnknownDataTypeError('Unable to map task datatype: ' + data_type + '. A template must be created.') gp_param['name'] = task_param['name'] gp_param['displayName'] = task_param['display_name'] gp_param['direction'] = _DIRECTION_MAP[task_param['direction']] gp_param['paramType'] = 'Required' if task_param['required'] else 'Optional' # ENVI/IDL output type translates to a derived output type in Arc if gp_param['direction'] is 'Output': gp_param['paramType'] = 'Derived' gp_param['multiValue'] = True if 'dimensions' in task_param else False # Substitute values into the template gp_params.append(parameter_map[data_type].get_parameter(task_param).substitute(gp_param)) # Convert the default value if 'default_value' in task_param: gp_param['defaultValue'] = task_param['default_value'] gp_params.append(parameter_map[data_type].default_value().substitute(gp_param)) # Convert any choicelist if 'choice_list' in task_param: gp_param['choiceList'] = task_param['choice_list'] gp_params.append(_CHOICELIST_TEMPLATE.substitute(gp_param)) # Construct the parameter list and indicies for future reference for param_name in parameter_map[data_type].parameter_names(task_param): gp_param_list.append(param_name.substitute(gp_param)) gp_param_idx_list.append(_PARAM_INDEX_TEMPLATE.substitute( {'name': param_name.substitute(gp_param), 'idx': gp_param_idx})) gp_param_idx += 1 # Construct the final parameter string gp_params.append(_PARAM_RETURN_TEMPLATE.substitute({'paramList': convert_list(gp_param_list)})) return ''.join((''.join(gp_params), ''.join(gp_param_idx_list)))
<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 task_params: A list of task parameters from the task info structure. :return: A string representing the code block to the GPTool UpdateParameter method. """
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.append(parameter_map[data_type].update_parameter().substitute(param)) return ''.join(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_params. :param task_params: A list of task parameters from the task info structure. :return: A string representing the code block to the GPTool Execute method. """
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 data_type in parameter_map: gp_params.append(parameter_map[data_type].pre_execute().substitute(task_param)) gp_params.append(_PRE_EXECUTE_CLEANUP_TEMPLATE) return ''.join(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_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_params. :param task_params: A list of task parameters from the task info structure. :return: A string representing the code block to the GPTool Execute method. """
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: gp_params.append(parameter_map[data_type].post_execute().substitute(task_param)) return ''.join(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 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, map(self.statistics, 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 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('_')] return '\n'.join(s) sps = StochasticProcessStatistics([0, 0]) keys = list() for k in dir(sps): if not k.startswith('_'): a = getattr(sps, k) if isinstance(a, (int, float, str)): keys.append(k) else: delattr(sps, k) for k in keys: setattr(sps, k, list()) grid = list() for g, r in self.result: grid.append(g) for k in keys: a = getattr(sps, k) a.append(getattr(r, k)) self.result = grid, sps
<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 distutils Distribution object for the project being installed. _: The keyword used in the setup function. Unused. value: The value set to the keyword in the setup function. If the value is not True, this function will do nothing. """
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.setdefault('console_scripts', []) if entry_point not in entry_points: entry_points.append(entry_point) dist.entry_points.setdefault('rcli', []).extend(subcommands)
<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 egg info. Args: cmd: An egg info command instance to use for writing. basename: The basename of the file to write. filename: The full path of the file to write into the egg info. """
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'): return config = dict(parser.items('rcli')) # type: typing.Dict[str, typing.Any] for k, v in six.iteritems(config): if v.lower() in ('y', 'yes', 'true'): config[k] = True elif v.lower() in ('n', 'no', 'false'): config[k] = False else: try: config[k] = json.loads(v) except ValueError: pass cmd.write_file(basename, filename, json.dumps(config))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_commands(dist # type: setuptools.dist.Distribution ): """Find all commands belonging to the given distribution. Args: dist: The Distribution to search for docopt-compatible docstrings that can be used to generate command entry points. Returns: A dictionary containing a mapping of primary commands to sets of subcommands. """
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: module = typing.cast(ast.Module, ast.parse(py_file.read())) module_name = _get_module_name(file_name) _append_commands(commands, module_name, _get_module_commands(module)) _append_commands(commands, module_name, _get_class_commands(module)) _append_commands(commands, module_name, _get_function_commands(module)) return commands
<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 point strings representing the given Command objects. Args: dct: The dictionary to append with entry point strings. Each key will be a primary command with a value containing a list of entry point strings representing a Command. module_name: The name of the module in which the command object resides. commands: A list of Command objects to convert to entry point strings. """
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=(':{}'.format(command.callable) if command.callable else ''), ) dct.setdefault(command.command, set()).add(entry_point)
<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. Module commands consist of a docopt-style module docstring and a callable Command class. Args: module: An ast.Module object used to retrieve docopt-style commands. Yields: Command objects that represent entry points to append to setup.py. """
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) for commands, _ in usage.parse_commands(docstring): yield _EntryPoint(commands[0], next(iter(commands[1:]), None), None)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_function_commands(module): # type: (ast.Module) -> typing.Generator[_EntryPoint, None, None] """Yield all Command objects represented by python functions in the module. Function commands consist of all top-level functions that contain docopt-style docstrings. Args: module: An ast.Module object used to retrieve docopt-style commands. Yields: Command objects that represent entry points to append to setup.py. """
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) unit = "KB" return hr, unit
<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): try: is_dir = entry.is_dir(follow_symlinks=False) except (PermissionError, FileNotFoundError): err = "!" return total, err if is_dir: result = calc(entry.path) total += result[0] err = result[1] if err: return total, err else: try: total += entry.stat(follow_symlinks=False).st_size except (PermissionError, FileNotFoundError): err = "!" return total, err except (PermissionError, FileNotFoundError): err = "!" return total, err else: total += os.path.getsize(path) return total, err
<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, it will register each item as it is re-saved. The purpose of this script is to register content in your database that existed prior to installing the timeline app. """
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: object.save() except Exception as e: print("Error saving: {}".format(e))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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', AudioCodec='opus', MaxSampleRate=48000, PlaySessionId=1496213367201 #TODO no hard code )
<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: size = int(size_string) except ValueError: raise ValueError('Query parameter "size" must be a number.') if size < 1: raise ValueError('Query parameter "size" must be a positive ' 'number.') return slice(start, start + 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 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, **params) return wrapper return _match
<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): setattr(bunch, x, cfgparser.get(dummy_section, str(x))) return bunch
<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 containing methods. method: The method to call. version: The version of the method. paramters: Parameters to supply to the method. """
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(parameters)) return 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 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 relationship: Type of friend to request (all, friend) format: Return format. None defaults to json. (json, xml, vdf) """
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(data, format=format)
<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 format. None defaults to json. (json, xml, vdf) """
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)