output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
A wrapper for xbmcplugin. addSortMethod that adds a sort method to the current sort hierarchy.
Given the following Python 3 function, write the documentation def add_sort_method(self, sort_method, label2_mask=None): '''A wrapper for `xbmcplugin.addSortMethod() <http://mirrors.xbmc.org/docs/python-docs/xbmcplugin.html#-addSortMethod>`_. You can use ``dir(xbmcswift2.SortMethod)`` to list al...
You are a Python code generator, capable of creating scripts from specifications.
def finish(self, items=None, sort_methods=None, succeeded=True, update_listing=False, cache_to_disc=True, view_mode=None): '''Adds the provided items to the XBMC interface. :param items: an iterable of items where each item is either a dictionary with keys/values suitable for...
Write a Python 3 function that can finish the list items in the XBMC interface.
As a Python code translator, you convert algorithms and pseudocode into Python.
Register a cleanup function to be called at the end of every validation task. Takes either a callable that is called at the end of every validation task. Takes either a class with a __call_ method or a class with a cleanup class method.
Can you tell what is the following Python 3 function doing def register_cleanup(cleanup): if not callable(cleanup): # Allow decorating a class with a `cleanup` classm ethod. cleanup = cleanup.cleanup CLEANUP_FUNCTIONS.append(cleanup.cleanup) return cleanup
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns all values after and including the version for the app guid
How would you explain what the following Python 3 function does def version_range(guid, version, before=None, app_versions=None): if app_versions is None: app_versions = validator.constants.APPROVED_APPLICATIONS app_key = None # Support for shorthand instead of full GUIDs. for app_guid, app_na...
As a Python code translator, you convert algorithms and pseudocode into Python.
Attempts to match a url to the given path.
Can you tell what is the following Python 3 function doing def match(self, path): '''Attempts to match a url to the given path. If successful, a tuple is returned. The first item is the matchd function and the second item is a dictionary containing items to be passed to the function parsed from ...
As a python code expert, you are capable of creating scripts from specifications.
Returns a relative path for the given dictionary of items.
Can you generate a brief explanation for the following Python 3 code def _make_path(self, items): '''Returns a relative path for the given dictionary of items. Uses this url rule's url pattern and replaces instances of <var_name> with the appropriate value from the items dict. ''' ...
As a Python code composer, you craft elegant and concise scripts.
Returns a relative path complete with query string for the given items.
Make a summary of the following Python 3 code def make_path_qs(self, items): '''Returns a relative path complete with query string for the given dictionary of items. Any items with keys matching this rule's url pattern will be inserted into the path. Any remaining items will be appended...
You are a Python code generator, capable of creating scripts from specifications.
def sync(self): '''Write the dict to disk''' if self.flag == 'r': return filename = self.filename tempname = filename + '.tmp' fileobj = open(tempname, 'wb' if self.file_format == 'pickle' else 'w') try: self.dump(fileobj) except Exception:...
Can you create a Python 3 function that writes the dict to disk
As a Python code analyst, you investigate and solve complex coding mysteries
def dump(self, fileobj): '''Handles the writing of the dict to the file object''' if self.file_format == 'csv': csv.writer(fileobj).writerows(self.raw_dict().items()) elif self.file_format == 'json': json.dump(self.raw_dict(), fileobj, separators=(',', ':')) elif ...
Create a Python 3 function to handle the writing of the dict to the file object
You are a Python code architect, reviewing and designing scalable and efficient code
Load the dict from the file object fileobj
Here you have a function in Python 3, explain what it does def load(self, fileobj): '''Load the dict from the file object''' # try formats from most restrictive to least restrictive for loader in (pickle.load, json.load, csv.reader): fileobj.seek(0) try: r...
As a Python code composer, you craft elegant and concise scripts.
def initial_update(self, mapping): '''Initially fills the underlying dictionary with keys, values and timestamps. ''' for key, val in mapping.items(): _, timestamp = val if not self.TTL or (datetime.utcnow() - datetime.utcfromtimestamp(timestamp) <...
Create a Python 3 function to initial update of the underlying dictionary with keys values and timestamps.
As a Python code composer, you craft elegant and concise scripts.
def setup_log(name): '''Returns a logging instance for the provided name. The returned object is an instance of logging.Logger. Logged messages will be printed to stderr when running in the CLI, or forwarded to XBMC's log when running in XBMC mode. ''' _log = logging.getLogger(name) _log.set...
Write a Python 3 script to return a logging instance for the provided name.
You are a Python code generator, capable of creating scripts from specifications.
Returns True if all records if running in CLI else returns False.
How would you explain what the following Python 3 function does def filter(self, record): '''Returns True for all records if running in the CLI, else returns True. When running inside XBMC it calls the xbmc.log() method and prevents the message from being double printed to STDOUT. ...
As a Python code analyst, you investigate and solve complex coding mysteries
def validate_name(err, value, source): 'Tests a manifest name value for trademarks.' ff_pattern = re.compile('(mozilla|firefox)', re.I) err.metadata['name'] = value if ff_pattern.search(value): err.warning( ('metadata_helpers', '_test_name', 'trademark'), 'Add-on has p...
Write a Python 3 script for testing a manifest name value for trademarks.
You are a Python code generator, capable of creating scripts from specifications.
Tests a manifest UUID value
Here you have a function in Python 3, explain what it does def validate_id(err, value, source): 'Tests a manifest UUID value' field_name = '<em:id>' if source == 'install.rdf' else 'id' id_pattern = re.compile( '(' # UUID format. '\{[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}\}' ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Tests a manifest version number
Can you generate a brief explanation for the following Python 3 code def validate_version(err, value, source): 'Tests a manifest version number' field_name = '<em:version>' if source == 'install.rdf' else 'version' err.metadata['version'] = value # May not be longer than 32 characters if len(val...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_device(self, pin=None): """ Query the status of a specific pin (or all configured pins if pin is ommitted) """ url = self.base_url + '/device' try: r = requests.get(url, params={'pin': pin}, timeout=10) return r.json() except RequestException as err: ...
Implement a function in Python 3 to query the status of a specific pin or all configured pins
As a python code expert, you are capable of creating scripts from specifications.
Query the device status. Returns the device internal state.
Explain what the following Python 3 code does def get_status(self): url = self.base_url + '/status' try: r = requests.get(url, timeout=10) return r.json() except RequestException as err: raise Client.ClientError(err)
You are a Python code generator, capable of creating scripts from specifications.
def put_device(self, pin, state, momentary=None, times=None, pause=None): """ Actuate a device pin """ url = self.base_url + '/device' payload = { "pin": pin, "state": state } if momentary is not None: payload["momentary"] = momentary ...
How would you implement a function in Python 3 that actuates a device pin
As a python code expert, you are capable of creating scripts from specifications.
Syncs the settings to the Konnected device
Given the following Python 3 function, write the documentation def put_settings(self, sensors=[], actuators=[], auth_token=None, endpoint=None, blink=None, discovery=None, dht_sensors=[], ds18b20_sensors=[]): """ Sync settings to the Konnected device """ url = s...
As a Python code composer, you craft elegant and concise scripts.
Parses a mime - type into its component parts.
Here you have a function in Python 3, explain what it does def parse_mime_type(mime_type): full_type, params = cgi.parse_header(mime_type) # Java URLConnection class sends an Accept header that includes a # single '*'. Turn it into a legal wildcard. if full_type == '*': full_type = '*/*' ty...
As a python code expert, you are capable of creating scripts from specifications.
def parse_media_range(range): """Parse a media-range into its component parts. Carves up a media range and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/*;q=0.5' would get parsed in...
Write a Python 3 function that can parse a media - range into its component parts.
As a Python code translator, you convert algorithms and pseudocode into Python.
Find the best match for a given mime - type amongst parsed media - ranges. Returns a tuple of the fitness value and the value of the q quality parameter of the best match.
Can you tell what is the following Python 3 function doing def quality_and_fitness_parsed(mime_type, parsed_ranges): best_fitness = -1 best_fit_q = 0 (target_type, target_subtype, target_params) = \ parse_media_range(mime_type) for (type, subtype, params) in parsed_ranges: # check if t...
You are a Python code generator, capable of creating scripts from specifications.
Return the quality of a mime - type against a list of media - ranges.
Can you generate the documentation for the following Python 3 function def quality(mime_type, ranges): parsed_ranges = [parse_media_range(r) for r in ranges.split(',')] return quality_parsed(mime_type, parsed_ranges)
As a python code expert, you are capable of creating scripts from specifications.
Return mime - type with the highest quality ('q') from list of candidates.
Explain what the following Python 3 code does def best_match(supported, header): split_header = _filter_blank(header.split(',')) parsed_header = [parse_media_range(r) for r in split_header] weighted_matches = [] pos = 0 for mime_type in supported: weighted_matches.append(( qualit...
You are a Python code architect, reviewing and designing scalable and efficient code
Helper that creates a XSLT stylesheet from a file.
Here you have a function in Python 3, explain what it does def makeXsl(filename): pkg = 'cnxml2html' package = ''.join(['.' + x for x in __name__.split('.')[:-1]])[1:] if package != '': pkg = package + '.' + pkg path = pkg_resources.resource_filename(pkg, filename) xml = etree.parse(path) return etree...
As a Python code translator, you convert algorithms and pseudocode into Python.
def transform_collxml(collxml_file): """ Given a collxml file (collection.xml) this returns an HTML version of it (including "include" anchor links to the modules) """ xml = etree.parse(collxml_file) xslt = makeXsl('collxml2xhtml.xsl') xml = xslt(xml) return xml
Can you write a function in Python 3 where it gives a collxml file this returns an HTML version of it
You are a Python code analyst, evaluating scripts for potential improvements.
def transform_cnxml(cnxml_file): """ Given a module cnxml file (index.cnxml) this returns an HTML version of it """ xml = etree.parse(cnxml_file) xslt = makeXsl('cnxml2xhtml.xsl') xml = xslt(xml) return xml
Create a Python 3 function for giving a module cnxml file this returns an HTML version of it
As a python code expert, you are capable of creating scripts from specifications.
def transform_collection(collection_dir): """ Given an unzipped collection generate a giant HTML file representing the entire collection (including loading and converting individual modules) """ collxml_file = open(os.path.join(collection_dir, 'collection.xml')) collxml_html = transform_collxml(col...
Write a Python 3 script to give an unzipped collection generate a giant HTML file representing the entire collection
As a python code expert, you are capable of creating scripts from specifications.
def from_dict(cls, d: dict, force_snake_case: bool=True, force_cast: bool=False, restrict: bool=True) -> T: """From dict to instance :param d: Dict :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True :param force_cast: Cast forcibly if True ...
Implement a function in Python 3 to create an instance of the class instance from a dictionary.
You are a Python code analyst, evaluating scripts for potential improvements.
From dict to optional instance.
Explain what the following Python 3 code does def from_optional_dict(cls, d: Optional[dict], force_snake_case: bool=True,force_cast: bool=False, restrict: bool=True) -> TOption[T]: """From dict to optional instance. :param d: Dict :param force_snake_case: Keys are tra...
You are a Python code generator, capable of creating scripts from specifications.
From list of dict to optional list of instance.
Can you tell what is the following Python 3 function doing def from_optional_dicts(cls, ds: Optional[List[dict]], force_snake_case: bool=True, force_cast: bool=False, restrict: bool=True) -> TOption[TList[T]]: """From list of dict to optional list of instance. :param ds: Lis...
You are a Python code generator, capable of creating scripts from specifications.
From dict of dict to dict of instance
How would you explain what the following Python 3 function does def from_dicts_by_key(cls, ds: dict, force_snake_case: bool=True, force_cast: bool=False, restrict: bool=True) -> TDict[T]: """From dict of dict to dict of instance :param ds: Dict of dict :param force_sna...
As a Python code analyst, you investigate and solve complex coding mysteries
From dict of dict of dict of instance.
Given the following Python 3 function, write the documentation def from_optional_dicts_by_key(cls, ds: Optional[dict], force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> TOption[TDict[T]]: """From dict of dict to optional dict of instance. :param d...
As a python code expert, you are capable of creating scripts from specifications.
From json file path to instance
Here you have a function in Python 3, explain what it does def from_jsonf(cls, fpath: str, encoding: str='utf8', force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> T: """From json file path to instance :param fpath: Json file path :param encoding: Json fi...
You are a Python code architect, reviewing and designing scalable and efficient code
From json string to list of instance of class T
Can you generate a brief explanation for the following Python 3 code def from_json_to_list(cls, data: str, force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> TList[T]: """From json string to list of instance :param data: Json string :param force_sn...
As a python code expert, you are capable of creating scripts from specifications.
From json file path to list of instance containing keys and values.
Can you tell what is the following Python 3 function doing def from_jsonf_to_list(cls, fpath: str, encoding: str='utf8', force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> TList[T]: """From json file path to list of instance :param fpath: Json file path ...
You are a Python code generator, capable of creating scripts from specifications.
From yaml string to instance
Can you tell what is the following Python 3 function doing def from_yaml(cls, data: str, force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> T: return cls.from_dict(util.load_yaml(data), force_snake_case=force_snake_case, force_cast=fo...
You are a Python code generator, capable of creating scripts from specifications.
From csv file path to list of InstanceTrees
Can you generate the documentation for the following Python 3 function def from_csvf(cls, fpath: str, fieldnames: Optional[Sequence[str]]=None, encoding: str='utf8', force_snake_case: bool=True, restrict: bool=True) -> TList[T]: """From csv file path to list of instance :param fpath: ...
As a python code expert, you are capable of creating scripts from specifications.
Get the object at the specified index.
Given the following Python 3 function, write the documentation def get(self, index: int) -> TOption[T]: return TOption(self[index]) if len(self) > index else TOption(None)
You are a Python code generator, capable of creating scripts from specifications.
Returns a copy of the list with elements from the head of the list while a truth test is true.
Can you generate the documentation for the following Python 3 function def head_while(self, func: Callable[[T], bool]) -> 'TList[T]': r = TList() for x in self: if not func(x): return r else: r.append(x) return r
You are a Python code analyst, evaluating scripts for potential improvements.
Return a new list of unique entries in the list.
Can you generate a brief explanation for the following Python 3 code def uniq(self) -> 'TList[T]': rs = TList() for e in self: if e not in rs: rs.append(e) return rs
You are a Python code analyst, evaluating scripts for potential improvements.
def uniq_by(self, func: Callable[[T], Any]) -> 'TList[T]': """ Usage: >>> TList([1, 2, 3, -2, -1]).uniq_by(lambda x: x**2) [1, 2, 3] """ rs = TList() for e in self: if func(e) not in rs.map(func): rs.append(e) return rs
Write a Python 3 function for returning a new list with unique elements from the list.
As a python code expert, you are capable of creating scripts from specifications.
def group_by(self, to_key): """ :param to_key: :type to_key: T -> unicode :rtype: TDict[TList[T]] Usage: >>> TList([1, 2, 3, 4, 5]).group_by(lambda x: x % 2).to_json() '{"0": [2,4],"1": [1,3,5]}' """ ret = TDict() for v in self: ...
Create a Python 3 function to return a dictionary of the set of keys and values grouped by to_key
As a Python code composer, you craft elegant and concise scripts.
Return a copy of the list with keys mapped to the given function.
Can you generate a brief explanation for the following Python 3 code def key_by(self, to_key: Callable[[T], str]) -> 'TDict[T]': return TDict({to_key(x): x for x in self})
As a Python code composer, you craft elegant and concise scripts.
def order_by(self, func, reverse=False): """ :param func: :type func: T -> any :param reverse: Sort by descend order if True, else by ascend :type reverse: bool :rtype: TList[T] Usage: >>> TList([12, 25, 31, 40, 57]).order_by(lambda x: x % 10) ...
Write a Python 3 function for sorting the list by a function.
As a python code expert, you are capable of creating scripts from specifications.
Find the first entry in the list that satisfies the condition func.
Here you have a function in Python 3, explain what it does def find(self, func: Callable[[T], bool]) -> TOption[T]: for x in self: if func(x): return TOption(x) return TOption(None)
You are a Python code generator, capable of creating scripts from specifications.
Get the value of the key in the object.
Explain what the following Python 3 code does def get(self, key: K) -> TOption[T]: return TOption(self[key]) if key in self else TOption(None)
As a python code expert, you are capable of creating scripts from specifications.
Return a list of U objects by applying func to each element of the list.
Can you tell what is the following Python 3 function doing def map(self, func): return TList([func(k, v) for k, v in self.items()])
You are a Python code analyst, evaluating scripts for potential improvements.
def map_values(self, func): """ :param func: :type func: T -> U :rtype: TDict[U] Usage: >>> TDict(k1=1, k2=2, k3=3).map_values(lambda x: x*2) == { ... "k1": 2, ... "k2": 4, ... "k3": 6 ... } Tru...
Write a Python 3 function for mapping a function to the values of the object.
As a python code expert, you are capable of creating scripts from specifications.
Map a function to the values of a set of keys and values.
Here you have a function in Python 3, explain what it does def map_values2(self, func): return TDict({k: func(k, v) for k, v in self.items()})
As a Python code analyst, you investigate and solve complex coding mysteries
Return a copy of the dictionary with only the keys that pass the given function.
Explain what the following Python 3 code does def filter(self, func): return TList([v for k, v in self.items() if func(k, v)])
You are a Python code analyst, evaluating scripts for potential improvements.
def reject(self, func): """ :param func: :type func: (K, T) -> bool :rtype: TList[T] Usage: >>> TDict(k1=1, k2=2, k3=3).reject(lambda k, v: v < 3) [3] """ return TList([v for k, v in self.items() if not func(k, v)])
Can you create a Python 3 function that returns a copy of the dictionary with entries in the order of the keys that do not satisfy the condition func.
As a Python code translator, you convert algorithms and pseudocode into Python.
def find(self, func: Callable[[K, T], bool]) -> TOption[T]: """ Usage: >>> TDict(k1=1, k2=2, k3=3).find(lambda k, v: v == 2) Option --> 2 >>> TDict(k1=1, k2=2, k3=3).find(lambda k, v: v == 4) Option --> None """ for k, v in self.items(): ...
Can you write a function in Python 3 where it returns the first entry in the cache that satisfies the given function.
As a Python code composer, you craft elegant and concise scripts.
Tests if all elements in the dictionary are True or False.
Here you have a function in Python 3, explain what it does def all(self, func): return all([func(k, v) for k, v in self.items()])
As a Python code analyst, you investigate and solve complex coding mysteries
Tests if any of the keys in the dictionary are True or False.
Here you have a function in Python 3, explain what it does def any(self, func): return any([func(k, v) for k, v in self.items()])
As a Python code composer, you craft elegant and concise scripts.
def pick_by(self, func: Callable[[K, T], bool]) -> 'TDict[T]': """ Usage: >>> TDict(k1=1, k2=2, k3=3).pick_by(lambda k, v: v > 2) {'k3': 3} """ return TDict({k: v for k, v in self.items() if func(k, v)})
Write a Python 3 script to return a copy of the dictionary with only the keys that satisfy the given function.
As a Python code analyst, you investigate and solve complex coding mysteries
Stores the state of the section at the given level.
Explain what the following Python 3 code does def storeSectionState(self, level): # self.document.append("<!-- storeSectionState(): " + str(len(self.header_stack)) + " open section tags. " + str(self.header_stack) + "-->\n") try: # special case. we are not processing an OOo XML start tag ...
As a Python code composer, you craft elegant and concise scripts.
def endSections(self, level=u'0'): """Closes all sections of level >= sectnum. Defaults to closing all open sections""" iSectionsClosed = self.storeSectionState(level) self.document.append("</section>\n" * iSectionsClosed)
Write a Python 3 script to close all sections of level > = sectnum. Defaults to closing all open sections.
As a Python code analyst, you investigate and solve complex coding mysteries
From instance to dict
Can you tell what is the following Python 3 function doing def to_dict(self, ignore_none: bool=True, force_value: bool=True, ignore_empty: bool=False) -> dict: return traverse_dict(self._dict, ignore_none, force_value, ignore_empty)
As a python code expert, you are capable of creating scripts from specifications.
From instance to yaml string
How would you explain what the following Python 3 function does def to_yaml(self, ignore_none: bool=True, ignore_empty: bool=False) -> str: return util.dump_yaml(traverse(self, ignore_none, force_value=True, ignore_empty=ignore_empty))
As a Python code translator, you convert algorithms and pseudocode into Python.
From sequence of text to csv string
Can you generate a brief explanation for the following Python 3 code def to_csv(self, fieldnames: Sequence[str], with_header: bool=False, crlf: bool=False, tsv: bool=False) -> str: return util.dump_csv(traverse(self, force_value=True), fieldnames, with_header, crlf, tsv)
You are a Python code architect, reviewing and designing scalable and efficient code
This method transforms post tidy. Will go away when tidy goes away.
Explain what the following Python 3 code does def _post_tidy(html): tree = etree.fromstring(html) ems = tree.xpath( "//xh:em[@class='underline']|//xh:em[contains(@class, ' underline ')]", namespaces={'xh': 'http://www.w3.org/1999/xhtml'}) for el in ems: c = el.attrib.get('class', '')...
As a python code expert, you are capable of creating scripts from specifications.
Tidy up a html4. 5 soup to a parsable valid XHTML5.
Can you generate the documentation for the following Python 3 function def _tidy2xhtml5(html): html = _io2string(html) html = _pre_tidy(html) # Pre-process xhtml5, errors =\ tidy_document(html, options={ # do not merge nested div elements ...
You are a Python code architect, reviewing and designing scalable and efficient code
Helper that creates a XSLT stylesheet
Explain what the following Python 3 code does def _make_xsl(filename): path = pkg_resources.resource_filename('rhaptos.cnxmlutils.xsl', filename) xml = etree.parse(path) return etree.XSLT(xml)
You are a Python code architect, reviewing and designing scalable and efficient code
def _transform(xsl_filename, xml, **kwargs): """Transforms the xml using the specifiec xsl file.""" xslt = _make_xsl(xsl_filename) xml = xslt(xml, **kwargs) return xml
Write a Python 3 script to transform the xml using the specifiec xsl file.
You are a Python code generator, capable of creating scripts from specifications.
Transform the CNXML source to HTML
Given the following Python 3 function, write the documentation def cnxml_to_html(cnxml_source): source = _string2io(cnxml_source) xml = etree.parse(source) # Run the CNXML to HTML transform xml = _transform('cnxml-to-html5.xsl', xml, version='"{}"'.format(version)) xml = XHTML_M...
As a Python code composer, you craft elegant and concise scripts.
Converts HTML5 from Aloha editor output to lxml etree.
Here you have a function in Python 3, explain what it does def aloha_to_etree(html_source): xml = _tidy2xhtml5(html_source) for i, transform in enumerate(ALOHA2HTML_TRANSFORM_PIPELINE): xml = transform(xml) return xml
You are a Python code architect, reviewing and designing scalable and efficient code
def aloha_to_html(html_source): """Converts HTML5 from Aloha to a more structured HTML5""" xml = aloha_to_etree(html_source) return etree.tostring(xml, pretty_print=True)
Can you create a Python 3 function that converts HTML5 from Aloha to a more structured HTML5
You are a Python code generator, capable of creating scripts from specifications.
Transform the HTML to CNXML.
Can you generate the documentation for the following Python 3 function def html_to_cnxml(html_source, cnxml_source): source = _string2io(html_source) xml = etree.parse(source) cnxml = etree.parse(_string2io(cnxml_source)) # Run the HTML to CNXML transform on it xml = _transform('html5-to-cnxml.xsl',...
As a python code expert, you are capable of creating scripts from specifications.
def html_to_valid_cnxml(html_source): """Transform the HTML to valid CNXML (used for OERPUB). No original CNXML is needed. If HTML is from Aloha please use aloha_to_html before using this method """ source = _string2io(html_source) xml = etree.parse(source) return etree_to_valid_cnxml(xml, ...
How would you implement a function in Python 3 that transforms the HTML to valid CNXML.
As a Python code composer, you craft elegant and concise scripts.
def get_or(self, default: T) -> T: """ Usage: >>> TOption(3).get_or(999) 3 >>> TOption(0).get_or(999) 0 >>> TOption(None).get_or(999) 999 """ return default if self.value is None else self.value
Write a Python 3 function for getting or return the current value of the object.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a new instance of the class with the value mapped to the given function.
Can you generate the documentation for the following Python 3 function def map(self, func: Callable[[T], U]) -> 'TOption[T]': return self if self.is_none() else TOption(func(self.value))
You are a Python code generator, capable of creating scripts from specifications.
def flat_map(self, func: Callable[[T], 'TOption[T]']) -> 'TOption[T]': """ Usage: >>> TOption(3).flat_map(lambda x: TOption(x+1)).get() 4 >>> TOption(3).flat_map(lambda x: TOption(None)).get_or(999) 999 >>> TOption(None).flat_map(lambda x: TOp...
Can you create a Python 3 function that returns a new TOption instance with the values mapped to the specified function.
You are a Python code analyst, evaluating scripts for potential improvements.
Replace both the hex and decimal versions of symbols in an XML string
Explain what the following Python 3 code does def replace(text): for hex, value in UNICODE_DICTIONARY.items(): num = int(hex[3:-1], 16) #uni = unichr(num) decimal = '&#' + str(num) + ';' for key in [ hex, decimal ]: #uni text = text.replace(key, value) return text
As a Python code analyst, you investigate and solve complex coding mysteries
def replace_keys(d, keymap, force_snake_case): """ :param dict d: :param Dict[unicode, unicode] keymap: :param bool force_snake_case: :rtype: Dict[unicode, unicode] """ return { to_snake(keymap.get(k, k)) if force_snake_case else keymap.get(k, k): v for k, v in d.items() ...
Can you create a Python 3 function that replaces keys in a dictionary with the values in keymap.
As a Python code analyst, you investigate and solve complex coding mysteries
def load_jsonf(fpath, encoding): """ :param unicode fpath: :param unicode encoding: :rtype: dict | list """ with codecs.open(fpath, encoding=encoding) as f: return json.load(f)
Write a Python 3 function for loading a single node from a JSON file.
As a Python code composer, you craft elegant and concise scripts.
def load_yamlf(fpath, encoding): """ :param unicode fpath: :param unicode encoding: :rtype: dict | list """ with codecs.open(fpath, encoding=encoding) as f: return yaml.safe_load(f)
Write a Python 3 function for loading a single node from a yaml file.
As a Python code composer, you craft elegant and concise scripts.
def load_csvf(fpath, fieldnames, encoding): """ :param unicode fpath: :param Optional[list[unicode]] fieldnames: :param unicode encoding: :rtype: List[dict] """ with open(fpath, mode='r', encoding=encoding) as f: snippet = f.read(8192) f.seek(0) dialect = csv.Sniffer...
Write a Python 3 function that can load a single ndata tree from a CSV file.
As a Python code analyst, you investigate and solve complex coding mysteries
def dump_csv(data: List[dict], fieldnames: Sequence[str], with_header: bool = False, crlf: bool = False, tsv: bool = False) -> str: """ :param data: :param fieldnames: :param with_header: :param crlf: :param tsv: :return: unicode """ def force_str(v): # XXX: Dou...
Write a Python 3 script to dump a list of dicts into a CSV file.
You are a Python code architect, reviewing and designing scalable and efficient code
Save data to a CSV file.
Explain what the following Python 3 code does def save_csvf(data: list, fieldnames: Sequence[str], fpath: str, encoding: str, with_header: bool = False, crlf: bool = False, tsv: bool = False) -> str: """ :param data: :param fieldnames: :param fpath: write path :param encoding: encoding...
As a python code expert, you are capable of creating scripts from specifications.
def dump_json(data, indent=None): """ :param list | dict data: :param Optional[int] indent: :rtype: unicode """ return json.dumps(data, indent=indent, ensure_ascii=False, sort_keys=True, separators=(',', ': '...
Write a Python 3 script to dump a list | dict to JSON.
You are a Python code generator, capable of creating scripts from specifications.
def save_jsonf(data: Union[list, dict], fpath: str, encoding: str, indent=None) -> str: """ :param data: list | dict data :param fpath: write path :param encoding: encoding :param indent: :rtype: written path """ with codecs.open(fpath, mode='w', encoding=encoding) as f: f.write(...
Write a Python 3 script to save a list of dicts to a JSON file.
As a Python code analyst, you investigate and solve complex coding mysteries
def dump_yaml(data): """ :param list | dict data: :rtype: unicode """ return yaml.dump(data, indent=2, encoding=None, allow_unicode=True, default_flow_style=False, Dumper=MyDumper)
Implement a Python 3 function for dumping a list | dict to YAML
You are a Python code architect, reviewing and designing scalable and efficient code
def save_yamlf(data: Union[list, dict], fpath: str, encoding: str) -> str: """ :param data: list | dict data :param fpath: write path :param encoding: encoding :rtype: written path """ with codecs.open(fpath, mode='w', encoding=encoding) as f: f.write(dump_yaml(data)) return ...
How would you code a function in Python 3 to save a list of dicts to a file in YAML format.
As a Python code composer, you craft elegant and concise scripts.
def dump_table(data: List[dict], fieldnames: Sequence[str]) -> str: """ :param data: :param fieldnames: :return: Table string """ def min3(num: int) -> int: return 3 if num < 4 else num width_by_col: Dict[str, int] = { f: min3(max([string_width(str(d.get(f))) for d in data]...
Write a Python 3 function for dumping a list of dictionaries into a string.
You are a Python code analyst, evaluating scripts for potential improvements.
def string_width(word: str) -> int: """ :param word: :return: Widths of word Usage: >>> string_width('abc') 3 >>> string_width('Abしー') 7 >>> string_width('') 0 """ return sum(map(lambda x: 2 if east_asian_width(x) in 'FWA' else 1, word))
Create a Python 3 function for returning the width of the word in the alphabet
You are a Python code analyst, evaluating scripts for potential improvements.
def writeXMLFile(filename, content): """ Used only for debugging to write out intermediate files""" xmlfile = open(filename, 'w') # pretty print content = etree.tostring(content, pretty_print=True) xmlfile.write(content) xmlfile.close()
Implement a function in Python 3 to write out XML file.
You are a Python code architect, reviewing and designing scalable and efficient code
This function takes an ODT file and returns a tuple containing the cnxml a dictionary of filename - > data a list of errors
How would you explain what the following Python 3 function does def transform(odtfile, debug=False, parsable=False, outputdir=None): # Store mapping of images extracted from the ODT file (and their bits) images = {} # Log of Errors and Warnings generated # For example, the text produced by XSLT should b...
As a python code expert, you are capable of creating scripts from specifications.
def from_value(cls, value: str) -> T: """Create instance from symbol :param value: unique symbol :return: This instance Usage: >>> from owlmixin.samples import Animal >>> Animal.from_value('cat').crow() mewing """ return [x for x in c...
Implement a Python 3 function for creating an instance from a unique symbol.
You are a Python code generator, capable of creating scripts from specifications.
Will provision vault based on the definition within a Secretfile
Make a summary of the following Python 3 code def seed(vault_client, opt): if opt.thaw_from: opt.secrets = tempfile.mkdtemp('aomi-thaw') auto_thaw(vault_client, opt) Context.load(get_secretfile(opt), opt) \ .fetch(vault_client) \ .sync(vault_client, opt) if opt.thaw_f...
As a Python code analyst, you investigate and solve complex coding mysteries
def render(directory, opt): """Render any provided template. This includes the Secretfile, Vault policies, and inline AWS roles""" if not os.path.exists(directory) and not os.path.isdir(directory): os.mkdir(directory) a_secretfile = render_secretfile(opt) s_path = "%s/Secretfile" % director...
Write a Python 3 script for rendering any provided template. This includes the Secretfile Vault policies and inline AWS roles.
You are a Python code generator, capable of creating scripts from specifications.
Export contents of a Secretfile from the Vault server into a specified directory.
Can you generate the documentation for the following Python 3 function def export(vault_client, opt): ctx = Context.load(get_secretfile(opt), opt) \ .fetch(vault_client) for resource in ctx.resources(): resource.export(opt.directory)
As a Python code composer, you craft elegant and concise scripts.
def normalize_val(val): """Normalize JSON/YAML derived values as they pertain to Vault resources and comparison operations """ if is_unicode(val) and val.isdigit(): return int(val) elif isinstance(val, list): return ','.join(val) elif val is None: return '' return val
How would you implement a function in Python 3 that normalizes JSON or YAML derived values as they pertain to Vault resources and comparison operations
As a Python code translator, you convert algorithms and pseudocode into Python.
Output the changes if any for a dict
Make a summary of the following Python 3 code def details_dict(obj, existing, ignore_missing, opt): existing = dict_unicodeize(existing) obj = dict_unicodeize(obj) for ex_k, ex_v in iteritems(existing): new_value = normalize_val(obj.get(ex_k)) og_value = normalize_val(ex_v) if ex_k i...
As a Python code translator, you convert algorithms and pseudocode into Python.
def maybe_details(resource, opt): """At the first level of verbosity this will print out detailed change information on for the specified Vault resource""" if opt.verbose == 0: return if not resource.present: return obj = None existing = None if isinstance(resource, Resour...
Can you create a Python 3 function that prints out detailed version of the specified Vault resource
As a Python code analyst, you investigate and solve complex coding mysteries
Handle the diff action for a single thing
Explain what the following Python 3 code does def diff_a_thing(thing, opt): changed = thing.diff() if changed == ADD: print("%s %s" % (maybe_colored("+", "green", opt), str(thing))) elif changed == DEL: print("%s %s" % (maybe_colored("-", "red", opt), str(thing))) elif changed == CHANGED...
As a Python code translator, you convert algorithms and pseudocode into Python.
Derive a comparison between what is represented in the Secretfile and what is actually live on a Vault instance
Given the following Python 3 function, write the documentation def diff(vault_client, opt): if opt.thaw_from: opt.secrets = tempfile.mkdtemp('aomi-thaw') auto_thaw(vault_client, opt) ctx = Context.load(get_secretfile(opt), opt) \ .fetch(vault_client) for backend in ctx.mou...
You are a Python code generator, capable of creating scripts from specifications.
def help_me(parser, opt): """Handle display of help and whatever diagnostics""" print("aomi v%s" % version) print('Get started with aomi' ' https://autodesk.github.io/aomi/quickstart') if opt.verbose == 2: tf_str = 'Token File,' if token_file() else '' app_str = 'AppID File,' i...
Implement a Python 3 function for handling display of help and whatever diagnostics
As a Python code analyst, you investigate and solve complex coding mysteries
Add the command line options for the extract_file operation
Can you generate the documentation for the following Python 3 function def extract_file_args(subparsers): extract_parser = subparsers.add_parser('extract_file', help='Extract a single secret from' 'Vault to a local file') extr...
You are a Python code architect, reviewing and designing scalable and efficient code