output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Check user permissions. :return: ``True`` if the identity is allowed the permission, else return ``False``.
Can you tell what is the following Python 3 function doing async def can(self, identity, permission) -> bool: assert isinstance(permission, (str, enum.Enum)), permission assert permission identify = await self.identity_policy.identify(identity) # non-registered user still may has some pe...
As a Python code translator, you convert algorithms and pseudocode into Python.
Checks if the identity is authorized.
How would you explain what the following Python 3 function does async def check_authorized(self, identity): identify = await self.identify(identity) if identify is None: raise UnauthorizedError() return identify
You are a Python code analyst, evaluating scripts for potential improvements.
Checks if the identity has the permission.
How would you explain what the following Python 3 function does async def check_permission(self, identity, permission): await self.check_authorized(identity) allowed = await self.can(identity, permission) if not allowed: raise ForbiddenError()
As a python code expert, you are capable of creating scripts from specifications.
Pulls in command line arguments.
Can you generate the documentation for the following Python 3 function def arguments(): DESCRIPTION = """\ """ parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=Raw) parser.add_argument("--email", dest="email", action='store', required=False, default=False, ...
You are a Python code analyst, evaluating scripts for potential improvements.
def run(self, *nodes): """Execute benchmarks on every node specified in arguments. If none are given, then execute benchmarks on every nodes specified in the ``network.nodes`` campaign configuration. """ nodes = nodes or self.nodes self._prelude(*nodes) @write_ya...
How would you code a function in Python 3 to execute benchmarks on every node specified in arguments.
As a python code expert, you are capable of creating scripts from specifications.
def run(self): """Execute benchmark on the specified node """ with self._scp_bensh_runner(): self._execute_bensh_runner() path = self._retrieve_tarball() try: self._aggregate_tarball(path) finally: os.remove(path)
Write a Python 3 script for executing benchmark on the specified node
You are a Python code analyst, evaluating scripts for potential improvements.
def node_pairing(self): """if "node" then test current node and next one if "tag", then create tests for every pair of the current tag. """ value = self.attributes['node_pairing'] if value not in IMB.NODE_PAIRING: msg = 'Unexpected {0} value: got "{1}" but valid value...
Implement a function in Python 3 to get the node pairing attribute of the current tag.
As a python code expert, you are capable of creating scripts from specifications.
Write a valid gentoo make. conf file to the given path.
Explain what the following Python 3 code does def write_makeconfig(_path): http_proxy = str(CFG["gentoo"]["http_proxy"]) ftp_proxy = str(CFG["gentoo"]["ftp_proxy"]) rsync_proxy = str(CFG["gentoo"]["rsync_proxy"]) path.mkfile_uchroot(local.path('/') / _path) with open(_path, 'w') as makeconf: ...
As a Python code analyst, you investigate and solve complex coding mysteries
Write a valid gentoo bashrc file to the path.
Explain what the following Python 3 code does def write_bashrc(_path): cfg_mounts = CFG["container"]["mounts"].value cfg_prefix = CFG["container"]["prefixes"].value path.mkfile_uchroot("/etc/portage/bashrc") mounts = uchroot.mounts("mnt", cfg_mounts) p_paths, p_libs = uchroot.env(cfg_prefix) pa...
As a Python code composer, you craft elegant and concise scripts.
def write_layout(_path): """ Write a valid gentoo layout file to :path:. Args: path - The output path of the layout.conf """ path.mkdir_uchroot("/etc/portage/metadata") path.mkfile_uchroot("/etc/portage/metadata/layout.conf") with open(_path, 'w') as layoutconf: lines = '''...
Write a Python 3 function for writing a valid gentoo layout file to the path.
As a Python code translator, you convert algorithms and pseudocode into Python.
def write_wgetrc(_path): """ Write a valid gentoo wgetrc file to :path:. Args: path - The output path of the wgetrc """ http_proxy = str(CFG["gentoo"]["http_proxy"]) ftp_proxy = str(CFG["gentoo"]["ftp_proxy"]) path.mkfile_uchroot("/etc/wgetrc") with open(_path, 'w') as wgetrc: ...
Write a Python 3 function for writing a valid gentoo wgetrc file to the path.
As a python code expert, you are capable of creating scripts from specifications.
Setup benchbuild inside a container.
Here you have a function in Python 3, explain what it does def setup_benchbuild(): LOG.debug("Setting up Benchbuild...") venv_dir = local.path("/benchbuild") prefixes = CFG["container"]["prefixes"].value prefixes.append(venv_dir) CFG["container"]["prefixes"] = prefixes src_dir = str(CFG["sourc...
As a python code expert, you are capable of creating scripts from specifications.
ben - elastic entry point
How would you explain what the following Python 3 function does def main(argv=None): arguments = cli_common(__doc__, argv=argv) es_export = ESExporter(arguments['CAMPAIGN-DIR'], arguments['--es']) es_export.export() if argv is not None: return es_export
You are a Python code architect, reviewing and designing scalable and efficient code
def name(self, value): """ Setter for **self.__name** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format("name", value) self._...
Create a Python 3 function to set the name of the object.
As a Python code translator, you convert algorithms and pseudocode into Python.
Setter for **self. __activated** attribute.
How would you explain what the following Python 3 function does def activated(self, value): if value is not None: assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("activated", value) self.component_activated.emit() if value else self.component_deactivated....
As a Python code translator, you convert algorithms and pseudocode into Python.
Setter for **self. __initialized** attribute.
How would you explain what the following Python 3 function does def initialized(self, value): if value is not None: assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("initialized", value) self.component_initialized.emit() if value else self.component_uninit...
You are a Python code generator, capable of creating scripts from specifications.
Sets the value of the .
Can you tell what is the following Python 3 function doing def deactivatable(self, value): if value is not None: assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("deactivatable", value) self.__deactivatable = value
As a Python code analyst, you investigate and solve complex coding mysteries
This method handles the main route of the CTS API.
Can you generate a brief explanation for the following Python 3 code def r_cts(self): _request = request.args.get("request", None) if _request is not None: try: if _request.lower() == "getcapabilities": return self._get_capabilities( ...
As a Python code analyst, you investigate and solve complex coding mysteries
Create a CTS Error Response
Make a summary of the following Python 3 code def cts_error(self, error_name, message=None): self.nautilus_extension.logger.info( "CTS error thrown {} for {} ({})".format( error_name, request.query_string.decode(), message) ) return ren...
You are a Python code architect, reviewing and designing scalable and efficient code
Provisional route for GetCapabilities request
Given the following Python 3 function, write the documentation def _get_capabilities(self, urn=None): r = self.resolver.getMetadata(objectId=urn) if len(r.parents) > 0: r = r.parents[-1] r = render_template( "cts/GetCapabilities.xml", filters="urn={}".format(u...
You are a Python code generator, capable of creating scripts from specifications.
Provisional route for GetFirstUrn request
Explain what the following Python 3 code does def _get_first_urn(self, urn): urn = URN(urn) subreference = None textId = urn.upTo(URN.NO_PASSAGE) if urn.reference is not None: subreference = str(urn.reference) firstId = self.resolver.getTextualNode(textId=textId, subr...
You are a Python code analyst, evaluating scripts for potential improvements.
Yields events from the internal libinput s queue.
Can you generate the documentation for the following Python 3 function def events(self): while True: events = self._selector.select() for nevent in range(len(events) + 1): self._libinput.libinput_dispatch(self._li) hevent = self._libinput.libinput_get_event(self._li) if hevent: type_ = self._l...
As a Python code composer, you craft elegant and concise scripts.
def next_event_type(self): """Return the type of the next event in the internal queue. This method does not pop the event off the queue and the next call to :attr:`events` returns that event. Returns: ~libinput.constant.EventType: The event type of the next available event or :obj:`None` if no event is ...
Can you create a Python 3 function that returns the type of the next available event in the internal queue.
You are a Python code generator, capable of creating scripts from specifications.
Adds a device to a libinput context.
Make a summary of the following Python 3 code def add_device(self, path): hdevice = self._libinput.libinput_path_add_device( self._li, path.encode()) if hdevice: return Device(hdevice, self._libinput) return None
As a Python code analyst, you investigate and solve complex coding mysteries
Assign a seat to this libinput context.
How would you explain what the following Python 3 function does def assign_seat(self, seat): rc = self._libinput.libinput_udev_assign_seat(self._li, seat.encode()) assert rc == 0, 'Failed to assign {}'.format(seat)
You are a Python code generator, capable of creating scripts from specifications.
Setup instance to extract metrics from the proper run directory.
Can you tell what is the following Python 3 function doing def context(self, outdir, log_prefix): try: self._outdir = outdir self._log_prefix = log_prefix yield finally: self._log_prefix = None self._outdir = None
You are a Python code generator, capable of creating scripts from specifications.
Get a Benchmark class by name
Can you generate the documentation for the following Python 3 function def get_subclass(cls, name): for subclass in cls.__subclasses__(): if subclass.name == name: return subclass raise NameError("Not a valid Benchmark class: " + name)
As a Python code composer, you craft elegant and concise scripts.
def auto_detect_adjacent_shapes(svg_source, shape_i_attr='id', layer_name='Connections', shapes_xpath='//svg:path | //svg:polygon', extend=1.5): ''' Attempt to automatically find "adjacent" shapes in a SVG layer. ...
How would you implement a function in Python 3 that attempts to automatically find "adjacent" shapes in a SVG layer. In a layer within a new SVG document, draw each detected connection between the center points of the corresponding shapes. Parameters ---------- svg_source : str Input SVG file as a filepath (or file-lik...
As a Python code analyst, you investigate and solve complex coding mysteries
def flatten_dict(dic, parent_key='', sep='.'): """Flatten sub-keys of a dictionary """ items = [] for key, value in dic.items(): new_key = parent_key + sep + key if parent_key else key if isinstance(value, collections.MutableMapping): items.extend(flatten_dict(value, new_key,...
Write a Python 3 function for flattening a dictionary into a single dictionary.
You are a Python code architect, reviewing and designing scalable and efficient code
Recursive dict merge. Inspired by dict. update.
Here you have a function in Python 3, explain what it does def dict_merge(dct, merge_dct): for key in merge_dct.keys(): if ( key in dct and isinstance(dct[key], dict) and isinstance(merge_dct[key], collections.Mapping) ): dict_merge(dct[key], merge_dct...
As a Python code composer, you craft elegant and concise scripts.
def freeze(obj): """Transform tree of dict and list in read-only data structure. dict instances are transformed to FrozenDict, lists in FrozenList. """ if isinstance(obj, collections.Mapping): return FrozenDict({freeze(k): freeze(v) for k, v in six.iteritems(obj)}) elif isinstance(ob...
Implement a Python 3 function for transforming tree of dict and list in read - only data structure.
You are a Python code generator, capable of creating scripts from specifications.
def from_file(cls, path): """Create a ``Configuration`` from a file :param path: path to YAML file :return: new configuration :rtype: ``Configuration`` """ if path == '-': return Configuration(yaml.safe_load(sys.stdin)) if not osp.exists(path) and not...
Can you write a function in Python 3 where it creates a Configuration from a YAML file.
You are a Python code generator, capable of creating scripts from specifications.
def hex_color_to_rgba(hex_color, normalize_to=255): ''' Convert a hex-formatted number (i.e., `"#RGB[A]"` or `"#RRGGBB[AA]"`) to an RGBA tuple (i.e., `(<r>, <g>, <b>, <a>)`). Args: hex_color (str) : hex-formatted number (e.g., `"#2fc"`, `"#3c2f8611"`) normalize_to (int, float) : Factor...
Write a Python 3 script for converting a hex - formatted number to an anatomical color tuple.
As a python code expert, you are capable of creating scripts from specifications.
def split_term(cls, term): """ Split a term in to parent and record term components :param term: combined term text :return: Tuple of parent and record term """ if '.' in term: parent_term, record_term = term.split('.') parent_term, record_term = ...
Can you implement a function in Python 3 that splits a term into parent and record term components
You are a Python code analyst, evaluating scripts for potential improvements.
Like split_term but also lowercases both parent and record term
Given the following Python 3 function, write the documentation def split_term_lower(cls, term): return tuple(e.lower() for e in Term.split_term(term))
You are a Python code analyst, evaluating scripts for potential improvements.
def file_ref(self): """Return a string for the file, row and column of the term.""" from metatab.util import slugify assert self.file_name is None or isinstance(self.file_name, str) if self.file_name is not None and self.row is not None: parts = split(self.file_name); ...
Can you create a Python 3 function that returns a string for the file row and column of the term.
As a Python code analyst, you investigate and solve complex coding mysteries
def add_child(self, child): """Add a term to this term's children. Also sets the child term's parent""" assert isinstance(child, Term) self.children.append(child) child.parent = self assert not child.term_is("Datafile.Section")
Implement a function in Python 3 to add a term to this term s children. Also sets the child term s parent.
As a Python code analyst, you investigate and solve complex coding mysteries
def new_child(self, term, value, **kwargs): """Create a new term and add it to this term as a child. Creates grandchildren from the kwargs. :param term: term name. Just the record term :param term: Value to assign to the term :param term: Term properties, which create children of the ch...
Can you create a Python 3 function that creates a new term and add it to this term as a child.
You are a Python code analyst, evaluating scripts for potential improvements.
Removes the term from this term s children.
Can you generate a brief explanation for the following Python 3 code def remove_child(self, child): assert isinstance(child, Term) self.children.remove(child) self.doc.remove_term(child)
You are a Python code architect, reviewing and designing scalable and efficient code
Create new children from kwargs
Can you tell what is the following Python 3 function doing def new_children(self, **kwargs): for k, v in kwargs.items(): self.new_child(k, v) return self
As a Python code analyst, you investigate and solve complex coding mysteries
Recursivelt set the parent section and doc for a children
Given the following Python 3 function, write the documentation def set_ownership(self): assert self.section is not None for t in self.children: t.parent = self t._section = self.section t.doc = self.doc t.set_ownership()
You are a Python code generator, capable of creating scripts from specifications.
Return a list of terms by name.
Can you tell what is the following Python 3 function doing def find(self, term, value=False): if '.' in term: parent, term = term.split('.') assert parent.lower() == self.record_term_lc, (parent.lower(), self.record_term_lc) for c in self.children: if c.record_term_l...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_or_new_child(self, term, value=False, **kwargs): """Find a term, using find_first, and set it's value and properties, if it exists. If it does not, create a new term and children. """ pt, rt = self.split_term(term) term = self.record_term + '.' + rt c = self.find_first...
How would you code a function in Python 3 to find a term using find_first and set it s value and properties and create a new child term. If it does not exist create a new child term.
As a Python code analyst, you investigate and solve complex coding mysteries
Get the value of a child
Can you tell what is the following Python 3 function doing def get_value(self, item, default=None): try: return self[item].value except (AttributeError, KeyError) as e: return default
As a Python code translator, you convert algorithms and pseudocode into Python.
def qualified_term(self): """Return the fully qualified term name. The parent will be 'root' if there is no parent term defined. """ assert self.parent is not None or self.parent_term_lc == 'root' if self.parent: return self.parent.record_term_lc + '.' + self.record_term_lc ...
Implement a function in Python 3 to return the fully qualified term name.
As a Python code translator, you convert algorithms and pseudocode into Python.
Return True if the fully qualified name of the term is the same as the argument.
How would you explain what the following Python 3 function does def term_is(self, v): if isinstance(v, str): if '.' not in v: v = 'root.' + v v_p, v_r = self.split_term_lower(v) if self.join_lc == v.lower(): return True elif v_r...
You are a Python code analyst, evaluating scripts for potential improvements.
Return the value and scalar properties as a dictionary. Returns only the value and scalar properties declared on the same row as a term. Returns only the value and scalar properties declared on the same row as a term.
Given the following Python 3 function, write the documentation def arg_props(self): d = dict(zip([str(e).lower() for e in self.section.property_names], self.args)) # print({ c.record_term_lc:c.value for c in self.children}) d[self.term_value_name.lower()] = self.value return d
As a python code expert, you are capable of creating scripts from specifications.
Returns a dictionary with the values of all children and place holders for all of the section argumemts. It combines arg_props with props
How would you explain what the following Python 3 function does def all_props(self): d = self.arg_props d.update(self.props) return d
As a python code expert, you are capable of creating scripts from specifications.
Converts a record heirarchy to nested dicts.
Can you generate the documentation for the following Python 3 function def _convert_to_dict(cls, term, replace_value_names=True): from collections import OrderedDict if not term: return None if term.children: d = OrderedDict() for c in term.children: ...
As a Python code composer, you craft elegant and concise scripts.
def rows(self): """Yield rows for the term, for writing terms to a CSV file. """ # Translate the term value name so it can be assigned to a parameter. tvm = self.section.doc.decl_terms.get(self.qualified_term, {}).get('termvaluename', '@value') assert tvm # Terminal children hav...
Create a Python 3 function for yielding the rows for the term for writing terms to a CSV file.
As a Python code translator, you convert algorithms and pseudocode into Python.
Iterate over all descendent terms
Given the following Python 3 function, write the documentation def descendents(self): for c in self.children: yield c for d in c.descendents: yield d
As a Python code translator, you convert algorithms and pseudocode into Python.
Change a term into a Section Term
Explain what the following Python 3 code does def subclass(cls, t): t.doc = None t.terms = [] t.__class__ = SectionTerm return t
As a Python code translator, you convert algorithms and pseudocode into Python.
Append an arg to the arg list
How would you explain what the following Python 3 function does def add_arg(self,arg, prepend=False): self.args = [arg_.strip() for arg_ in self.args if arg_.strip()] if arg.title() not in self.args: if prepend: self.args = [arg.title()] + self.args else: ...
As a python code expert, you are capable of creating scripts from specifications.
Remove an arg from the arg list
Explain what the following Python 3 code does def remove_arg(self, arg): self.args = [arg_.strip() for arg_ in self.args if arg_.strip()] for arg_ in list(self.args): if arg_.lower() == arg.lower(): self.args.remove(arg_)
You are a Python code architect, reviewing and designing scalable and efficient code
Add a term to this section and set it s ownership. Should only be used on root level terms
Can you tell what is the following Python 3 function doing def add_term(self, t): if t not in self.terms: if t.parent_term_lc == 'root': self.terms.append(t) self.doc.add_term(t, add_section=False) t.set_ownership() else: ...
You are a Python code analyst, evaluating scripts for potential improvements.
Create a new root - level term in this section
Can you generate a brief explanation for the following Python 3 code def new_term(self, term, value, **kwargs): tc = self.doc.get_term_class(term.lower()) t = tc(term, value, doc=self.doc, parent=None, section=self).new_children(**kwargs) self.doc.add_term(t) return t
You are a Python code architect, reviewing and designing scalable and efficient code
def set_terms(self,*terms, **kw_terms): """ Create or set top level terms in the section. After python 3.6.0, the terms entries should maintain the same order as the argument list. The term arguments can have any of these forms: * For position argument, a Term object * For kw ar...
Implement a function in Python 3 to create or set top level terms in the section.
As a Python code composer, you craft elegant and concise scripts.
Remove a term from the terms. Must be the identical term the same object.
Can you generate the documentation for the following Python 3 function def remove_term(self, term, remove_from_doc=True): try: self.terms.remove(term) except ValueError: pass if remove_from_doc: self.doc.remove_term(term)
You are a Python code generator, capable of creating scripts from specifications.
Remove all of the terms from the section and also remove them from the document
Given the following Python 3 function, write the documentation def clean(self): terms = list(self) for t in terms: self.doc.remove_term(t)
As a python code expert, you are capable of creating scripts from specifications.
def sort_by_term(self, order=None): """ Sort the terms in the section. :param order: If specified, a list of qualified, lowercased term names. These names will appear first in the section, and the remaining terms will be sorted alphabetically. If not specified, all terms are alph...
How would you code a function in Python 3 to sort the terms in the section.
You are a Python code analyst, evaluating scripts for potential improvements.
Extract the chldren of a term that are arg - children from those that are row - children.
Make a summary of the following Python 3 code def _args(self, term, d): # Get the term value name, the property name that should be assigned to the term value. tvm = self.doc.decl_terms.get(term, {}).get('termvaluename', '@value') # Convert the keys to lower case lower_d = {k.lower():...
As a Python code analyst, you investigate and solve complex coding mysteries
def rows(self): """Yield rows for the section""" for t in self.terms: for row in t.rows: term, value = row # Value can either be a string, or a dict if isinstance(value, dict): # Dict is for properties, which might be arg-children term,...
Create a Python 3 function to yield the rows for the section
You are a Python code architect, reviewing and designing scalable and efficient code
def lines(self): """Iterate over all of the rows as text lines""" # Yield the section header if self.name != 'Root': yield ('Section', '|'.join([self.value] + self.property_names)) # Yield all of the rows for terms in the section for row in self.rows: te...
How would you code a function in Python 3 to iterate over all of the rows as text lines
As a Python code composer, you craft elegant and concise scripts.
def as_dict(self, replace_value_names=True): """Return the whole section as a dict""" old_children = self.children self.children = self.terms d = super(SectionTerm, self).as_dict(replace_value_names) self.children = old_children return d
Write a Python 3 script to return the whole section as a dict
You are a Python code architect, reviewing and designing scalable and efficient code
Find a suitable C compiler and return its name path and vendor.
Can you tell what is the following Python 3 function doing def find_compiler(cls, preferred_vendor, metadir, cwd, use_meta=True): """ Identify a suitable C/fortran/other compiler When it is possible that the user (un)installs a compiler inbetween compilations of ob...
As a Python code analyst, you investigate and solve complex coding mysteries
def cmd(self): """ The command below covers most cases, if you need someting more complex subclass this. """ cmd = ( [self.compiler_binary] + self.flags + ['-U'+x for x in self.undef] + ['-D'+x for x in self.define] + ['...
Write a Python 3 function that can return the command to run this module.
As a Python code translator, you convert algorithms and pseudocode into Python.
def drawLine(self, x1, y1, x2, y2, silent=False): """ Draws a line on the current :py:class:`Layer` with the current :py:class:`Brush`. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param x1: Starting X coordinate. :param y1: Starting Y coordinate. :param x2: End X coor...
Create a Python 3 function for drawing a line on the current layer with the current brush.
You are a Python code analyst, evaluating scripts for potential improvements.
Draws a point on the current layer with the current brush.
Make a summary of the following Python 3 code def drawPoint(self, x, y, silent=True): start = time.time() #Downsample the coordinates x = int(x/config.DOWNSAMPLING) y = int(y/config.DOWNSAMPLING) #Apply the dab with or without source caching if self.brush.usesSourceCaching: applyMirroredDab_jit(self.mi...
As a Python code composer, you craft elegant and concise scripts.
def drawPath(self, pointList): """ Draws a series of lines on the current :py:class:`Layer` with the current :py:class:`Brush`. No interpolation is applied to these point and :py:meth:`drawLine` will be used to connect all the points lineraly. Coordinates are relative to the original layer size WITHOUT downsamp...
Can you create a Python 3 function that draws a series of lines on the current layer with the current brush.
As a Python code translator, you convert algorithms and pseudocode into Python.
Draws a closed series of lines on the current layer with the current brush.
Explain what the following Python 3 code does def drawClosedPath(self, pointList): self.drawLine(pointList[0][0], pointList[0][1], pointList[1][0], pointList[1][1]) i = 1 while i<len(pointList)-1: self.drawLine(pointList[i][0], pointList[i][1], pointList[i+1][0], pointList[i+1][1]) i+=1 self.drawLine(poin...
As a python code expert, you are capable of creating scripts from specifications.
Draws a rectangle on the current layer with the current brush.
Explain what the following Python 3 code does def drawRect(self, x1, y1, x2, y2, angle=0): vertices = [[x1,y1],[x2,y1],[x2,y2],[x1,y2],] rotatedVertices = rotateMatrix(vertices, (x1+x2)*0.5, (y1+y2)*0.5, angle) self.drawClosedPath(rotatedVertices)
You are a Python code architect, reviewing and designing scalable and efficient code
Fills the current layer with the current color.
How would you explain what the following Python 3 function does def fillLayerWithColor(self, color): layer = self.image.getActiveLayer().data colorRGBA = color.get_0_255() layer[:,:,0] = colorRGBA[0] layer[:,:,1] = colorRGBA[1] layer[:,:,2] = colorRGBA[2] layer[:,:,3] = colorRGBA[3]
As a python code expert, you are capable of creating scripts from specifications.
def addBorder(self, width, color=None): """ Add a border to the current :py:class:`Layer`. :param width: The width of the border. :param color: The :py:class:`Color` of the border, current :py:class:`Color` is the default value. :rtype: Nothing. """ width = int(width/config.DOWNSAMPLING) if color==No...
How would you code a function in Python 3 to add a border to the current layer.
As a Python code translator, you convert algorithms and pseudocode into Python.
def setColor(self, color): """ Sets the current :py:class:`Color` to use. :param color: The :py:class:`Color` to use. :rtype: Nothing. """ self.color = color if self.brush and self.brush.doesUseSourceCaching(): self.brush.cacheBrush(color)
Write a Python 3 script for setting the current color to use.
As a Python code analyst, you investigate and solve complex coding mysteries
Change the alpha of the current color.
Make a summary of the following Python 3 code def setColorAlpha(self, fixed=None, proportional=None): if fixed!=None: self.color.set_alpha(fixed) elif proportional!=None: self.color.set_alpha(self.color.get_alpha()*proportional)
As a Python code composer, you craft elegant and concise scripts.
Swaps the current Color with the secondary Color.
Make a summary of the following Python 3 code def swapColors(self): rgba = self.color.get_0_255() self.color = self.secondColor self.secondColor = Color(rgba, '0-255')
As a python code expert, you are capable of creating scripts from specifications.
def setBrush(self, b, resize=0, proportional=None): """ Sets the size of the current :py:class:`Brush`. :param brush: The :py:class:`Brush` object to use as a brush. :param resize: An optional absolute value to resize the brush before using it. :param proportional: An optional relative float 0-1 value to r...
How would you code a function in Python 3 to set the size of the current brush.
As a python code expert, you are capable of creating scripts from specifications.
Sets the mirror mode for this object.
Here you have a function in Python 3, explain what it does def setMirrorMode(self, mirror): assert (mirror=='' or mirror=='h' or mirror=='v' or mirror=='hv'or mirror=='vh'), 'setMirrorMode: wrong mirror mode, got '+str(mirror)+' expected one of ["","h","v","hv"]' #Round up all the coordinates and convert them to...
You are a Python code generator, capable of creating scripts from specifications.
def renderImage(self, output='', show=True): """ Renders the :py:class:`Image` and outputs the final PNG file. :param output: A string with the output file path, can be empty if you don't want to save the final image. :param show: A boolean telling the system to display the final image after the rendering is...
Write a Python 3 function that can render the Image and outputs the final PNG file.
You are a Python code generator, capable of creating scripts from specifications.
def setActiveLayerEffect(self, effect): """ Changes the effect of the current active :py:class:`Layer`. :param output: A string with the one of the blend modes listed in :py:meth:`newLayer`. :rtype: Nothing. """ self.image.layers[self.image.activeLayer].effect = effect
Create a Python 3 function to change the effect of the current active layer.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_hash_of_dirs(directory): """ Recursively hash the contents of the given directory. Args: directory (str): The root directory we want to hash. Returns: A hash of all the contents in the directory. """ import hashlib sha = hashlib.sha512() if not os.path.exists(di...
Create a Python 3 function for returning the hash of all the contents of the given directory.
As a Python code composer, you craft elegant and concise scripts.
Check if a download is required.
Make a summary of the following Python 3 code def source_required(src_file): if not src_file.exists(): return True required = True hash_file = src_file.with_suffix(".hash", depth=0) LOG.debug("Hash file location: %s", hash_file) if hash_file.exists(): new_hash = get_hash_of_dirs(src...
You are a Python code architect, reviewing and designing scalable and efficient code
def update_hash(src_file): """ Update the hash for the given file. Args: src: The file name. root: The path of the given file. """ hash_file = local.path(src_file) + ".hash" new_hash = 0 with open(hash_file, 'w') as h_file: new_hash = get_hash_of_dirs(src_file) ...
Can you create a Python 3 function that updates the hash for the given file.
As a Python code translator, you convert algorithms and pseudocode into Python.
Small copy wrapper. Args: From (str): Path to the SOURCE. To (str): Path to the TARGET.
Can you generate the documentation for the following Python 3 function def Copy(From, To): from benchbuild.utils.cmd import cp cp("-ar", "--reflink=auto", From, To)
You are a Python code generator, capable of creating scripts from specifications.
def CopyNoFail(src, root=None): """ Just copy fName into the current working directory, if it exists. No action is executed, if fName does not exist. No Hash is checked. Args: src: The filename we want to copy to '.'. root: The optional source dir we should pull fName from. Defaults ...
How would you implement a function in Python 3 that copies a file into the current working directory.
As a python code expert, you are capable of creating scripts from specifications.
def Wget(src_url, tgt_name, tgt_root=None): """ Download url, if required. Args: src_url (str): Our SOURCE url. tgt_name (str): The filename we want to have on disk. tgt_root (str): The TARGET directory for the download. Defaults to ``CFG["tmpdir"]``. """ if tgt_...
Implement a Python 3 function for downloading a file from a URL and update the hash of it.
As a Python code translator, you convert algorithms and pseudocode into Python.
def with_wget(url_dict=None, target_file=None): """ Decorate a project class with wget-based version information. This adds two attributes to a project class: - A `versions` method that returns a list of available versions for this project. - A `repository` attribute that provides...
Can you implement a function in Python 3 that decorates a project class with wget-based version information. This adds two attributes to a project class: - A `versions` method that returns a list of available versions for this project. - A `repository` attribute that provides a repository string to download from later....
As a python code expert, you are capable of creating scripts from specifications.
Get a clone of the given git repo.
Can you tell what is the following Python 3 function doing def Git(repository, directory, rev=None, prefix=None, shallow_clone=True): repository_loc = str(prefix) if prefix is None: repository_loc = str(CFG["tmp_dir"]) from benchbuild.utils.cmd import git src_dir = local.path(repository_loc) /...
You are a Python code generator, capable of creating scripts from specifications.
Decorator for creating a new project class with git - based version information.
How would you explain what the following Python 3 function does def with_git(repo, target_dir=None, limit=None, refspec="HEAD", clone=True, rev_list_args=None, version_filter=lambda version: True): """ Decorate a project class with gi...
You are a Python code generator, capable of creating scripts from specifications.
RSync a folder. Args: url (str): The url of the SOURCE location. fname (str): The name of the TARGET. to (str): Path of the target location. Defaults to ``CFG["tmpdir"]``.
Can you generate a brief explanation for the following Python 3 code def Rsync(url, tgt_name, tgt_root=None): if tgt_root is None: tgt_root = str(CFG["tmp_dir"]) from benchbuild.utils.cmd import rsync tgt_dir = local.path(tgt_root) / tgt_name if not source_required(tgt_dir): Copy(tgt_d...
You are a Python code generator, capable of creating scripts from specifications.
def camel_to_snake(s: str) -> str: """Convert string from camel case to snake case.""" return CAMEL_CASE_RE.sub(r'_\1', s).strip().lower()
Implement a Python 3 function for converting string from camel case to snake case.
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert string from snake case to camel case.
Make a summary of the following Python 3 code def snake_to_camel(s: str) -> str: fragments = s.split('_') return fragments[0] + ''.join(x.title() for x in fragments[1:])
As a Python code analyst, you investigate and solve complex coding mysteries
def _create_extractors(cls, metrics): """Build metrics extractors according to the `metrics` config :param metrics: Benchmark `metrics` configuration section """ metrics_dict = {} # group entries by `category` attribute (default is "standard") for metric, config in six.i...
Create a Python 3 function to build metrics extractors according to the metrics section
As a python code expert, you are capable of creating scripts from specifications.
Returns a dictionary of metrics extracted by this class
How would you explain what the following Python 3 function does def metrics(self): return dict( (name, getattr(Metrics, config['type'])) for name, config in six.iteritems(self._metrics) )
You are a Python code analyst, evaluating scripts for potential improvements.
Group metrics according to the from property.
Here you have a function in Python 3, explain what it does def froms(self): eax = {} for name, config in six.iteritems(self._metrics): from_ = self._get_property(config, 'from', default=self.stdout) eax.setdefault(from_, {})[name] = config return eax
As a Python code composer, you craft elegant and concise scripts.
Tesselate each shape path into one or more triangles.
Can you generate the documentation for the following Python 3 function def tesselate_shapes_frame(df_shapes, shape_i_columns): ''' Tesselate each shape path into one or more triangles. Parameters ---------- df_shapes : pandas.DataFrame Table containing vertices of shapes, one row per vertex...
As a python code expert, you are capable of creating scripts from specifications.
Intercept standard output in a with - context
Can you tell what is the following Python 3 function doing def capture_stdout(): stdout = sys.stdout sys.stdout = six.moves.cStringIO() try: yield sys.stdout finally: sys.stdout = stdout
You are a Python code architect, reviewing and designing scalable and efficient code
def pushd(path, mkdir=True, cleanup=False): """Change current working directory in a with-context :param mkdir: If True, then directory is created if it does not exist :param cleanup: If True and no pre-existing directory, the directory is cleaned up at the end """ cwd = os.getcwd() exists =...
How would you implement a function in Python 3 that changes current working directory in a with-context :param mkdir: If True, then directory is created if it does not exist :param cleanup: If True and no pre-existing directory, the directory is cleaned up at the end
As a Python code composer, you craft elegant and concise scripts.
def mkdtemp(*args, **kwargs): """Create a temporary directory in a with-context keyword remove: Remove the directory when leaving the context if True. Default is True. other keywords arguments are given to the tempfile.mkdtemp function. """ remove = kwargs.pop('remove', True) path = tem...
Create a Python 3 function to create a temporary directory in a with - context keyword arguments.
You are a Python code generator, capable of creating scripts from specifications.
Returns the amount of time spent in the context.
How would you explain what the following Python 3 function does def elapsed(self): if self.end is None: return self() - self.end return self.end - self.start
As a python code expert, you are capable of creating scripts from specifications.