output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Reset sort state set collection and emit resetModel signal
How would you explain what the following Python 3 function does def set_collection(self, collection): self.beginResetModel() self.collection = collection self.sort_state = (-1, False) self.endResetModel()
As a Python code translator, you convert algorithms and pseudocode into Python.
Changes the item at index in collection. Emit dataChanged signal.
Here you have a function in Python 3, explain what it does def set_item(self, index, new_item): row = index.row() if hasattr(index, "row") else index self.collection[row] = new_item self.dataChanged.emit(self.index( row, 0), self.index(row, self.rowCount() - 1))
As a Python code composer, you craft elegant and concise scripts.
Uses given data setter and emit modelReset signal
Make a summary of the following Python 3 code def set_data(self, index, value): acces, field = self.get_item(index), self.header[index.column()] self.beginResetModel() self.set_data_hook(acces, field, value) self.endResetModel()
You are a Python code architect, reviewing and designing scalable and efficient code
def _set_id(self, Id, is_added, index): """Update selected_ids and emit dataChanged""" if is_added: self.selected_ids.add(Id) else: self.selected_ids.remove(Id) self.dataChanged.emit(index, index)
Create a Python 3 function to update selected_ids and emit dataChanged
As a Python code analyst, you investigate and solve complex coding mysteries
def setData(self, index: QModelIndex, value, role=None): """Update selected_ids on click on index cell.""" if not (index.isValid() and role == Qt.CheckStateRole): return False c_id = self.get_item(index).Id self._set_id(c_id, value == Qt.Checked, index) return True
Write a Python 3 script to update selected_ids on click on index cell.
You are a Python code generator, capable of creating scripts from specifications.
def set_by_Id(self, Id, is_added): """Update selected_ids with given Id""" row = self.collection.index_from_id(Id) if row is None: return self._set_id(Id, is_added, self.index(row, 0))
Create a Python 3 function to update selected_ids with given Id
As a Python code analyst, you investigate and solve complex coding mysteries
Add resize behavior on edit
Here you have a function in Python 3, explain what it does def _setup_delegate(self): delegate = self.DELEGATE_CLASS(self) self.setItemDelegate(delegate) delegate.sizeHintChanged.connect( lambda index: self.resizeRowToContents(index.row())) if self.RESIZE_COLUMN: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Draw the placeholder text for the current item.
Can you tell what is the following Python 3 function doing def _draw_placeholder(self): if self.model().rowCount() == 0: painter = QPainter(self.viewport()) painter.setFont(_custom_font(is_italic=True)) painter.drawText(self.rect().adjusted(0, 0, -5, -5), Qt.AlignCenter | Qt....
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the currently selected item or None
How would you explain what the following Python 3 function does def get_current_item(self): l = self.selectedIndexes() if len(l) > 0: return self.model().get_item(l[0])
You are a Python code analyst, evaluating scripts for potential improvements.
Return a model with a collection from a list of entries
How would you explain what the following Python 3 function does def model_from_list(l, header): col = groups.sortableListe(PseudoAccesCategorie(n) for n in l) return MultiSelectModel(col, header)
As a Python code composer, you craft elegant and concise scripts.
def _parse_status_code(response): """ Return error string code if the response is an error, otherwise ``"OK"`` """ # This happens when a status response is expected if isinstance(response, string_types): return response # This happens when a list of structs are expected is_single_l...
Create a Python 3 function for parsing the status code from the response.
As a Python code analyst, you investigate and solve complex coding mysteries
def remove_zone_record(self, id, domain, subdomain=None): """ Remove the zone record with the given ID that belongs to the given domain and sub domain. If no sub domain is given the wildcard sub-domain is assumed. """ if subdomain is None: subdomain = "@" ...
How would you implement a function in Python 3 that removes the zone record with the given ID that belongs to the given domain and sub - domain.
As a python code expert, you are capable of creating scripts from specifications.
Parse the module and class name part of the fully qualifed class name.
How would you explain what the following Python 3 function does def parse_module_class(self): cname = self.class_name match = re.match(self.CLASS_REGEX, cname) if not match: raise ValueError(f'not a fully qualified class name: {cname}') return match.groups()
As a Python code analyst, you investigate and solve complex coding mysteries
def get_module_class(self): """Return the module and class as a tuple of the given class in the initializer. :param reload: if ``True`` then reload the module before returning the class """ pkg, cname = self.parse_module_class() logger.debug(f'pkg: {pkg}, class:...
Create a Python 3 function to return the module and class in the initializer.
You are a Python code generator, capable of creating scripts from specifications.
Create an instance of the specified class in the initializer.
Can you tell what is the following Python 3 function doing def instance(self, *args, **kwargs): mod, cls = self.get_module_class() inst = cls(*args, **kwargs) logger.debug(f'inst: {inst}') return inst
You are a Python code architect, reviewing and designing scalable and efficient code
Convenciene method to set the log level of the module given in the initializer of this class.
Given the following Python 3 function, write the documentation def set_log_level(self, level=logging.INFO): mod, cls = self.parse_module_class() logging.getLogger(mod).setLevel(level)
You are a Python code analyst, evaluating scripts for potential improvements.
Register a class with the factory.
Can you generate a brief explanation for the following Python 3 code def register(cls, instance_class, name=None): if name is None: name = instance_class.__name__ cls.INSTANCE_CLASSES[name] = instance_class
As a Python code translator, you convert algorithms and pseudocode into Python.
def _find_class(self, class_name): "Resolve the class from the name." classes = {} classes.update(globals()) classes.update(self.INSTANCE_CLASSES) logger.debug(f'looking up class: {class_name}') cls = classes[class_name] logger.debug(f'found class: {cls}') ...
Implement a function in Python 3 to resolve the class from the name.
You are a Python code generator, capable of creating scripts from specifications.
def _class_name_params(self, name): "Get the class name and parameters to use for ``__init__``." sec = self.pattern.format(**{'name': name}) logger.debug(f'section: {sec}') params = {} params.update(self.config.populate({}, section=sec)) class_name = params['class_name'] ...
Implement a function in Python 3 to get the class name and parameters to use for __init__.
As a Python code composer, you craft elegant and concise scripts.
def _has_init_config(self, cls): """Return whether the class has a ``config`` parameter in the ``__init__`` method. """ args = inspect.signature(cls.__init__) return self.config_param_name in args.parameters
Write a Python 3 script to return whether the class has a config parameter in the __init__ method.
As a Python code composer, you craft elegant and concise scripts.
Return whether the class has a name parameter in the __init__ method.
Can you tell what is the following Python 3 function doing def _has_init_name(self, cls): args = inspect.signature(cls.__init__) return self.name_param_name in args.parameters
You are a Python code architect, reviewing and designing scalable and efficient code
def _instance(self, cls, *args, **kwargs): """Return the instance. :param cls: the class to create the instance from :param args: given to the ``__init__`` method :param kwargs: given to the ``__init__`` method """ logger.debug(f'args: {args}, kwargs: {kwargs}') ...
Create a Python 3 function for returning the instance from the cache.
As a Python code translator, you convert algorithms and pseudocode into Python.
def instance(self, name=None, *args, **kwargs): """Create a new instance using key ``name``. :param name: the name of the class (by default) or the key name of the class used to find the class :param args: given to the ``__init__`` method :param kwargs: given to the ``__init...
Implement a function in Python 3 to create a new instance of the class with the given name.
As a Python code translator, you convert algorithms and pseudocode into Python.
def load(self, name=None, *args, **kwargs): "Load the instance of the object from the stash." inst = self.stash.load(name) if inst is None: inst = self.instance(name, *args, **kwargs) logger.debug(f'loaded (conf mng) instance: {inst}') return inst
How would you code a function in Python 3 to load the instance of the object from the stash.
You are a Python code analyst, evaluating scripts for potential improvements.
def dump(self, name: str, inst): "Save the object instance to the stash." self.stash.dump(name, inst)
Create a Python 3 function for saving the object instance to the stash.
You are a Python code analyst, evaluating scripts for potential improvements.
def from_env(cls, default_timeout=DEFAULT_TIMEOUT_SECONDS): """Return a client configured from environment variables. Essentially copying this: https://github.com/docker/docker-py/blob/master/docker/client.py#L43. The environment variables looked for are the following: .. envv...
Write a Python 3 function for returning a Saltant API client configured from environment variables.
As a Python code translator, you convert algorithms and pseudocode into Python.
def clear_global(self): """Clear only any cached global data. """ vname = self.varname logger.debug(f'global clearning {vname}') if vname in globals(): logger.debug('removing global instance var: {}'.format(vname)) del globals()[vname]
Create a Python 3 function for clearing all global data.
As a Python code translator, you convert algorithms and pseudocode into Python.
def clear(self): """Clear the data, and thus, force it to be created on the next fetch. This is done by removing the attribute from ``owner``, deleting it from globals and removing the file from the disk. """ vname = self.varname if self.path.exists(): logge...
Implement a Python 3 function for clearing the data of the is and force it to be created on the next fetch.
As a python code expert, you are capable of creating scripts from specifications.
def _load_or_create(self, *argv, **kwargs): """Invoke the file system operations to get the data, or create work. If the file does not exist, calling ``__do_work__`` and save it. """ if self.path.exists(): self._info('loading work from {}'.format(self.path)) with...
Create a Python 3 function for loading the data from the file system and create it if it does not exist.
You are a Python code architect, reviewing and designing scalable and efficient code
Return whether or not the stash has any data available or not.
Explain what the following Python 3 code does def has_data(self): if not hasattr(self, '_has_data'): try: next(iter(self.delegate.keys())) self._has_data = True except StopIteration: self._has_data = False return self._has_data
As a Python code translator, you convert algorithms and pseudocode into Python.
def _get_instance_path(self, name): "Return a path to the pickled data with key ``name``." fname = self.pattern.format(**{'name': name}) logger.debug(f'path {self.create_path}: {self.create_path.exists()}') self._create_path_dir() return Path(self.create_path, fname)
How would you implement a function in Python 3 that returns a path to the pickled data with key name.
You are a Python code architect, reviewing and designing scalable and efficient code
Return an opened shelve object.
Explain what the following Python 3 code does def shelve(self): logger.info('creating shelve data') fname = str(self.create_path.absolute()) inst = sh.open(fname, writeback=self.writeback) self.is_open = True return inst
You are a Python code analyst, evaluating scripts for potential improvements.
Delete the shelve data file.
Can you tell what is the following Python 3 function doing def delete(self, name=None): "Delete the shelve data file." logger.info('clearing shelve data') self.close() for path in Path(self.create_path.parent, self.create_path.name), \ Path(self.create_path.parent, self.creat...
You are a Python code analyst, evaluating scripts for potential improvements.
Close the shelve object which is needed for data consistency.
Explain what the following Python 3 code does def close(self): "Close the shelve object, which is needed for data consistency." if self.is_open: logger.info('closing shelve data') try: self.shelve.close() self._shelve.clear() except Exc...
You are a Python code generator, capable of creating scripts from specifications.
Map data_item separately in each thread.
Explain what the following Python 3 code does def _map(self, data_item): "Map ``data_item`` separately in each thread." delegate = self.delegate logger.debug(f'mapping: {data_item}') if self.clobber or not self.exists(data_item.id): logger.debug(f'exist: {data_item.id}: {self...
You are a Python code analyst, evaluating scripts for potential improvements.
Load all instances witih multiple threads.
Explain what the following Python 3 code does def load_all(self, workers=None, limit=None, n_expected=None): if not self.has_data: self._preempt(True) # we did the best we could (avoid repeat later in this method) n_expected = 0 keys = tuple(self.delegate.keys()) ...
As a Python code composer, you craft elegant and concise scripts.
Monkey - patch object persistence to avoid unnecessary modification of the model class.
Can you generate the documentation for the following Python 3 function def _make_persistent(self, model_name, pkg_name): # # WARNING: ugly piece of monkey-patching below. Hopefully will replace # with native bravado-core code in the future... # # Load class at path pkg_name ...
As a python code expert, you are capable of creating scripts from specifications.
def spawn_api(self, app, decorator=None): """Auto-generate server endpoints implementing the API into this Flask app""" if decorator: assert type(decorator).__name__ == 'function' self.is_server = True self.app = app if self.local: # Re-generate client ca...
Write a Python 3 function for spawning a new API endpoint for this application.
As a python code expert, you are capable of creating scripts from specifications.
def json_to_model(self, model_name, j, validate=False): """Take a json strust and a model name, and return a model instance""" if validate: self.api_spec.validate(model_name, j) return self.api_spec.json_to_model(model_name, j)
Write a Python 3 script to take a json strust and a model name and return a model instance
As a Python code composer, you craft elegant and concise scripts.
def assemble( iterable, patterns=None, minimum_items=2, case_sensitive=True, assume_padded_when_ambiguous=False ): '''Assemble items in *iterable* into discreet collections. *patterns* may be specified as a list of regular expressions to limit the returned collection possibilities. Use this when in...
Can you write a function in Python 3 where it assembles items in iterable into discreet collections.
As a Python code composer, you craft elegant and concise scripts.
Parse a string into a : py : class ~clique. collection. Collection.
Given the following Python 3 function, write the documentation def parse(value, pattern='{head}{padding}{tail} [{ranges}]'): '''Parse *value* into a :py:class:`~clique.collection.Collection`. Use *pattern* to extract information from *value*. It may make use of the following keys: * *head* - Commo...
As a Python code composer, you craft elegant and concise scripts.
Add item to the list.
Explain what the following Python 3 code does def add(self, item): '''Add *item*.''' if not item in self: index = bisect.bisect_right(self._members, item) self._members.insert(index, item)
You are a Python code analyst, evaluating scripts for potential improvements.
def discard(self, item): '''Remove *item*.''' index = self._index(item) if index >= 0: del self._members[index]
How would you code a function in Python 3 to remove the specified item from the set.
You are a Python code analyst, evaluating scripts for potential improvements.
Return index of item in member list or - 1 if not present.
Given the following Python 3 function, write the documentation def _index(self, item): '''Return index of *item* in member list or -1 if not present.''' index = bisect.bisect_left(self._members, item) if index != len(self) and self._members[index] == item: return index retur...
As a Python code composer, you craft elegant and concise scripts.
def match(self, item): '''Return whether *item* matches this collection expression. If a match is successful return data about the match otherwise return None. ''' match = self._expression.match(item) if not match: return None index = match.group('i...
Can you create a Python 3 function that returns whether the item matches this collection expression.
You are a Python code analyst, evaluating scripts for potential improvements.
Add item to the collection.
Can you generate a brief explanation for the following Python 3 code def add(self, item): '''Add *item* to collection. raise :py:class:`~clique.error.CollectionError` if *item* cannot be added to the collection. ''' match = self.match(item) if match is None: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def remove(self, item): '''Remove *item* from collection. raise :py:class:`~clique.error.CollectionError` if *item* cannot be removed from the collection. ''' match = self.match(item) if match is None: raise clique.error.CollectionError( 'Ite...
Write a Python 3 function that can remove item from the collection.
As a python code expert, you are capable of creating scripts from specifications.
def format(self, pattern='{head}{padding}{tail} [{ranges}]'): '''Return string representation as specified by *pattern*. Pattern can be any format accepted by Python's standard format function and will receive the following keyword arguments as context: * *head* - Common leading pa...
How would you code a function in Python 3 to return string representation as specified by pattern.
As a Python code translator, you convert algorithms and pseudocode into Python.
def is_contiguous(self): '''Return whether entire collection is contiguous.''' previous = None for index in self.indexes: if previous is None: previous = index continue if index != (previous + 1): return False ...
Write a Python 3 function that can return whether entire collection is contiguous.
As a Python code analyst, you investigate and solve complex coding mysteries
Return a new collection with holes in self.
Explain what the following Python 3 code does def holes(self): '''Return holes in collection. Return :py:class:`~clique.collection.Collection` of missing indexes. ''' missing = set([]) previous = None for index in self.indexes: if previous is None: ...
You are a Python code architect, reviewing and designing scalable and efficient code
Return whether the given collection is compatible with this one.
Here you have a function in Python 3, explain what it does def is_compatible(self, collection): '''Return whether *collection* is compatible with this collection. To be compatible *collection* must have the same head, tail and padding properties as this collection. ''' return a...
You are a Python code architect, reviewing and designing scalable and efficient code
Merge the current collection into the given collection.
Make a summary of the following Python 3 code def merge(self, collection): '''Merge *collection* into this collection. If the *collection* is compatible with this collection then update indexes with all indexes in *collection*. raise :py:class:`~clique.error.CollectionError` if *collec...
As a Python code translator, you convert algorithms and pseudocode into Python.
def separate(self): '''Return contiguous parts of collection as separate collections. Return as list of :py:class:`~clique.collection.Collection` instances. ''' collections = [] start = None end = None for index in self.indexes: if start is None: ...
Implement a Python 3 function for returning contiguous parts of collection as separate collections.
You are a Python code architect, reviewing and designing scalable and efficient code
Check the format of a osmnet_config object.
Given the following Python 3 function, write the documentation def format_check(settings): valid_keys = ['logs_folder', 'log_file', 'log_console', 'log_name', 'log_filename', 'keep_osm_tags'] for key in list(settings.keys()): assert key in valid_keys, \ ('{} not found in ...
You are a Python code architect, reviewing and designing scalable and efficient code
def to_dict(self): """ Return a dict representation of an osmnet osmnet_config instance. """ return {'logs_folder': self.logs_folder, 'log_file': self.log_file, 'log_console': self.log_console, 'log_name': self.log_name, 'lo...
Implement a function in Python 3 to return a dict representation of an osmnet osmnet_config instance.
You are a Python code generator, capable of creating scripts from specifications.
Calculates the great circle distance between two lat / lon points and returns the distance in meters.
Make a summary of the following Python 3 code def great_circle_dist(lat1, lon1, lat2, lon2): radius = 6372795 # meters lat1 = math.radians(lat1) lon1 = math.radians(lon1) lat2 = math.radians(lat2) lon2 = math.radians(lon2) dlat = lat2 - lat1 dlon = lon2 - lon1 # formula from: # h...
You are a Python code architect, reviewing and designing scalable and efficient code
def osm_filter(network_type): """ Create a filter to query Overpass API for the specified OSM network type. Parameters ---------- network_type : string, {'walk', 'drive'} denoting the type of street network to extract Returns ------- osm_filter : string """ filters = {} ...
Create a Python 3 function for creating a filter to query Overpass API for the specified OSM network type.
As a Python code analyst, you investigate and solve complex coding mysteries
Download OSM ways and nodes within a bounding box from the Overpass API.
How would you explain what the following Python 3 function does def osm_net_download(lat_min=None, lng_min=None, lat_max=None, lng_max=None, network_type='walk', timeout=180, memory=None, max_query_area_size=50*1000*50*1000, custom_osm_filter=None): """...
As a Python code analyst, you investigate and solve complex coding mysteries
Send a request to the Overpass API and return the JSON response
How would you explain what the following Python 3 function does def overpass_request(data, pause_duration=None, timeout=180, error_pause_duration=None): """ Send a request to the Overpass API via HTTP POST and return the JSON response Parameters ---------- data : dict or Or...
As a Python code translator, you convert algorithms and pseudocode into Python.
Get the pause duration of the current item in the order they are available.
How would you explain what the following Python 3 function does def get_pause_duration(recursive_delay=5, default_duration=10): try: response = requests.get('http://overpass-api.de/api/status') status = response.text.split('\n')[3] status_first_token = status.split(' ')[0] except Excepti...
You are a Python code analyst, evaluating scripts for potential improvements.
Consolidate a geometry into a convex hull then subdivide it into smaller sub - polygons if it exceeds max_query_area_size.
Explain what the following Python 3 code does def consolidate_subdivide_geometry(geometry, max_query_area_size): # let the linear length of the quadrats (with which to subdivide the # geometry) be the square root of max area size quadrat_width = math.sqrt(max_query_area_size) if not isinstance(geometr...
You are a Python code analyst, evaluating scripts for potential improvements.
Split a shapely Polygon or MultiPolygon into smaller sub - polygons and buffer them into smaller quadrats.
Can you tell what is the following Python 3 function doing def quadrat_cut_geometry(geometry, quadrat_width, min_num=3, buffer_amount=1e-9): """ Split a Polygon or MultiPolygon up into sub-polygons of a specified size, using quadrats. Parameters ---------- geometry : sh...
You are a Python code analyst, evaluating scripts for potential improvements.
def project_geometry(geometry, crs, to_latlong=False): """ Project a shapely Polygon or MultiPolygon from WGS84 to UTM, or vice-versa Parameters ---------- geometry : shapely Polygon or MultiPolygon the geometry to project crs : int the starting coordinate reference system of th...
Create a Python 3 function for projecting a shapely geometry to a shapely polygon or MultiPolygon from WGS84 to UTM or vice - versa.
You are a Python code analyst, evaluating scripts for potential improvements.
Process a node element entry into a dict suitable for going into a Pandas DataFrame.
Can you generate a brief explanation for the following Python 3 code def process_node(e): node = {'id': e['id'], 'lat': e['lat'], 'lon': e['lon']} if 'tags' in e: if e['tags'] is not np.nan: for t, v in list(e['tags'].items()): if t in config.settings...
As a Python code analyst, you investigate and solve complex coding mysteries
Process a way element entry into a list of dicts suitable for going into a Pandas DataFrame.
How would you explain what the following Python 3 function does def process_way(e): way = {'id': e['id']} if 'tags' in e: if e['tags'] is not np.nan: for t, v in list(e['tags'].items()): if t in config.settings.keep_osm_tags: way[t] = v # nodes that ...
As a Python code analyst, you investigate and solve complex coding mysteries
Convert OSM query data to DataFrames of ways and way - nodes.
Explain what the following Python 3 code does def parse_network_osm_query(data): if len(data['elements']) == 0: raise RuntimeError('OSM query results contain no data.') nodes = [] ways = [] waynodes = [] for e in data['elements']: if e['type'] == 'node': nodes.append(pr...
You are a Python code generator, capable of creating scripts from specifications.
Get DataFrames of OSM data in a bounding box.
Can you generate a brief explanation for the following Python 3 code def ways_in_bbox(lat_min, lng_min, lat_max, lng_max, network_type, timeout=180, memory=None, max_query_area_size=50*1000*50*1000, custom_osm_filter=None): """ Get DataFrames of OSM data in a b...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a set of all the nodes that appear in 2 or more ways.
Make a summary of the following Python 3 code def intersection_nodes(waynodes): counts = waynodes.node_id.value_counts() return set(counts[counts > 1].index.values)
You are a Python code architect, reviewing and designing scalable and efficient code
def node_pairs(nodes, ways, waynodes, two_way=True): """ Create a table of node pairs with the distances between them. Parameters ---------- nodes : pandas.DataFrame Must have 'lat' and 'lon' columns. ways : pandas.DataFrame Table of way metadata. waynodes : pandas.DataFrame...
Create a Python 3 function to create a table of node pairs for the given nodes and ways.
As a Python code composer, you craft elegant and concise scripts.
def network_from_bbox(lat_min=None, lng_min=None, lat_max=None, lng_max=None, bbox=None, network_type='walk', two_way=True, timeout=180, memory=None, max_query_area_size=50*1000*50*1000, custom_osm_filter=None): """ Make a g...
Can you implement a function in Python 3 that makes a graph network from a bounding lat/lon box composed of nodes and edges for use in Pandana street network accessibility calculations. You may either enter a lat/long box via the four lat_min, lng_min, lat_max, lng_max parameters or the bbox parameter as a tuple. Param...
You are a Python code analyst, evaluating scripts for potential improvements.
def read_lines(in_file): """Returns a list of lines from a input markdown file.""" with open(in_file, 'r') as inf: in_contents = inf.read().split('\n') return in_contents
Implement a Python 3 function for returning a list of lines from a markdown file.
As a python code expert, you are capable of creating scripts from specifications.
Removes existing links and tags from a list of lines.
How would you explain what the following Python 3 function does def remove_lines(lines, remove=('[[back to top]', '<a class="mk-toclify"')): if not remove: return lines[:] out = [] for l in lines: if l.startswith(remove): continue out.append(l) return out
As a python code expert, you are capable of creating scripts from specifications.
Takes a string version of the head line and returns a tuple of the stripped version of the head line a string version for anchor tags and the level of the headline as integer.
Can you tell what is the following Python 3 function doing def slugify_headline(line, remove_dashes=False): stripped_right = line.rstrip('#') stripped_both = stripped_right.lstrip('#') level = len(stripped_right) - len(stripped_both) stripped_wspace = stripped_both.strip() # character replacements ...
As a python code expert, you are capable of creating scripts from specifications.
Returns a list of headlines and anchor tags for the given list of lines.
Can you generate the documentation for the following Python 3 function def tag_and_collect(lines, id_tag=True, back_links=False, exclude_h=None, remove_dashes=False): out_contents = [] headlines = [] for l in lines: saw_headline = False orig_len = len(l) l = l.lstrip() if l...
You are a Python code generator, capable of creating scripts from specifications.
def positioning_headlines(headlines): """ Strips unnecessary whitespaces/tabs if first header is not left-aligned """ left_just = False for row in headlines: if row[-1] == 1: left_just = True break if not left_just: for row in headlines: row[-1...
How would you implement a function in Python 3 that positions the headlines in a sequence of words.
As a Python code composer, you craft elegant and concise scripts.
Create a TOC header from a list of headlines.
Can you generate a brief explanation for the following Python 3 code def create_toc(headlines, hyperlink=True, top_link=False, no_toc_header=False): processed = [] if not no_toc_header: if top_link: processed.append('<a class="mk-toclify" id="table-of-contents"></a>\n') processed.app...
As a Python code translator, you convert algorithms and pseudocode into Python.
def build_markdown(toc_headlines, body, spacer=0, placeholder=None): """ Returns a string with the Markdown output contents incl. the table of contents. Keyword arguments: toc_headlines: lines for the table of contents as created by the create_toc function. body: contents of...
Create a Python 3 function for building the Markdown output contents incl. the table of contents.
You are a Python code analyst, evaluating scripts for potential improvements.
Writes a markdown file to an output file if outfile is a valid path.
Make a summary of the following Python 3 code def output_markdown(markdown_cont, output_file): if output_file: with open(output_file, 'w') as out: out.write(markdown_cont)
As a Python code composer, you craft elegant and concise scripts.
def markdown_toclify(input_file, output_file=None, github=False, back_to_top=False, nolink=False, no_toc_header=False, spacer=0, placeholder=None, exclude_h=None, remove_dashes=False): """ Function to add table of contents to markdown files. Parame...
Create a Python 3 function to function to add table of contents to a markdown file.
You are a Python code architect, reviewing and designing scalable and efficient code
parse urls with different prefixes
Can you generate the documentation for the following Python 3 function def url_parse(name): position = name.find("github.com") if position >= 0: if position != 0: position_1 = name.find("www.github.com") position_2 = name.find("http://github.com") position_3 = name.fi...
As a Python code composer, you craft elegant and concise scripts.
get request that returns 302
Here you have a function in Python 3, explain what it does def geturl_req(url): request = urllib.request.Request(url) request.add_header('Authorization', 'token %s' % API_TOKEN) try: response_url = urllib.request.urlopen(request).geturl() return response_url except urllib.error.HTTPError...
As a Python code analyst, you investigate and solve complex coding mysteries
main function of the command line
Can you tell what is the following Python 3 function doing def main(): parser = argparse.ArgumentParser( description='Github within the Command Line') group = parser.add_mutually_exclusive_group() group.add_argument('-n', '--url', type=str, help="Get repos from the user profil...
As a Python code composer, you craft elegant and concise scripts.
Capture the contents of a tag output.
How would you explain what the following Python 3 function does def do_capture(parser, token): bits = token.split_contents() # tokens t_as = 'as' t_silent = 'silent' var = 'capture' silent = False num_bits = len(bits) if len(bits) > 4: raise TemplateSyntaxError("'capture' node ...
You are a Python code architect, reviewing and designing scalable and efficient code
Helper function that saves the token on disk
Here you have a function in Python 3, explain what it does def _save_token_on_disk(self): token = self._token.copy() # Client secret is needed for token refreshing and isn't returned # as a pared of OAuth token by default token.update(client_secret=self._client_secret) with cod...
As a Python code translator, you convert algorithms and pseudocode into Python.
Get Monzo access token via OAuth 2 grant type.
Explain what the following Python 3 code does def _get_oauth_token(self): url = urljoin(self.api_url, '/oauth2/token') oauth = OAuth2Session( client_id=self._client_id, redirect_uri=config.REDIRECT_URI, ) token = oauth.fetch_token( token_url=url, ...
As a Python code composer, you craft elegant and concise scripts.
def _refresh_oath_token(self): """ Refresh Monzo OAuth 2 token. Official docs: https://monzo.com/docs/#refreshing-access :raises UnableToRefreshTokenException: when token couldn't be refreshed """ url = urljoin(self.api_url, '/oauth2/token') data = {...
Can you create a Python 3 function that refreshes Monzo OAuth 2 token.
As a python code expert, you are capable of creating scripts from specifications.
def whoami(self): """ Get information about the access token. Official docs: https://monzo.com/docs/#authenticating-requests :returns: access token details :rtype: dict """ endpoint = '/ping/whoami' response = self._get_response( ...
Create a Python 3 function for getting information about the access token.
You are a Python code generator, capable of creating scripts from specifications.
Returns a list of Monzo accounts owned by the currently authorised user.
Make a summary of the following Python 3 code def accounts(self, refresh=False): if not refresh and self._cached_accounts: return self._cached_accounts endpoint = '/accounts' response = self._get_response( method='get', endpoint=endpoint, ) accounts_json...
You are a Python code generator, capable of creating scripts from specifications.
Returns balance information for a specific account.
Here you have a function in Python 3, explain what it does def balance(self, account_id=None): if not account_id: if len(self.accounts()) == 1: account_id = self.accounts()[0].id else: raise ValueError("You need to pass account ID") endpoint = '/b...
You are a Python code analyst, evaluating scripts for potential improvements.
def pots(self, refresh=False): """ Returns a list of pots owned by the currently authorised user. Official docs: https://monzo.com/docs/#pots :param refresh: decides if the pots information should be refreshed. :type refresh: bool :returns: list of Monzo pot...
Create a Python 3 function for returning a list of MonzoPot objects owned by the currently authorised user.
You are a Python code generator, capable of creating scripts from specifications.
Returns a list of transactions on the user s account.
Can you generate the documentation for the following Python 3 function def transactions(self, account_id=None, reverse=True, limit=None): if not account_id: if len(self.accounts()) == 1: account_id = self.accounts()[0].id else: raise ValueError("You need t...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns an individual Monzo transaction
Can you generate the documentation for the following Python 3 function def transaction(self, transaction_id, expand_merchant=False): endpoint = '/transactions/{}'.format(transaction_id) data = dict() if expand_merchant: data['expand[]'] = 'merchant' response = self._get_res...
You are a Python code generator, capable of creating scripts from specifications.
def get_auth_string(self): """Create auth string from credentials.""" auth_info = '{}:{}'.format(self.sauce_username, self.sauce_access_key) return base64.b64encode(auth_info.encode('utf-8')).decode('utf-8')
Implement a function in Python 3 to create auth string from credentials.
As a Python code composer, you craft elegant and concise scripts.
Access basic account information.
Can you generate the documentation for the following Python 3 function def get_user(self): method = 'GET' endpoint = '/rest/v1/users/{}'.format(self.client.sauce_username) return self.client.request(method, endpoint)
You are a Python code architect, reviewing and designing scalable and efficient code
Create a sub account.
Here you have a function in Python 3, explain what it does def create_user(self, username, password, name, email): method = 'POST' endpoint = '/rest/v1/users/{}'.format(self.client.sauce_username) body = json.dumps({'username': username, 'password': password, 'name': n...
You are a Python code architect, reviewing and designing scalable and efficient code
Check account concurrency limits.
Make a summary of the following Python 3 code def get_concurrency(self): method = 'GET' endpoint = '/rest/v1.1/users/{}/concurrency'.format( self.client.sauce_username) return self.client.request(method, endpoint)
As a python code expert, you are capable of creating scripts from specifications.
Get a list of sub accounts associated with a parent account.
Can you generate the documentation for the following Python 3 function def get_subaccounts(self): method = 'GET' endpoint = '/rest/v1/users/{}/list-subaccounts'.format( self.client.sauce_username) return self.client.request(method, endpoint)
You are a Python code architect, reviewing and designing scalable and efficient code
def get_siblings(self): """Get a list of sibling accounts associated with provided account.""" method = 'GET' endpoint = '/rest/v1.1/users/{}/siblings'.format( self.client.sauce_username) return self.client.request(method, endpoint)
Create a Python 3 function for getting a list of sibling accounts associated with provided account.
You are a Python code architect, reviewing and designing scalable and efficient code
Get information about a sub account.
Make a summary of the following Python 3 code def get_subaccount_info(self): method = 'GET' endpoint = '/rest/v1/users/{}/subaccounts'.format( self.client.sauce_username) return self.client.request(method, endpoint)
You are a Python code generator, capable of creating scripts from specifications.
Change the access key of your account.
How would you explain what the following Python 3 function does def change_access_key(self): method = 'POST' endpoint = '/rest/v1/users/{}/accesskey/change'.format( self.client.sauce_username) return self.client.request(method, endpoint)
You are a Python code generator, capable of creating scripts from specifications.